写一个简单的贪吃蛇Python小游戏代码
时间: 2024-12-15 08:16:09 浏览: 2
编写一个简单的贪吃蛇Python小游戏,需要一些基本的游戏元素,比如网格、蛇的身体、食物、以及游戏循环。下面是一个简化的版本,使用了`pygame`库:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
window_size = (400, 400)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
# 蛇的初始位置和尺寸
snake_pos = [(window_size[0] // 2, window_size[1] // 2)]
snake_body = [[10, 10], [90, 10], [80, 10]]
food_pos = [random.randint(0, window_size[0] - 20), random.randint(0, window_size[1] - 20)]
food_spawn = True
clock = pygame.time.Clock()
direction = "right"
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_UP and direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN and direction != "up":
direction = "down"
elif event.key == pygame.K_LEFT and direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT and direction != "left":
direction = "right"
screen.fill((0, 0, 0)) # 渲染黑色背景
if food_spawn:
food_pos = [random.randint(0, window_size[0] - 20), random.randint(0, window_size[1] - 20)]
food_spawn = False
snake_head = snake_pos[-1]
snake_head_new = [snake_head[0] + {"up": 0, "down": 20, "left": -20, "right": 20}[direction],
snake_head[1] + {"up": -20, "down": 20, "left": 0, "right": 0}[direction]]
# 检查边界和身体碰撞
if snake_head_new in snake_body[:-1] or snake_head_new[0] < 0 or snake_head_new[0] >= window_size[0] \
or snake_head_new[1] < 0 or snake_head_new[1] >= window_size[1]:
print("Game Over!")
pygame.quit()
quit()
snake_body.insert(0, list(snake_head_new))
if snake_head == food_pos:
snake_body.append([snake_head[0] + 20, snake_head[1]])
food_spawn = True
else:
tail = snake_body.pop()
screen.blit(pygame.image.load("snake.png"), tail) # 使用图片显示蛇身
screen.blit(pygame.image.load("food.png"), food_pos) # 显示食物
screen.blit(pygame.image.load("snake_head.png"), snake_head) # 显示蛇头
pygame.display.update()
clock.tick(snake_speed)
```
这个代码只是一个基础版本,实际游戏中还需要更复杂的逻辑处理,例如检测玩家操作、增加得分等。请注意,你需要下载并替换"snake.png", "food.png", 和 "snake_head.png" 为蛇、食物和蛇头的实际图像文件。
阅读全文