import tkinter as tk
from tkinter import messagebox
class ChessBoard:
def __init__(self, size=15):
self.size = size
self.board = [[0] * size for _ in range(size)] # 棋盘上所有的位置都初始化为0
self.player = 1 # 当前玩家,1表示黑子,-1表示白子
self.gameover = False
def move(self, x, y):
if self.board[x][y] == 0 and not self.gameover: # 当前位置没有棋子,游戏未结束
self.board[x][y] = self.player # 下棋
if self._check(x, y): # 判断是否有五子连珠
self.gameover = True
messagebox.showinfo("游戏结束", f"玩家 {self.player} 获胜!")
self.player = -self.player # 轮换玩家
def _check(self, x, y):
# 判断横向是否有五子连珠
if sum([self.board[x][j] == self.player for j in range(self.size)]) >= 5:
return True
# 判断纵向是否有五子连珠
if sum([self.board[j][y] == self.player for j in range(self.size)]) >= 5:
return True
# 判断左上到右下是否有五子连珠
if sum([self.board[i][j] == self.player for i, j in zip(range(x, -1, -1), range(y, -1, -1))]) + \
sum([self.board[i][j] == self.player for i, j in zip(range(x+1, self.size), range(y+1, self.size))]) >= 5:
return True
# 判断右上到左下是否有五子连珠
if sum([self.board[i][j] == self.player for i, j in zip(range(x, -1, -1), range(y, self.size))]) + \
sum([self.board[i][j] == self.player for i, j in zip(range(x+1, self.size), range(y-1, -1, -1))]) >= 5:
return True
return False
class ChessBoardGUI:
def __init__(self, size=15):
self.size = size
self.chessboard = ChessBoard(size)
self.window = tk.Tk()
self.window.title("五子棋游戏")
self.window.geometry(f"{self.size*40}x{self.size*40+40}") # 设置窗口大小
self.canvas = tk.Canvas(self.window, width=self.size*40, height=self.size*40, bg="#ebdbb2")
self.canvas.pack()
self.draw_board()
self.canvas.bind("", self.click) # 绑定鼠标点击事件
self.window.mainloop()
def draw_board(self):
for i in range(self.size):
self.canvas.create_line(20, 20+i*40, self.size*40-20, 20+i*40, width=2) # 画横线
self.canvas.create_line(20 + i * 40, 20, 20 + i * 40, self.size * 40 - 20, width=2)
# 画中心点
self.canvas.create_oval(self.size * 40 // 2 - 5, self.size * 40 // 2 - 5, self.size * 40 // 2 + 5,
self.size * 40 // 2 + 5, fill="black")
def click(self, event):
if not self.chessboard.gameover:
x, y = event.x // 40, event.y // 40 # 计算鼠标点击的位置
self.chessboard.move(x, y)
if self.chessboard.board[x][y] == 1:
self.canvas.create_oval(x * 40 + 5, y * 40 + 5, x * 40 + 35, y * 40 + 35, fill="black") # 画黑子
else:
self.canvas.create_oval(x * 40 + 5, y * 40 + 5, x * 40 + 35, y * 40 + 35, fill="white") # 画白子
if __name__ == '__main__':
ChessBoardGUI()