用Python编写一个带UI功能能对弈的小游戏
时间: 2023-11-16 10:09:19 浏览: 55
好的,我可以为您提供一个使用Python和Tkinter库编写的简单的井字棋游戏。以下是代码:
```python
import tkinter as tk
class TicTacToe:
def __init__(self, master):
self.master = master
self.master.title("Tic Tac Toe")
self.current_player = "X"
self.board = [""] * 9
self.create_widgets()
def create_widgets(self):
self.cells = []
for i in range(3):
for j in range(3):
cell = tk.Button(self.master, text="", font=("Arial", 50), width=4, height=2,
command=lambda i=i, j=j: self.play(i, j))
cell.grid(row=i, column=j)
self.cells.append(cell)
self.reset_button = tk.Button(self.master, text="Reset", font=("Arial", 20), command=self.reset)
self.reset_button.grid(row=3, column=1)
self.message_label = tk.Label(self.master, text="Current player: X", font=("Arial", 20))
self.message_label.grid(row=4, column=0, columnspan=3)
def play(self, row, col):
index = 3 * row + col
if self.board[index] or self.winner():
return
self.board[index] = self.current_player
self.cells[index].config(text=self.current_player)
if self.winner():
self.message_label.config(text=f"Winner: {self.current_player}")
elif "" not in self.board:
self.message_label.config(text="Draw")
else:
self.current_player = "O" if self.current_player == "X" else "X"
self.message_label.config(text=f"Current player: {self.current_player}")
def winner(self):
lines = [[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 line in lines:
if self.board[line[0]] == self.board[line[1]] == self.board[line[2]] != "":
return True
return False
def reset(self):
self.current_player = "X"
self.board = [""] * 9
for i in range(9):
self.cells[i].config(text="")
self.message_label.config(text="Current player: X")
root = tk.Tk()
game = TicTacToe(root)
root.mainloop()
```
这个程序创建了一个井字棋游戏界面,玩家可以点击空白的方格放置他们的棋子。游戏会检查是否有一方获胜或游戏结束,如果是,将显示相应的消息。玩家可以通过点击“重置”按钮来重新开始游戏。
这只是一个简单的例子,您可以根据需要进行修改和扩展。
阅读全文