用python中的turtle写出一个井字格的游戏
以下是一个使用Python中的turtle库编写的井字格游戏的示例代码:
import turtle
# 设置窗口的大小和背景色
turtle.setup(400, 400)
turtle.bgcolor("white")
# 绘制井字格
def draw_grid():
turtle.speed(0)
turtle.penup()
turtle.goto(-100, 0)
turtle.pendown()
turtle.pensize(3)
for i in range(2):
turtle.forward(200)
turtle.left(90)
turtle.forward(200)
turtle.right(90)
turtle.penup()
turtle.goto(-100, -50)
turtle.pendown()
turtle.setheading(0)
turtle.forward(200)
turtle.penup()
turtle.goto(-100, 50)
turtle.pendown()
turtle.forward(200)
turtle.penup()
turtle.goto(-50, 100)
turtle.pendown()
turtle.setheading(-90)
turtle.forward(200)
turtle.penup()
turtle.goto(50, 100)
turtle.pendown()
turtle.forward(200)
# 绘制棋子
def draw_piece(x, y, piece):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.setheading(0)
if piece == "X":
turtle.right(45)
for _ in range(4):
turtle.forward(40)
turtle.backward(40)
turtle.right(90)
elif piece == "O":
turtle.circle(40)
# 点击事件处理函数
def click_handler(x, y):
if -100 <= x <= 100 and -100 <= y <= 100:
row = None
col = None
if y < -50:
row = -1
elif y < 50:
row = 0
else:
row = 1
if x < -50:
col = -1
elif x < 50:
col = 0
else:
col = 1
if board[row][col] == "":
draw_piece(col * 100, row * 100, turn)
board[row][col] = turn
if check_win(row, col, turn):
turtle.penup()
turtle.goto(-100, -150)
turtle.pendown()
turtle.write(turn + " wins!", align="center", font=("Arial", 24, "normal"))
turtle.exitonclick()
elif check_tie():
turtle.penup()
turtle.goto(-100, -150)
turtle.pendown()
turtle.write("It's a tie!", align="center", font=("Arial", 24, "normal"))
turtle.exitonclick()
else:
switch_turn()
# 判断是否有玩家获胜
def check_win(row, col, piece):
# 检查行
if board[row][0] == piece and board[row][1] == piece and board[row][2] == piece:
return True
# 检查列
if board[0][col] == piece and board[1][col] == piece and board[2][col] == piece:
return True
# 检查对角线
if board[0][0] == piece and board[1][1] == piece and board[2][2] == piece:
return True
if board[0][2] == piece and board[1][1] == piece and board[2][0] == piece:
return True
return False
# 判断是否平局
def check_tie():
for row in board:
if "" in row:
return False
return True
# 切换玩家
def switch_turn():
global turn
if turn == "X":
turn = "O"
else:
turn = "X"
# 创建井字格游戏的二维列表
board = [["", "", ""],
["", "", ""],
["", "", ""]]
# 初始化玩家
turn = "X"
# 绘制井字格
draw_grid()
# 监听鼠标点击事件
turtle.onscreenclick(click_handler)
# 运行游戏
turtle.mainloop()
使用上述代码,你可以在turtle图形窗口中玩井字格游戏。玩家可以依次点击空白的格子来放置“X”和“O”,当有一方玩家获胜或者平局时,游戏会自动结束
原文地址: https://www.cveoy.top/t/topic/iiOn 著作权归作者所有。请勿转载和采集!