帮我用python编写一个贪吃蛇游戏
时间: 2023-08-27 16:05:51 浏览: 43
当然可以!下面是一个简单的贪吃蛇游戏的Python代码示例:
```python
import pygame
import random
# 游戏窗口大小
width = 640
height = 480
# 定义颜色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 初始化pygame模块
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
# 初始化游戏时钟
clock = pygame.time.Clock()
# 蛇的初始位置和速度
snake_head = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, width // 10) * 10,
random.randrange(1, height // 10) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
# 防止蛇直接掉头
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
# 更新蛇头的位置
if direction == 'RIGHT':
snake_head[0] += 10
if direction == 'LEFT':
snake_head[0] -= 10
if direction == 'UP':
snake_head[1] -= 10
if direction == 'DOWN':
snake_head[1] += 10
# 增加蛇身长度
snake_body.insert(0, list(snake_head))
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# 生成新的食物
if not food_spawn:
food_pos = [random.randrange(1, width // 10) * 10,
random.randrange(1, height // 10) * 10]
food_spawn = True
# 绘制游戏画面
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, green, pygame.Rect(
pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, white, pygame.Rect(
food_pos[0], food_pos[1], 10, 10))
# 检测是否碰到边界或自身
if snake_head[0] < 0 or snake_head[0] >= width or snake_head[1] < 0 or snake_head[1] >= height:
pygame.quit()
quit()
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
pygame.quit()
quit()
# 更新分数
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, white)
screen.blit(text, [10, 10])
# 刷新屏幕
pygame.display.update()
# 控制游戏速度
clock.tick(15)
```
请确保在运行代码前已经安装了Pygame库。此代码仅提供了基本的游戏逻辑和绘制,你可以根据自己的需要进行修改和扩展。玩家可以使用方向键或WASD来控制贪吃蛇的移动方向,游戏目标是吃掉尽可能多的食物并避免碰到边界或自身。