用Python的tkinter库帮我写一个五子棋游戏
时间: 2024-04-12 13:08:28 浏览: 117
好的,下面是一个简单的五子棋游戏代码,你可以根据自己的需求进行修改。
```python
import tkinter as tk
# 定义棋盘大小和棋子大小
BOARD_SIZE = 500
PIECE_SIZE = 20
class Board:
def __init__(self):
self.board = [[0 for _ in range(15)] for _ in range(15)]
self.current_player = 1
def play(self, x, y):
if self.board[x][y] == 0:
self.board[x][y] = self.current_player
self.current_player = 3 - self.current_player
return True
else:
return False
def get_board(self):
return self.board
class Game:
def __init__(self):
self.board = Board()
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, width=BOARD_SIZE, height=BOARD_SIZE)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.play)
def draw_board(self):
# 画棋盘
for i in range(15):
self.canvas.create_line(i * PIECE_SIZE, 0, i * PIECE_SIZE, BOARD_SIZE)
self.canvas.create_line(0, i * PIECE_SIZE, BOARD_SIZE, i * PIECE_SIZE)
def draw_piece(self, x, y):
# 画棋子
if self.board.current_player == 1:
color = "black"
else:
color = "white"
self.canvas.create_oval(x * PIECE_SIZE - PIECE_SIZE // 2,
y * PIECE_SIZE - PIECE_SIZE // 2,
x * PIECE_SIZE + PIECE_SIZE // 2,
y * PIECE_SIZE + PIECE_SIZE // 2,
fill=color, outline=color)
def play(self, event):
# 下棋
x = round(event.x / PIECE_SIZE)
y = round(event.y / PIECE_SIZE)
if self.board.play(x, y):
self.draw_piece(x, y)
self.check_win()
def check_win(self):
# 判断胜负
board = self.board.get_board()
for i in range(15):
for j in range(15):
if board[i][j] != 0:
if i <= 10 and board[i][j] == board[i + 1][j] == board[i + 2][j] == board[i + 3][j] == board[i + 4][j]:
self.game_over(board[i][j])
if j <= 10 and board[i][j] == board[i][j + 1] == board[i][j + 2] == board[i][j + 3] == board[i][j + 4]:
self.game_over(board[i][j])
if i <= 10 and j <= 10 and board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2] == board[i + 3][j + 3] == board[i + 4][j + 4]:
self.game_over(board[i][j])
if i <= 10 and j >= 4 and board[i][j] == board[i + 1][j - 1] == board[i + 2][j - 2] == board[i + 3][j - 3] == board[i + 4][j - 4]:
self.game_over(board[i][j])
def game_over(self, player):
# 游戏结束
if player == 1:
color = "black"
else:
color = "white"
self.canvas.create_text(BOARD_SIZE // 2, BOARD_SIZE // 2, text=color + " wins!", font=("Helvetica", 32))
self.canvas.unbind("<Button-1>")
def run(self):
self.root.mainloop()
if __name__ == "__main__":
game = Game()
game.run()
```
运行这段代码,会弹出一个窗口,你可以在窗口中下五子棋。
阅读全文