python turtle四子棋
时间: 2023-09-27 16:03:59 浏览: 157
以下是一个简单的 Python Turtle 四子棋游戏代码示例:
```python
import turtle
# 创建棋盘
def draw_board():
turtle.speed(0)
turtle.penup()
turtle.setpos(-150, 150)
turtle.pendown()
turtle.pensize(3)
for i in range(4):
turtle.forward(300)
turtle.right(90)
turtle.penup()
turtle.setpos(-150, 50)
turtle.pendown()
for i in range(3):
turtle.forward(300)
turtle.right(90)
turtle.penup()
turtle.setpos(-150, -50)
turtle.pendown()
for i in range(3):
turtle.forward(300)
turtle.right(90)
# 画棋子
def draw_piece(x, y, color):
turtle.penup()
turtle.setpos(x, y)
turtle.pendown()
turtle.dot(40, color)
# 判断胜负
def check_win(board, piece):
for i in range(4):
if board[i][0] == piece and board[i][1] == piece and board[i][2] == piece and board[i][3] == piece:
return True
if board[0][i] == piece and board[1][i] == piece and board[2][i] == piece and board[3][i] == piece:
return True
if board[0][0] == piece and board[1][1] == piece and board[2][2] == piece and board[3][3] == piece:
return True
if board[0][3] == piece and board[1][2] == piece and board[2][1] == piece and board[3][0] == piece:
return True
return False
# 主函数
def main():
board = [[0 for i in range(4)] for j in range(4)] # 初始化棋盘
player = 1 # 第一个玩家为红色
draw_board() # 画棋盘
while True:
x, y = turtle.numinput("四子棋", "请输入下棋位置(x,y):", default=(0, 0))
x = int(x)
y = int(y)
if x < -150 or x > 150 or y < -150 or y > 150:
continue
i = (x + 150) // 100
j = (y + 150) // 100
if board[i][j] != 0:
continue
if player == 1:
color = "red"
piece = 1
player = 2
else:
color = "blue"
piece = 2
player = 1
draw_piece(i * 100 - 150, j * 100 - 150, color)
board[i][j] = piece
if check_win(board, piece):
turtle.penup()
turtle.setpos(-100, 0)
turtle.pendown()
turtle.write(color + " wins!", font=("Arial", 30, "normal"))
break
turtle.done()
if __name__ == "__main__":
main()
```
该代码使用 Python Turtle 图形库绘制了一个简单的四子棋游戏界面,并实现了下棋、判断胜负等功能。在运行代码后,用户可以通过输入坐标来下棋,并根据游戏规则进行判断胜负。
阅读全文