[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox
import random
# 棋盘大小
BOARD_SIZE = 15
# 棋子颜色
EMPTY, BLACK, WHITE = 0, 1, 2
class Gomoku:
def __init__(self, master):
self.master = master
self.master.title("五子棋")
self.board = [[EMPTY for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
self.current_player = BLACK
self.canvas = tk.Canvas(master, width=450, height=450)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.on_click)
def draw_board(self):
for i in range(BOARD_SIZE):
x0, y0 = 15 + i * 30, 15
x1, y1 = 15 + i * 30, 435
self.canvas.create_line(x0, y0, x1, y1)
x0, y0 = 15, 15 + i * 30
x1, y1 = 435, 15 + i * 30
self.canvas.create_line(x0, y0, x1, y1)
def on_click(self, event):
# 计算点击位置的棋盘坐标
x, y = event.x // 30, event.y // 30
# 检查是否在棋盘范围内并且位置为空
if x >= 0 and y >= 0 and x < BOARD_SIZE and y < BOARD_SIZE and self.board[y][x] == EMPTY:
self.make_move(x, y)
def make_move(self, x, y):
self.board[y][x] = self.current_player
color = "black" if self.current_player == BLACK else "white"
self.canvas.create_oval(x*30 + 20, y*30 + 20, x*30 + 40, y*30 + 40, fill=color)
if self.check_win(x, y):
messagebox.showinfo("Game Over", f"{'Black' if self.current_player == BLACK else 'White'} Wins!")
self.master.quit()
else:
self.current_player = WHITE if self.current_player == BLACK else BLACK
if self.current_player == WHITE: # 如果当前是AI(白棋)的回合
self.ai_move()
def ai_move(self):
# 找一个空位随机下棋
empty_cells = [(i, j) for i in range(BOARD_SIZE) for j in range(BOARD_SIZE) if self.board[j] == EMPTY]
if empty_cells:
x, y = random.choice(empty_cells)
self.make_move(x, y)
def check_win(self, x, y):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
for i in range(1, 5):
nx, ny = x + dx*i, y + dy*i
if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and self.board[ny][nx] == self.current_player:
count += 1
else:
break
for i in range(1, 5):
nx, ny = x - dx*i, y - dy*i
if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and self.board[ny][nx] == self.current_player:
count += 1
else:
break
if count >= 5:
return True
return False
if __name__ == "__main__":
root = tk.Tk()
game = Gomoku(root)
root.mainloop()