You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.7 KiB

import tkinter as tk
from tkinter import messagebox
BOARD_SIZE = 15
GRID_SIZE = 40
PIECE_RADIUS = 15
WIN_COUNT = 5
class GomokuGUI:
def __init__(self, root):
self.root = root
self.root.title("五子棋")
self.canvas = tk.Canvas(root, width=GRID_SIZE * BOARD_SIZE, height=GRID_SIZE * BOARD_SIZE, bg="#F0D9B5")
self.canvas.pack()
self.board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
self.current_player = 1 # 1: Black ●, 2: White ○
self.draw_board()
self.canvas.bind("<Button-1>", self.handle_click)
def draw_board(self):
for i in range(BOARD_SIZE):
# 画竖线
x = GRID_SIZE // 2 + i * GRID_SIZE
self.canvas.create_line(x, GRID_SIZE // 2, x, GRID_SIZE // 2 + (BOARD_SIZE - 1) * GRID_SIZE)
# 画横线
y = GRID_SIZE // 2 + i * GRID_SIZE
self.canvas.create_line(GRID_SIZE // 2, y, GRID_SIZE // 2 + (BOARD_SIZE - 1) * GRID_SIZE, y)
def handle_click(self, event):
col = round((event.x - GRID_SIZE // 2) / GRID_SIZE)
row = round((event.y - GRID_SIZE // 2) / GRID_SIZE)
if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE and self.board[row][col] == 0:
self.place_piece(row, col, self.current_player)
if self.check_winner(row, col):
messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
self.canvas.unbind("<Button-1>")
return
self.current_player = 3 - self.current_player
def place_piece(self, row, col, player):
x = GRID_SIZE // 2 + col * GRID_SIZE
y = GRID_SIZE // 2 + row * GRID_SIZE
color = "black" if player == 1 else "white"
self.canvas.create_oval(
x - PIECE_RADIUS, y - PIECE_RADIUS,
x + PIECE_RADIUS, y + PIECE_RADIUS,
fill=color, outline="black"
)
self.board[row][col] = player
def check_winner(self, row, col):
player = self.board[row][col]
directions = [(1,0), (0,1), (1,1), (1,-1)]
for dx, dy in directions:
count = 1
for dir in [1, -1]:
x, y = row, col
while True:
x += dx * dir
y += dy * dir
if 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE and self.board[x][y] == player:
count += 1
else:
break
if count >= WIN_COUNT:
return True
return False
if __name__ == "__main__":
root = tk.Tk()
game = GomokuGUI(root)
root.mainloop()