#import numpy as np
import tkinter as tk
class Board(tk.Canvas):
def __init__(self, master=None, side=15, block_size=30, *args, **kwargs):
# 初始化画布
super().__init__(master, *args, **kwargs)
self.side = side # 棋盘大小
self.block_size = block_size # 每个格子大小
self.width = side * block_size # 画布宽度
self.height = side * block_size # 画布高度
self.history = [] # 棋子落点历史
self.bind("<Button-1>", self.callback) # 绑定鼠标左键事件
self.draw_board() # 绘制棋盘
def draw_board(self):
for i in range(self.side):
self.create_line(self.block_size / 2 + i * self.block_size, self.block_size / 2,
self.block_size / 2 + i * self.block_size, self.height - self.block_size / 2)
self.create_line(self.block_size / 2, self.block_size / 2 + i * self.block_size,
self.width - self.block_size / 2, self.block_size / 2 + i * self.block_size)
def callback(self, event):
x, y = event.x, event.y
i, j = int(round((y - self.block_size / 2) / self.block_size)), \
int(round((x - self.block_size / 2) / self.block_size))
if i < 0 or i >= self.side or j < 0 or j >= self.side or (i, j) in self.history:
# 落点不合法
return
self.history.append((i, j))
if len(self.history) % 2 == 1:
self.create_oval(j * self.block_size + 2, i * self.block_size + 2,
(j + 1) * self.block_size - 2, (i + 1) * self.block_size - 2,
fill="black", width=0)
else:
self.create_oval(j * self.block_size + 2, i * self.block_size + 2,
(j + 1) * self.block_size - 2, (i + 1) * self.block_size - 2,
fill="white", width=0)
if self.check_win((i, j)):
self.unbind("<Button-1>")
if len(self.history) % 2 == 1:
print("黑棋胜利!")
else:
print("白棋胜利!")
def check_win(self, pos):
i, j = pos
player = 1 if len(self.history) % 2 == 1 else -1
for di, dj in [(0, 1), (1, 0), (1, 1), (1, -1)]:
s = 1
for k in range(1, 5):
if 0 <= i + k * di < self.side and 0 <= j + k * dj < self.side \
and (i + k * di, j + k * dj) in self.history \
and player == (1 if (i + k * di, j + k * dj) in self.history[::2] else -1):
s += 1
else:
break
for k in range(1, 5):
if 0 <= i - k * di < self.side and 0 <= j - k * dj < self.side \
and (i - k * di, j - k * dj) in self.history \
and player == (1 if (i - k * di, j - k * dj) in self.history[::2] else -1):
s += 1
else:
break
if s >= 5:
return True
return False
root = tk.Tk()
board = Board(root, width=450, height=450)
board.pack()
root.mainloop()
#这是一个基于`tkinter`的五子棋棋盘代码,棋盘大小为15x15,每个格子尺寸为30x30
一个用python实现的简单五子棋小程序
于 2023-03-29 20:28:53 首次发布