用python来写降落四子棋,用turtle,不能用pygame
时间: 2024-05-09 07:20:22 浏览: 167
以下是Python代码:
```
import turtle
# 定义常量
CELL_SIZE = 40 # 棋子大小
GRID_SIZE = 4 # 棋盘大小
PLAYER_1 = 'red'
PLAYER_2 = 'yellow'
# 初始化游戏窗口
window = turtle.Screen()
window.title('降落四子棋')
window.bgcolor('white')
window.setup(CELL_SIZE * GRID_SIZE + 100, CELL_SIZE * GRID_SIZE + 100)
# 初始化画笔
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# 初始化棋盘
board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
# 绘制棋盘网格线
def draw_grid():
pen.penup()
pen.goto(-GRID_SIZE/2*CELL_SIZE, -GRID_SIZE/2*CELL_SIZE)
pen.pendown()
for i in range(GRID_SIZE + 1):
pen.forward(CELL_SIZE * GRID_SIZE)
pen.left(90)
pen.forward(CELL_SIZE)
pen.left(90)
pen.forward(CELL_SIZE * GRID_SIZE)
pen.right(90)
pen.forward(CELL_SIZE)
pen.right(90)
pen.penup()
# 绘制棋子
def draw_piece(x, y, color):
pen.penup()
pen.goto(x, y)
pen.pendown()
pen.fillcolor(color)
pen.begin_fill()
pen.circle(CELL_SIZE/2)
pen.end_fill()
pen.penup()
# 判断是否胜利
def is_win(player):
# 判断行
for row in board:
if row.count(player) >= 4:
return True
# 判断列
for col in range(GRID_SIZE):
if [board[row][col] for row in range(GRID_SIZE)].count(player) >= 4:
return True
# 判断正斜线
for row in range(GRID_SIZE - 3):
for col in range(GRID_SIZE - 3):
if [board[row+i][col+i] for i in range(4)].count(player) >= 4:
return True
# 判断反斜线
for row in range(3, GRID_SIZE):
for col in range(GRID_SIZE - 3):
if [board[row-i][col+i] for i in range(4)].count(player) >= 4:
return True
return False
# 判断是否平局
def is_tie():
for row in board:
if 0 in row:
return False
return True
# 玩家1下棋
def player1_move(col):
for row in range(GRID_SIZE):
if board[row][col] == 0:
board[row][col] = PLAYER_1
draw_piece(col*CELL_SIZE - GRID_SIZE/2*CELL_SIZE + CELL_SIZE/2, row*CELL_SIZE - GRID_SIZE/2*CELL_SIZE + CELL_SIZE/2, PLAYER_1)
if is_win(PLAYER_1):
pen.goto(0, 200)
pen.write('玩家1胜利!', align='center', font=('Arial', 24, 'bold'))
window.onclick(None)
return
if is_tie():
pen.goto(0, 200)
pen.write('平局!', align='center', font=('Arial', 24, 'bold'))
window.onclick(None)
return
window.onclick(player2_turn)
return
# 玩家2下棋
def player2_move(col):
for row in range(GRID_SIZE):
if board[row][col] == 0:
board[row][col] = PLAYER_2
draw_piece(col*CELL_SIZE - GRID_SIZE/2*CELL_SIZE + CELL_SIZE/2, row*CELL_SIZE - GRID_SIZE/2*CELL_SIZE + CELL_SIZE/2, PLAYER_2)
if is_win(PLAYER_2):
pen.goto(0, 200)
pen.write('玩家2胜利!', align='center', font=('Arial', 24, 'bold'))
window.onclick(None)
return
if is_tie():
pen.goto(0, 200)
pen.write('平局!', align='center', font=('Arial', 24, 'bold'))
window.onclick(None)
return
window.onclick(player1_turn)
return
# 玩家1回合
def player1_turn(x, y):
col = int((x + GRID_SIZE/2*CELL_SIZE) // CELL_SIZE)
player1_move(col)
# 玩家2回合
def player2_turn(x, y):
col = int((x + GRID_SIZE/2*CELL_SIZE) // CELL_SIZE)
player2_move(col)
# 开始游戏
draw_grid()
window.onclick(player1_turn)
window.mainloop()
```
运行代码后,会弹出一个游戏窗口,可以点击窗口来控制玩家下棋。当有一方胜利或者平局时,会弹出相应的提示信息。
阅读全文