用Python的tkinter库帮我写一个五子棋游戏
时间: 2023-12-02 10:02:59 浏览: 96
基于Python实现五子棋小游戏-tkinter版【100011872】
好的,下面是代码,注释中有详细解释:
```python
import tkinter as tk
# 创建窗口
root = tk.Tk()
root.title("五子棋")
# 格子数
GRID_SIZE = 15
# 棋盘宽度和高度
BOARD_WIDTH = 500
BOARD_HEIGHT = 500
# 单元格大小
CELL_SIZE = BOARD_WIDTH // GRID_SIZE
# 棋子半径
PIECE_RADIUS = CELL_SIZE // 2 - 2
# 棋盘数组,0表示空,1表示黑子,2表示白子
board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
# 当前是黑子还是白子
current_player = 1
# 是否结束游戏
game_over = False
def draw_board(canvas):
"""
画棋盘
"""
for i in range(GRID_SIZE):
# 画横线
canvas.create_line(CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE,
BOARD_WIDTH - CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE)
# 画竖线
canvas.create_line(CELL_SIZE // 2 + i * CELL_SIZE, CELL_SIZE // 2,
CELL_SIZE // 2 + i * CELL_SIZE, BOARD_HEIGHT - CELL_SIZE // 2)
def draw_piece(canvas, row, col, player):
"""
画棋子
"""
x = col * CELL_SIZE + CELL_SIZE // 2
y = row * CELL_SIZE + CELL_SIZE // 2
if player == 1:
canvas.create_oval(x - PIECE_RADIUS, y - PIECE_RADIUS, x + PIECE_RADIUS, y + PIECE_RADIUS, fill="black")
else:
canvas.create_oval(x - PIECE_RADIUS, y - PIECE_RADIUS, x + PIECE_RADIUS, y + PIECE_RADIUS, fill="white")
def check_win(player):
"""
检查是否获胜
"""
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
# 横向检查
if j + 4 < GRID_SIZE and board[i][j] == player and board[i][j + 1] == player and board[i][j + 2] == player \
and board[i][j + 3] == player and board[i][j + 4] == player:
return True
# 竖向检查
if i + 4 < GRID_SIZE and board[i][j] == player and board[i + 1][j] == player and board[i + 2][j] == player \
and board[i + 3][j] == player and board[i + 4][j] == player:
return True
# 斜向检查
if i + 4 < GRID_SIZE and j + 4 < GRID_SIZE and board[i][j] == player and board[i + 1][j + 1] == player \
and board[i + 2][j + 2] == player and board[i + 3][j + 3] == player and board[i + 4][j + 4] == player:
return True
if i + 4 < GRID_SIZE and j - 4 >= 0 and board[i][j] == player and board[i + 1][j - 1] == player \
and board[i + 2][j - 2] == player and board[i + 3][j - 3] == player and board[i + 4][j - 4] == player:
return True
return False
def play(event):
"""
下棋
"""
global current_player, game_over
if game_over:
return
col = event.x // CELL_SIZE
row = event.y // CELL_SIZE
if board[row][col] != 0:
return
board[row][col] = current_player
draw_piece(canvas, row, col, current_player)
if check_win(current_player):
canvas.create_text(BOARD_WIDTH // 2, BOARD_HEIGHT // 2, text="黑子胜" if current_player == 1 else "白子胜", font=("Arial", 30))
game_over = True
else:
current_player = 3 - current_player
# 创建画布
canvas = tk.Canvas(root, width=BOARD_WIDTH, height=BOARD_HEIGHT)
canvas.pack()
# 画棋盘
draw_board(canvas)
# 点击事件
canvas.bind("<Button-1>", play)
# 运行程序
root.mainloop()
```
运行程序后,可以在窗口中下五子棋。当有一方获胜时,会在窗口中显示胜利信息。
阅读全文