python-小游戏-五子棋
需要安装turtle
代码—game-gobang.py
from turtle import *
# 游戏状态变量
win = False
yanse = "black"
gz = 40
m = [[0] * 19 for _ in range(19)]
# 设置屏幕
screen = Screen()
screen.bgcolor("lightgreen")
# 裁判
judge = Turtle()
judge.hideturtle()
judge.up()
judge.goto(-460, 330)
judge.write("谁下", font=("Kai", 40, "bold"))
judge.color(yanse)
judge.goto(-420, 300)
judge.dot(30)
# 棋盘画笔
board_drawer = Turtle()
board_drawer.hideturtle()
# 棋子画笔
piece_drawer = Turtle()
piece_drawer.hideturtle()
# 画棋盘函数
def draw_board():
board_drawer.clear()
board_drawer.speed(0)
board_drawer.pensize(1)
board_drawer.penup()
board_drawer.goto(0, 0)
board_drawer.setheading(0)
# 画19条横线
for i in range(19):
board_drawer.up()
board_drawer.goto(-gz * 9, gz * (9 - i))
board_drawer.down()
board_drawer.fd(gz * 18)
board_drawer.bk(gz * 18)
board_drawer.rt(90)
# 画19条竖线
for i in range(19):
board_drawer.up()
board_drawer.goto(-gz * (9 - i), gz * 9)
board_drawer.down()
board_drawer.fd(gz * 18)
board_drawer.bk(gz * 18)
# 画最外面的粗边框
board_drawer.pensize(5)
for _ in range(4):
board_drawer.fd(gz * 18)
board_drawer.rt(90)
# 初始化棋盘数据
def init_board():
global m, win, yanse
m = [[0] * 19 for _ in range(19)]
win = False
yanse = "black"
draw_board()
# 判断输赢
def check(i, j):
global win
g = [0] * 8
fw = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1))
for index in range(8):
d = fw[index]
next_i = i + d[0]
next_j = j + d[1]
while next_i in range(19) and next_j in range(19) and m[next_i][next_j] == m[i][j]:
g[index] += 1
next_i += d[0]
next_j += d[1]
for index in range(4):
if g[index] + g[index + 4] + 1 >= 5:
win = True
piece_drawer.goto(0, 0)
if yanse == "black":
piece_drawer.write('黑方胜', font=('', 100, ''), align='center')
else:
piece_drawer.write('白方胜', font=('', 100, ''), align='center')
break
# 放棋子的自定义函数
def play(x, y):
if not win:
global yanse
piece_drawer.color(yanse)
piece_drawer.up()
# x变成格子的整数倍,个位数上要进行4舍5入
x = round(x / gz) * gz
# y变成格子的整数倍,个位数上要进行4舍5入
y = round(y / gz) * gz
# 计算棋子在电脑中的位置
i = int(9 - y / gz)
j = int(x / gz + 9)
# 只有棋子在棋盘范围内才可以下
if 0 <= i <= 18 and 0 <= j <= 18:
# 如果[i, j]没有棋子
if m[i][j] == 0:
piece_drawer.goto(x, y)
piece_drawer.dot(30)
if yanse == "black":
m[i][j] = 1
# 判断输赢
check(i, j)
yanse = "white"
else:
m[i][j] = 2
# 判断输赢
check(i, j)
yanse = "black"
# 裁判变色并重新画点
judge.color(yanse)
judge.dot(30)
# 重置游戏
def reset_game():
global yanse
yanse = "black"
judge.clear() # 清除裁判信息
board_drawer.clear() # 清空棋盘
piece_drawer.clear() # 清空棋子
init_board() # 重置棋盘数据和状态
# 重新绘制裁判信息
judge.up()
judge.goto(-460, 330)
judge.write("谁下", font=("Kai", 40, "bold"))
judge.color(yanse)
judge.goto(-420, 300)
judge.dot(30)
# 初始化棋盘数据和绘制棋盘
init_board()
# 当鼠标左键点击屏幕时执行放棋子的自定义函数
onscreenclick(play, 1)
# 当按下空格键时重置游戏
screen.onkey(reset_game, "space")
# 启动主事件循环并开始监听事件
screen.listen()
mainloop()
运行 game-gobang.py
玩完一句可以按下空格键重新开始