实现贪吃蛇游戏的python代码
时间: 2023-11-12 16:58:17 浏览: 57
以下是一个简单的 Python 贪吃蛇游戏代码示例:
``` python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义窗口大小和网格大小
WIDTH = 800
HEIGHT = 600
GRID_SIZE = 20
# 初始化 pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# 定义字体
font = pygame.font.SysFont(None, 48)
# 定义蛇的初始位置和速度
snake_pos = [(WIDTH // 2, HEIGHT // 2)]
dx = 0
dy = -GRID_SIZE
# 定义食物的位置
food_pos = (random.randint(0, WIDTH // GRID_SIZE) * GRID_SIZE, random.randint(0, HEIGHT // GRID_SIZE) * GRID_SIZE)
# 定义游戏循环
clock = pygame.time.Clock()
running = True
while running:
clock.tick(10)
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx = -GRID_SIZE
dy = 0
elif event.key == pygame.K_RIGHT:
dx = GRID_SIZE
dy = 0
elif event.key == pygame.K_UP:
dx = 0
dy = -GRID_SIZE
elif event.key == pygame.K_DOWN:
dx = 0
dy = GRID_SIZE
# 更新蛇的位置
snake_pos.append((snake_pos[-1][0] + dx, snake_pos[-1][1] + dy))
snake_pos.pop(0)
# 检查是否吃到食物
if snake_pos[-1] == food_pos:
food_pos = (random.randint(0, WIDTH // GRID_SIZE) * GRID_SIZE, random.randint(0, HEIGHT // GRID_SIZE) * GRID_SIZE)
snake_pos.insert(0, (snake_pos[0][0] - dx, snake_pos[0][1] - dy))
# 检查是否撞到墙或自己
if snake_pos[-1][0] < 0 or snake_pos[-1][0] >= WIDTH or snake_pos[-1][1] < 0 or snake_pos[-1][1] >= HEIGHT:
running = False
for i in range(len(snake_pos) - 1):
if snake_pos[-1] == snake_pos[i]:
running = False
# 渲染画面
screen.fill(BLACK)
pygame.draw.rect(screen, RED, (food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE))
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, (pos[0], pos[1], GRID_SIZE, GRID_SIZE))
pygame.display.update()
# 游戏结束,显示得分
text = font.render("Game Over!", True, WHITE)
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 40))
screen.blit(text, text_rect)
score = len(snake_pos) - 1
text = font.render(f"Score: {score}", True, WHITE)
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))
screen.blit(text, text_rect)
pygame.display.update()
# 等待退出
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
```
阅读全文