python怎么绘制多条蛇
时间: 2024-01-10 18:45:07 浏览: 53
以下是使用pygame库绘制多条蛇的示例代码:
```python
import pygame
import random
# 初始化pygame库
pygame.init()
# 定义窗口大小和标题
window_size = (800, 600)
window_title = "Snake Game"
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption(window_title)
# 定义蛇和食物的颜色和大小
snake_color = (0, 255, 0)
food_color = (255, 0, 0)
block_size = 20
# 定义多条蛇的数量
num_snakes = 3
# 定义蛇的初始位置和移动速度
snake_positions = []
snake_speeds = []
for i in range(num_snakes):
x = random.randint(0, window_size[0] // block_size - 1) * block_size
y = random.randint(0, window_size[1] // block_size - 1) * block_size
snake_positions.append([(x, y)])
snake_speeds.append((block_size, 0))
# 定义食物的初始位置
food_position = (random.randint(0, window_size[0] // block_size - 1) * block_size,
random.randint(0, window_size[1] // block_size - 1) * block_size)
# 定义游戏循环标志变量
game_over = False
# 游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取按键状态
keys = pygame.key.get_pressed()
# 更新蛇的位置
for i in range(num_snakes):
# 获取蛇头位置和速度
head_position = snake_positions[i][-1]
speed = snake_speeds[i]
# 根据按键状态更新速度
if keys[pygame.K_LEFT]:
speed = (-block_size, 0)
elif keys[pygame.K_RIGHT]:
speed = (block_size, 0)
elif keys[pygame.K_UP]:
speed = (0, -block_size)
elif keys[pygame.K_DOWN]:
speed = (0, block_size)
# 计算新的蛇头位置
new_head_position = (head_position[0] + speed[0], head_position[1] + speed[1])
# 判断是否撞墙
if new_head_position[0] < 0 or new_head_position[0] >= window_size[0] \
or new_head_position[1] < 0 or new_head_position[1] >= window_size[1]:
game_over = True
break
# 判断是否吃到食物
if new_head_position == food_position:
food_position = (random.randint(0, window_size[0] // block_size - 1) * block_size,
random.randint(0, window_size[1] // block_size - 1) * block_size)
else:
snake_positions[i].pop(0)
# 添加新的蛇头
snake_positions[i].append(new_head_position)
snake_speeds[i] = speed
# 绘制游戏场景
screen.fill((255, 255, 255))
pygame.draw.rect(screen, food_color, (food_position[0], food_position[1], block_size, block_size))
for i in range(num_snakes):
for j in range(len(snake_positions[i])):
pygame.draw.rect(screen, snake_color, (snake_positions[i][j][0], snake_positions[i][j][1], block_size, block_size))
# 更新屏幕显示
pygame.display.flip()
# 退出pygame库
pygame.quit()
```
在上面的示例代码中,我们使用了一个列表`snake_positions`来存储多条蛇的位置,另外还定义了一个列表`snake_speeds`来存储多条蛇的速度。在更新蛇的位置时,我们需要分别计算每条蛇的新位置,并更新它们的位置和速度。在绘制游戏场景时,我们需要分别绘制每条蛇的身体。
阅读全文