用python编写贪吃蛇
时间: 2023-07-12 22:31:54 浏览: 149
如何用Python写一个贪吃蛇AI.pdf
好的,以下是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((640, 480))
# 设置标题
pygame.display.set_caption('Snake Game')
# 加载图像
snake_head_image = pygame.image.load('assets/snake_head.png').convert_alpha()
snake_body_image = pygame.image.load('assets/snake_body.png').convert_alpha()
apple_image = pygame.image.load('assets/apple.png').convert_alpha()
# 设置游戏参数
clock = pygame.time.Clock()
snake_direction = 'right'
snake_body = [(320, 240), (300, 240), (280, 240)]
apple_position = (random.randint(0, 31) * 20, random.randint(0, 23) * 20)
# 设置分数
score = 0
font = pygame.font.Font('04B_19.ttf', 40)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
# 移动蛇头
if snake_direction == 'up':
snake_head_position = (snake_body[0][0], snake_body[0][1] - 20)
elif snake_direction == 'down':
snake_head_position = (snake_body[0][0], snake_body[0][1] + 20)
elif snake_direction == 'left':
snake_head_position = (snake_body[0][0] - 20, snake_body[0][1])
elif snake_direction == 'right':
snake_head_position = (snake_body[0][0] + 20, snake_body[0][1])
# 检测碰撞
if snake_head_position == apple_position:
apple_position = (random.randint(0, 31) * 20, random.randint(0, 23) * 20)
score += 1
snake_body.append(snake_body[-1])
elif snake_head_position[0] < 0 or snake_head_position[0] >= 640 or snake_head_position[1] < 0 or snake_head_position[1] >= 480 or snake_head_position in snake_body:
pygame.quit()
exit()
else:
snake_body.pop()
# 更新蛇身
snake_body.insert(0, snake_head_position)
# 移动苹果
apple_rect = apple_image.get_rect(topleft=apple_position)
if apple_rect.collidelist(snake_body) != -1:
apple_position = (random.randint(0, 31) * 20, random.randint(0, 23) * 20)
# 移动背景
screen.fill((0, 0, 0))
for i, position in enumerate(snake_body):
if i == 0:
screen.blit(snake_head_image, position)
else:
screen.blit(snake_body_image, position)
screen.blit(apple_image, apple_position)
# 更新分数
score_surface = font.render(str(score), True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(320, 30))
screen.blit(score_surface, score_rect)
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(10)
```
注意:在运行此代码之前,需要将相关图像文件放置在名为“assets”的文件夹中。
阅读全文