好的,我可以帮你设计一个经典的贪吃蛇小游戏的源代码。以下是代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏界面大小
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇小游戏")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_pos = [random.randrange(1, 64) * 10, random.randrange(1, 48) * 10]
food_spawned = 1
# 定义蛇的初始移动方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束的函数
def game_over():
font = pygame.font.SysFont('Arial', 30)
text = font.render('游戏结束!', True, red)
screen.blit(text, [width // 4, height // 3])
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
quit()
# 开始游戏循环
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:
change_to = "RIGHT"
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
elif event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# 判断蛇是否撞到墙壁
if snake_pos[0] > width or snake_pos[0] < 0 or snake_pos[1] > height or snake_pos[1] < 0:
game_over()
# 更新蛇的移动方向
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 移动蛇的身体
if direction == "RIGHT":
snake_pos[0] += 10
elif direction == "LEFT":
snake_pos[0] -= 10
elif direction == "UP":
snake_pos[1] -= 10
elif direction == "DOWN":
snake_pos[1] += 10
# 增加蛇的长度
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_spawned = 0
else:
snake_body.pop()
# 生成新的食物
if food_spawned == 0:
food_pos = [random.randrange(1, 64) * 10, random.randrange(1, 48) * 10]
food_spawned = 1
# 更新游戏界面
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))
# 刷新游戏界面
pygame.display.update()
# 控制游戏帧率
clock.tick(15)
```
这个小游戏是用 pygame 模块实现的,通过键盘控制贪吃蛇的移动方向,吃到食物后蛇会变长,撞到墙壁或者自己的身体就会游戏结束。