目录
需求
使用图形化界面实现双人井字棋游戏
效果


代码实现
import tkinter as tk
from tkinter import messagebox
class TicTacToe:
def __init__(self, root):
self.root = root
self.root.title("井字游戏 (Tic-Tac-Toe)")
self.current_player = "X"
self.board = [""] * 9
self.buttons = []
for i in range(9):
button = tk.Button(root, text="", font=('normal', 40), width=5, height=2,
command=lambda i=i: self.on_button_click(i))
button.grid(row=i // 3, column=i % 3)
self.buttons.append(button)
def on_button_click(self, index):
if self.board[index] == "":
self.board[index] = self.current_player
self.buttons[index].config(text=self.current_player)
if self.check_winner():
messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
self.reset_board()
elif "" not in self.board:
messagebox.showinfo("游戏结束", "平局!")
self.reset_board()
else:
self.current_player = "O" if self.current_player == "X" else "X"
def check_winner(self):
win_conditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # 行
[0, 3, 6], [1, 4, 7], [2, 5, 8], # 列
[0, 4, 8], [2, 4, 6] # 对角线
]
for condition in win_conditions:
if self.board[condition[0]] == self.board[condition[1]] == self.board[condition[2]] != "":
return True
return False
def reset_board(self):
self.board = [""] * 9
for button in self.buttons:
button.config(text="")
self.current_player = "X"
if __name__ == "__main__":
root = tk.Tk()
game = TicTacToe(root)
root.mainloop()
解释代码
-
初始化界面:
- 创建主窗口并设置标题。
- 初始化当前玩家为 "X"。
- 创建一个长度为 9 的列表
board来存储棋盘的状态。 - 使用嵌套循环创建 9 个按钮,并将它们放置在网格布局中。每个按钮都绑定到
on_button_click方法。
-
按钮点击事件:
- 当按钮被点击时,检查该位置是否为空。
- 如果为空,则更新
board列表和按钮的文本。 - 检查是否有玩家获胜或棋盘已满(平局)。
- 如果游戏未结束,切换当前玩家。
-
检查胜利条件:
- 定义所有可能的胜利组合。
- 遍历这些组合,检查是否有玩家满足胜利条件。
-
重置棋盘:
- 将
board列表清空。 - 将所有按钮的文本清空。
- 将当前玩家重置为 "X"。
- 将
&spm=1001.2101.3001.5002&articleId=143960708&d=1&t=3&u=8cfb12eb72324654b98963aa6fdf1aaf)
4177

被折叠的 条评论
为什么被折叠?



