pygame贪吃蛇代码
时间: 2023-08-27 07:06:27 浏览: 148
pygame实现贪吃蛇游戏(下)
以下是使用pygame编写的贪吃蛇游戏的简单示例代码:
```python
import pygame
import random
# 游戏窗口大小
WIDTH = 640
HEIGHT = 480
# 蛇身格子大小
GRID_SIZE = 20
# 颜色定义
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和移动方向
snake_head = [WIDTH // 2, HEIGHT // 2]
snake_body = [[snake_head[0], snake_head[1] + GRID_SIZE],
[snake_head[0], snake_head[1] + 2 * GRID_SIZE],
[snake_head[0], snake_head[1] + 3 * GRID_SIZE]]
snake_direction = "UP"
# 定义食物的初始位置
food_pos = [random.randrange(1, WIDTH // GRID_SIZE) * GRID_SIZE,
random.randrange(1, HEIGHT // GRID_SIZE) * GRID_SIZE]
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
阅读全文