利用Python的pygame库可以轻松以40行的代码完成五子棋
下面是棋盘登初始化界面
下面是带注释版本
import time
import pygame as py
import tkinter.messagebox
# 初始化
py.init()
rect = py.Rect(0, 0, 592, 592)
a = [[-1 for i in range(1, 16)] for j in range(1, 16)]
# 屏幕
screen = py.display.set_mode((592, 592))
# 棋盘背景
bg = py.image.load('D:\\Photoes\\屏幕截图 2022-07-05 090732.png')
# 游戏时钟
clock = py.time.Clock()
# 下棋方
turns = 0
screen.blit(bg, rect)
# 音乐初始化
py.mixer.init()
py.mixer.music.load("D:\CloudMusic\晊恦 - Start Again.mp3")
py.mixer.music.play(-1, 0)
def direction(i, j, x, y, t):
if i < 0 or j < 0 or i > 14 or j > 14:
return 0
res = 0
if a[i][j] == t: res = 1
res += direction(i + x, j + y, x, y, t)
return res
# 判断是否存在五连子
def judie(i, j, x):
if direction(i, j, 0, 1, x) + direction(i, j, 0, -1, x) >= 6:
return True
elif direction(i, j, 1, 0, x) + direction(i, j, -1, 0, x) >= 6:
return True
elif direction(i, j, 1, -1, x) + direction(i, j, -1, 1, x) >= 6:
return True
elif direction(i, j, 1, 1, x) + direction(i, j, -1, -1, x) >= 6:
return True
else:
return False
def drawmessage(str):
py.draw.rect(screen, (202, 40, 222), (1, 1, 170, 22))
py.draw.rect(screen, (100, 100, 100), (550, 3, 40, 20))
Time = int((time.time() - timeStrat) // 1)
py.draw.circle(screen, str, (9, 9), 7)
font = py.font.Font(None, 23)
screen.blit(font.render(f' is {str} doing now', True, (0, 0, 0)), (17, 2))
screen.blit(font.render(" {:04d}".format(Time), True, (255, 255, 255)), (550 , 5))
def drawWhoWin(who):
tkinter.messagebox.showinfo('输赢确认',f'{who}赢了!!!!')
timeStrat = time.time()
tkinter.messagebox.showinfo('确认框', '是否确认开始游戏')
while True:
# 设置刷新率
clock.tick(20)
str = 'black'
# 在窗口左上角绘制哪方下棋
if turns % 2: str = 'white'
drawmessage(str)
# 结束游戏
for e in py.event.get():
if e.type == py.QUIT:
py.quit()
exit(0)
elif e.type == py.MOUSEBUTTONDOWN:
# 获取鼠标坐标
r = list(e.pos)
x, y = r[0], r[1]
# 计算点击坐标在棋盘的相对位置
i, j = int((x - 13) // 38.7), int((y - 13) // 38.7)
# 如果重复点击就滤过
if a[i][j] != -1 or i < 0 or j < 0:continue
# 判断是哪个棋子走
if turns % 2: str = 'white'
a[i][j] = turns % 2
# 绘制棋子
py.draw.circle(screen, str, (i * 38.7 + 25, j * 38.7 + 25), 12)
# 判断输赢
if judie(i, j, turns % 2):
drawWhoWin(str)
py.quit()
exit(0)
# 更改下棋方
turns += 1
# 更新游戏界面
py.display.update()
棋子采用画图完成, 棋盘引入图片, 音乐是随便搞得
游戏结束采用对话框