井字棋
2026-01-06 21:07:58
发布于:浙江
使用Python语言编写,采用Tkinter、最小值算法,保证人机输不了
import tkinter as tk
from tkinter import messagebox
class TicTacToe:
def __init__(self, root):
self.root = root
self.root.title("井字棋")
self.current_player = "X"
self.board = [["" for _ in range(3)] for _ in range(3)]
self.buttons = [[None for _ in range(3)] for _ in range(3)]
for i in range(3):
for j in range(3):
button = tk.Button(root, text="", font=('normal', 24), width=5, height=2,
command=lambda row=i, col=j: self.on_button_click(row, col))
button.grid(row=i, column=j)
self.buttons[i][j] = button
def on_button_click(self, row, col):
if self.board[row][col] == "" and not self.check_winner():
self.board[row][col] = self.current_player
self.buttons[row][col].config(text=self.current_player)
if self.check_winner():
messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
self.reset_board()
elif all(cell != "" for row in self.board for cell in row):
messagebox.showinfo("游戏结束", "平局!")
self.reset_board()
else:
self.current_player = "O"
self.computer_move()
def computer_move(self):
best_score = float('-inf')
move = None
for i in range(3):
for j in range(3):
if self.board[i][j] == "":
self.board[i][j] = "O"
score = self.minimax(self.board, False)
self.board[i][j] = ""
if score > best_score:
best_score = score
move = (i, j)
if move:
row, col = move
self.board[row][col] = "O"
self.buttons[row][col].config(text="O")
if self.check_winner():
messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
self.reset_board()
elif all(cell != "" for row in self.board for cell in row):
messagebox.showinfo("游戏结束", "平局!")
self.reset_board()
else:
self.current_player = "X"
def minimax(self, board, is_maximizing):
if self.check_winner(board, "X"):
return -1
if self.check_winner(board, "O"):
return 1
if all(cell != "" for row in board for cell in row):
return 0
if is_maximizing:
best_score = float('-inf')
for i in range(3):
for j in range(3):
if board[i][j] == "":
board[i][j] = "O"
score = self.minimax(board, False)
board[i][j] = ""
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == "":
board[i][j] = "X"
score = self.minimax(board, True)
board[i][j] = ""
best_score = min(score, best_score)
return best_score
def check_winner(self, board=None, player=None):
if board is None:
board = self.board
if player is None:
player = self.current_player
# Check rows, columns, and diagonals for a winner
lines = board + \
list(zip(*board)) + \
[[board[i][i] for i in range(3)], [board[i][2 - i] for i in range(3)]]
return any(all(cell == player for cell in line) for line in lines)
def reset_board(self):
self.current_player = "X"
self.board = [["" for _ in range(3)] for _ in range(3)]
for i in range(3):
for j in range(3):
self.buttons[i][j].config(text="")
if __name__ == "__main__":
root = tk.Tk()
game = TicTacToe(root)
root.mainloop()
全部评论 1
orz
竟然不是爆搜一遍(((
昨天 来自 广东
0

















有帮助,赞一个