用python写一个贪吃蛇小游戏
时间: 2023-12-07 16:02:27 浏览: 86
抱歉,作为AI语言模型,我无法编写并运行Python程序。但我可以提供一些伪代码帮助您完成这个项目:
1. 导入必要的模块
```python
import pygame
import random
```
2. 定义常量和变量
```python
# 游戏窗口大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
# 游戏区域大小
GAME_WIDTH = 400
GAME_HEIGHT = 400
# 方格大小
GRID_SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 创建时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的初始位置
snake_head = [200, 200]
snake_body = [[200, 200], [180, 200], [160, 200]]
# 定义食物的初始位置
food_pos = [random.randrange(1, GAME_WIDTH // GRID_SIZE) * GRID_SIZE,
random.randrange(1, GAME_HEIGHT // GRID_SIZE) * GRID_SIZE]
# 定义贪吃蛇的移动方向
direction = "RIGHT"
change_to = direction
# 定义得分
score = 0
```
3. 定义游戏循环
```python
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == pygame.K_LEFT and direction != "RIGHT":
change_to = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
change_to = "RIGHT"
elif event.key == pygame.K_UP and direction != "DOWN":
change_to = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
change_to = "DOWN"
# 更新贪吃蛇的移动方向
direction = change_to
# 移动贪吃蛇的头部
if direction == "RIGHT":
snake_head[0] += GRID_SIZE
elif direction == "LEFT":
snake_head[0] -= GRID_SIZE
elif direction == "UP":
snake_head[1] -= GRID_SIZE
elif direction == "DOWN":
snake_head[1] += GRID_SIZE
# 判断是否吃到食物
if snake_head == food_pos:
food_pos = [random.randrange(1, GAME_WIDTH // GRID_SIZE) * GRID_SIZE,
random.randrange(1, GAME_HEIGHT // GRID_SIZE) * GRID_SIZE]
score += 10
else:
snake_body.pop()
# 添加贪吃蛇的头部
snake_body.insert(0, list(snake_head))
# 游戏胜利条件
if score == 100:
print("You win!")
pygame.quit()
sys.exit()
# 判断是否游戏失败
if snake_head[0] < 0 or snake_head[0] > GAME_WIDTH - GRID_SIZE \
or snake_head[1] < 0 or snake_head[1] > GAME_HEIGHT - GRID_SIZE \
or snake_head in snake_body[1:]:
print("Game over!")
pygame.quit()
sys.exit()
# 绘制游戏界面
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [0, 0, GAME_WIDTH, GAME_HEIGHT], 2)
for pos in snake_body:
pygame.draw.rect(screen, RED, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
pygame.draw.rect(screen, WHITE, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE])
pygame.display.update()
# 控制游戏速度
clock.tick(10)
```
这个伪代码可以帮助您完成一个简单的贪吃蛇小游戏。您需要按照上面的代码来编写实际的Python程序,并且还需要添加一些其他的细节,如游戏音效、游戏难度等等。
阅读全文