import turtle # 设置屏幕和画笔 screen = turtle.Screen() screen.title("简易井字棋") pen = turtle.Turtle() pen.hideturtle() pen.speed(0) pen.pensize(3) # 当前玩家(X 先手) current_player = "X" # 保存每格的内容(3x3) board = [["" for _ in range(3)] for _ in range(3)] # 画井字棋的格子 def draw_board(): for i in range(0, 3): # 画2条竖线 pen.penup() pen.goto(-100 + i * 100, -150) pen.pendown() pen.goto(-100 + i * 100, 150) for i in range(0, 3): # 画2条横线 pen.penup() pen.goto(-150, -100 + i * 100) pen.pendown() pen.goto(150, -100 + i * 100) # 在某个格子画 X 或 O def draw_symbol(row, col, symbol): x = -150 + col * 100 + 50 y = 150 - row * 100 - 90 pen.penup() pen.goto(x, y) pen.write(symbol, align="center", font=("Arial", 36, "bold")) # 处理点击事件 def click(x, y): global current_player # 将坐标转换为格子位置 if not (-150 < x < 150 and -150 < y < 150): return col = int((x + 150) // 100) row = int((150 - y) // 100) if board[row][col] == "": board[row][col] = current_player draw_symbol(row, col, current_player) # 切换玩家 current_player = "O" if current_player == "X" else "X" # 运行程序 draw_board() screen.onclick(click) screen.mainloop()