pygame实现贪吃蛇小游戏


import pygame
import random

# 游戏初始化
pygame.init()

# 游戏窗口设置
win_width, win_height = 800, 600
window = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Snake Game")

# 颜色设置
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 蛇的初始位置
snake_size = 20
snake_x = win_width // 2
snake_y = win_height // 2

# 蛇的初始移动方向
snake_dx = 0
snake_dy = 0

# 存储蛇身体的坐标
snake_body = []
snake_length = 1

# 生成食物的随机位置
food_x = random.randint(0, win_width - snake_size) // snake_size * snake_size
food_y = random.randint(0, win_height - snake_size) // snake_size * snake_size

# 游戏主循环
running = True
clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 监听键盘事件,控制蛇的方向
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                snake_dx = -snake_size
                snake_dy = 0
            elif event.key == pygame.K_RIGHT:
                snake_dx = snake_size
                snake_dy = 0
            elif event.key == pygame.K_UP:
                snake_dx = 0
                snake_dy = -snake_size
            elif event.key == pygame.K_DOWN:
                snake_dx = 0
                snake_dy = snake_size

    # 更新蛇的位置
    snake_x += snake_dx
    snake_y += snake_dy

    # 检查蛇是否碰到边界
    if snake_x < 0 or snake_x >= win_width or snake_y < 0 or snake_y >= win_height:
        running = False

    # 检查蛇是否吃到了食物
    if snake_x == food_x and snake_y == food_y:
        # 随机生成新的食物位置
        food_x = random.randint(0, win_width - snake_size) // snake_size * snake_size
        food_y = random.randint(0, win_height - snake_size) // snake_size * snake_size
        snake_length += 1

    # 更新蛇的身体
    snake_body.append((snake_x, snake_y))
    if len(snake_body) > snake_length:
        del snake_body[0]

    # 检查是否与自身碰撞
    if (snake_x, snake_y) in snake_body[:-1]:
        running = False

    # 绘制背景
    window.fill(BLACK)

    # 绘制蛇的身体
    for body_part in snake_body:
        pygame.draw.rect(window, GREEN, (body_part[0], body_part[1], snake_size, snake_size))

    # 绘制食物
    pygame.draw.rect(window, RED, (food_x, food_y, snake_size, snake_size))

    # 更新屏幕
    pygame.display.update()

    # 控制游戏帧率
    clock.tick(10)

# 游戏结束,退出pygame
pygame.quit()

pygame实现贪吃蛇小游戏_第1张图片

你可能感兴趣的:(pygame,python,开发语言)