面向过程方法实现贪吃蛇
时间: 2024-03-18 22:42:38 浏览: 14
好的,下面是一个简单的面向过程方法实现贪吃蛇的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏窗口尺寸
WIDTH = 600
HEIGHT = 600
# 定义贪吃蛇方块大小
BLOCK_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义贪吃蛇初始位置和长度
snake = [
[WIDTH / 2, HEIGHT / 2],
[WIDTH / 2 - BLOCK_SIZE, HEIGHT / 2],
[WIDTH / 2 - 2 * BLOCK_SIZE, HEIGHT / 2]
]
# 定义初始移动方向
direction = "right"
# 定义食物位置
food = [random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE),
random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)]
# 定义游戏结束状态和分数
game_over = False
score = 0
# 定义绘制贪吃蛇函数
def draw_snake(snake):
for block in snake:
pygame.draw.rect(screen, GREEN, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
# 定义绘制食物函数
def draw_food(food):
pygame.draw.rect(screen, RED, [food[0], food[1], BLOCK_SIZE, BLOCK_SIZE])
# 定义更新分数函数
def update_score(score):
font = pygame.font.Font(None, 30)
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, [10, 10])
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT and direction != "left":
direction = "right"
elif event.key == pygame.K_UP and direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN and direction != "up":
direction = "down"
# 移动贪吃蛇
if direction == "right":
snake.insert(0, [snake[0][0] + BLOCK_SIZE, snake[0][1]])
elif direction == "left":
snake.insert(0, [snake[0][0] - BLOCK_SIZE, snake[0][1]])
elif direction == "up":
snake.insert(0, [snake[0][0], snake[0][1] - BLOCK_SIZE])
elif direction == "down":
snake.insert(0, [snake[0][0], snake[0][1] + BLOCK_SIZE])
# 判断是否吃到食物
if snake[0] == food:
food = [random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE),
random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)]
score += 10
else:
snake.pop()
# 判断游戏是否结束
if snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:
game_over = True
for block in snake[1:]:
if snake[0] == block:
game_over = True
# 绘制游戏画面
screen.fill(BLACK)
draw_snake(snake)
draw_food(food)
update_score(score)
pygame.display.update()
# 退出游戏
pygame.quit()
```
这个示例代码实现了一个简单的贪吃蛇游戏,游戏窗口大小为 600x600,贪吃蛇方块大小为 20x20,初始长度为 3,初始移动方向为向右,食物随机生成。玩家通过方向键控制贪吃蛇的移动方向,当贪吃蛇吃到食物时,长度加一,分数加10,食物重新生成。当贪吃蛇碰到边界或者自己时,游戏结束。在游戏画面中,显示当前分数。