从零开始用 Python 打造经典贪吃蛇游戏:代码+详解

贪吃蛇是一个经典的益智游戏。它不仅容易上手,也是学习 Python 游戏开发的好入门项目。本文将通过使用 pygame 模块实现一个简单的贪吃蛇游戏,并进行详细讲解。


在这里插入图片描述

1. 安装 pygame

在开始之前,需要确保安装了 pygame 模块。使用以下命令安装:

pip install pygame

2. 完整代码

以下是贪吃蛇游戏的完整实现代码:

import pygame
import random
import time

# 初始化 pygame
pygame.init()

# 屏幕大小
WIDTH, HEIGHT = 600, 400
CELL_SIZE = 20

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')

# 初始化时钟
clock = pygame.time.Clock()

def draw_snake(snake_body):
    """绘制蛇的身体"""
    for segment in snake_body:
        pygame.draw.rect(screen, GREEN, pygame.Rect(segment[0], segment[1], CELL_SIZE, CELL_SIZE))

def show_message(text, color, size, position):
    """显示信息"""
    font = pygame.font.Font(None, size)
    message = font.render(text, True, color)
    screen.blit(message, position)

def main():
    # 初始化蛇
    snake_pos = [100, 50]  # 蛇头初始位置
    snake_body = [[100, 50], [80, 50], [60, 50]]  # 蛇身体
    direction = 'RIGHT'  # 蛇头初始方向
    change_to = direction

    # 初始化食物
    food_pos = [random.randrange(1, WIDTH // CELL_SIZE) * CELL_SIZE, 
                random.randrange(1, HEIGHT // CELL_SIZE) * CELL_SIZE]
    food_spawn = True

    # 初始化分数
    score = 0

    running = True
    while running:
        # 监听按键事件
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and direction != 'DOWN':
                    change_to = 'UP'
                elif event.key == pygame.K_DOWN and direction != 'UP':
                    change_to = 'DOWN'
                elif event.key == pygame.K_LEFT and direction != 'RIGHT':
                    change_to = 'LEFT'
                elif event.key == pygame.K_RIGHT and direction != 'LEFT':
                    change_to = 'RIGHT'

        direction = change_to

        # 更新蛇头位置
        if direction == 'UP':
            snake_pos[1] -= CELL_SIZE
        elif direction == 'DOWN':
            snake_pos[1] += CELL_SIZE
        elif direction == 'LEFT':
            snake_pos[0] -= CELL_SIZE
        elif direction == 'RIGHT':
            snake_pos[0] += CELL_SIZE

        # 增加蛇头
        snake_body.insert(0, list(snake_pos))

        # 检测是否吃到食物
        if snake_pos == food_pos:
            score += 10
            food_spawn = False
        else:
            snake_body.pop()

        if not food_spawn:
            food_pos = [random.randrange(1, WIDTH // CELL_SIZE) * CELL_SIZE, 
                        random.randrange(1, HEIGHT // CELL_SIZE) * CELL_SIZE]
        food_spawn = True

        # 游戏结束条件
        if (
            snake_pos[0] < 0 or snake_pos[0] >= WIDTH or
            snake_pos[1] < 0 or snake_pos[1] >= HEIGHT
        ):
            running = False

        # 检测蛇是否碰到自己
        for block in snake_body[1:]:
            if snake_pos == block:
                running = False

        # 绘制屏幕
        screen.fill(BLACK)
        draw_snake(snake_body)
        pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
        show_message(f'Score: {score}', WHITE, 20, (10, 10))

        pygame.display.update()
        clock.tick(10)

    # 游戏结束信息
    screen.fill(BLACK)
    show_message("Game Over!", RED, 50, (WIDTH // 2 - 100, HEIGHT // 2 - 30))
    show_message(f"Your Score: {score}", WHITE, 30, (WIDTH // 2 - 90, HEIGHT // 2 + 20))
    pygame.display.update()
    time.sleep(3)

    pygame.quit()

if __name__ == "__main__":
    main()

3. 代码讲解

3.1 窗口设置

通过 pygame.display.set_mode() 创建窗口,WIDTH 和 HEIGHT 定义屏幕大小,CELL_SIZE 定义单元格大小,用于蛇的移动和食物生成。

3.2 蛇的定义和绘制

蛇通过一个列表 snake_body 存储位置,每个元素是 [x, y] 坐标。draw_snake() 函数绘制蛇的每个部分。

3.3 方向控制

通过监听键盘事件 (pygame.KEYDOWN) 控制蛇的方向变化。用 change_to 确保快速按键不会导致蛇逆行。

3.4 食物生成和检测

食物的位置由 food_pos 确定,使用 random 随机生成。蛇吃到食物后增长身体并刷新食物位置。

3.5 游戏结束条件

蛇头碰到边界。
蛇头碰到自身。

3.6 显示分数

使用 pygame.font.Font() 绘制得分。

4. 运行效果

游戏运行后:

  • 蛇会按照指定方向移动。
  • 吃到红色方块(食物)后,蛇会变长,分数增加。
  • 蛇碰到屏幕边界或自身后游戏结束。

5. 总结

这段代码使用了 pygame 的核心功能,如绘制图形、监听事件和更新屏幕等。通过学习此项目,你可以掌握如何用 Python 开发一个完整的游戏,并进一步扩展功能,如增加障碍物、调整游戏速度、设计多关卡等。

以下是一个简单的贪吃蛇代码示例,使用 Python 语言编写: ```python import pygame import random # 初始化 Pygame pygame.init() # 设置游戏界面尺寸、背景颜色、标题 screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption('贪吃蛇') # 定义颜色 BLACK = pygame.Color(0, 0, 0) WHITE = pygame.Color(255, 255, 255) RED = pygame.Color(255, 0, 0) GREEN = pygame.Color(0, 255, 0) # 定义游戏结束函数 def game_over(): font = pygame.font.SysFont(None, 48) text = font.render('游戏结束', True, RED) text_rect = text.get_rect() text_rect.centerx = screen.get_rect().centerx text_rect.centery = screen.get_rect().centery - 24 screen.blit(text, text_rect) pygame.display.flip() pygame.time.delay(3000) pygame.quit() sys.exit() # 定义主函数 def main(): # 初始化贪吃蛇和食物 snake_positions = [(200, 200), (210, 200), (220, 200)] snake_direction = 'right' food_position = (random.randint(0, 590), random.randint(0, 590)) food_exist = True # 设置游戏帧率 clock = pygame.time.Clock() # 开始游戏循环 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_LEFT and snake_direction != 'right': snake_direction = 'left' elif event.key == pygame.K_RIGHT and snake_direction != 'left': snake_direction = 'right' elif event.key == pygame.K_UP and snake_direction != 'down': snake_direction = 'up' elif event.key == pygame.K_DOWN and snake_direction != 'up': snake_direction = 'down' # 移动贪吃蛇 if snake_direction == 'right': new_head = (snake_positions[0][0] + 10, snake_positions[0][1]) elif snake_direction == 'left': new_head = (snake_positions[0][0] - 10, snake_positions[0][1]) elif snake_direction == 'up': new_head = (snake_positions[0][0], snake_positions[0][1] - 10) elif snake_direction == 'down': new_head = (snake_positions[0][0], snake_positions[0][1] + 10) snake_positions.insert(0, new_head) # 判断贪吃蛇是否吃到食物 if snake_positions[0] == food_position: food_exist = False else: snake_positions.pop() # 重新生成食物 if not food_exist: food_position = (random.randint(0, 590), random.randint(0, 590)) food_exist = True # 绘制游戏界面 screen.fill(BLACK) for position in snake_positions: pygame.draw.rect(screen, GREEN, pygame.Rect(position[0], position[1], 10, 10)) pygame.draw.rect(screen, WHITE, pygame.Rect(food_position[0], food_position[1], 10, 10)) # 判断贪吃蛇是否死亡 if snake_positions[0][0] < 0 or snake_positions[0][0] > 590 or snake_positions[0][1] < 0 or snake_positions[0][1] > 590: game_over() for position in snake_positions[1:]: if snake_positions[0] == position: game_over() # 更新游戏界面 pygame.display.update() # 控制游戏帧率 clock.tick(10) # 启动游戏 if __name__ == '__main__': main() ``` 这是一个基本的贪吃蛇代码示例,可以实现贪吃蛇的基本功能。当然,你可以根据自己的需要进行修改和扩展。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值