用python3写一个带界面的井字棋游戏然后优化简化代码并写出优化简化后的代码和改动了哪些地方
以下是一个简化且优化的Python3井字棋游戏代码示例:
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 = []
self.create_board()
def create_board(self):
for i in range(3):
row = []
for j in range(3):
button = tk.Button(self.root, text="", width=10, height=5,
command=lambda i=i, j=j: self.handle_click(i, j))
button.grid(row=i, column=j)
row.append(button)
self.buttons.append(row)
def handle_click(self, row, col):
if self.board[row][col] == "":
self.board[row][col] = self.current_player
self.buttons[row][col].config(text=self.current_player)
if self.check_winner(row, col):
messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
self.reset_game()
elif self.check_draw():
messagebox.showinfo("游戏结束", "平局!")
self.reset_game()
else:
self.switch_player()
def check_winner(self, row, col):
player = self.current_player
# 检查行
if self.board[row][0] == self.board[row][1] == self.board[row][2] == player:
return True
# 检查列
if self.board[0][col] == self.board[1][col] == self.board[2][col] == player:
return True
# 检查对角线
if row == col and self.board[0][0] == self.board[1][1] == self.board[2][2] == player:
return True
if row + col == 2 and self.board[0][2] == self.board[1][1] == self.board[2][0] == player:
return True
return False
def check_draw(self):
for row in self.board:
if "" in row:
return False
return True
def switch_player(self):
self.current_player = "O" if self.current_player == "X" else "X"
def reset_game(self):
self.current_player = "X"
self.board = [["" for _ in range(3)] for _ in range(3)]
for row in self.buttons:
for button in row:
button.config(text="")
if __name__ == "__main__":
root = tk.Tk()
game = TicTacToe(root)
root.mainloop()
对比原始代码,主要优化简化的地方有:
- 通过使用
self.buttons列表来保存按钮对象,而不是为每个按钮定义一个独立的变量。这样可以方便地通过row和col索引访问和修改按钮。 - 将按钮的点击处理函数中的匿名函数改为lambda表达式,以便传递按钮所在的行和列索引。
- 将检查获胜和平局的逻辑提取为独立的方法,使代码更加模块化和可读性更高。
- 重置游戏的逻辑也提取为独立的方法,使代码更清晰。
- 使用
messagebox模块来显示游戏结束的信息框
原文地址: https://www.cveoy.top/t/topic/h3Vc 著作权归作者所有。请勿转载和采集!