当前位置:首页 > Python > 正文

Python贪吃蛇游戏开发教程 - 从零开始创建经典游戏 | Python游戏编程指南

Python贪吃蛇游戏开发教程

从零开始使用Python和Pygame创建经典贪吃蛇游戏

为什么学习Python游戏开发?

Python是游戏开发入门的最佳语言之一,具有以下优势:

  • 语法简洁易学,适合初学者
  • 丰富的游戏开发库(Pygame, Arcade等)
  • 跨平台支持(Windows, macOS, Linux)
  • 活跃的开发者社区和大量学习资源
  • 快速原型开发能力

准备工作

在开始之前,我们需要安装必要的库:

安装Pygame

pip install pygame

Pygame是Python最流行的2D游戏开发库,提供:

  • 图形绘制和动画支持
  • 键盘、鼠标事件处理
  • 碰撞检测系统
  • 声音和音乐播放功能
  • 简单的物理引擎

贪吃蛇游戏开发步骤

1. 初始化游戏

设置游戏窗口、颜色和基本参数

import pygame
import random

# 初始化pygame
pygame.init()

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

# 设置游戏窗口
WIDTH, HEIGHT = 600, 400
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

2. 创建蛇和食物

实现蛇的移动逻辑和食物生成

# 蛇的初始位置和大小
snake_block = 20
snake_speed = 15

# 初始化蛇
snake_list = [[WIDTH/2, HEIGHT/2]]
snake_length = 1

# 食物位置
food_x = round(random.randrange(0, WIDTH - snake_block) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - snake_block) / 20.0) * 20.0

3. 游戏主循环

处理用户输入和游戏逻辑

# 游戏主循环
def game_loop():
    game_over = False
    x_change = 0
    y_change = 0
    
    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                # 处理方向键
                pass
        
        # 更新蛇的位置
        # 检查是否吃到食物
        # 检查碰撞
        # 绘制游戏元素
        
        pygame.display.update()
        clock.tick(snake_speed)

4. 添加游戏功能

计分系统、游戏结束处理等

  • 分数计数器
  • 游戏结束画面
  • 重新开始功能
  • 难度级别
  • 障碍物设置

完整游戏代码

下面是完整的贪吃蛇游戏Python代码:

import pygame
import time
import random

# 初始化pygame
pygame.init()

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# 设置显示窗口
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏 by Python')

# 设置游戏时钟
clock = pygame.time.Clock()

# 蛇的大小和速度
snake_block = 20
snake_speed = 15

# 设置字体
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)

# 显示得分
def your_score(score):
    value = score_font.render("得分: " + str(score), True, black)
    dis.blit(value, [10, 10])

# 绘制蛇
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])

# 显示消息
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])

# 游戏主循环
def gameLoop():
    game_over = False
    game_close = False

    # 蛇的初始位置
    x1 = dis_width / 2
    y1 = dis_height / 2

    # 蛇的移动方向
    x1_change = 0
    y1_change = 0

    # 蛇的身体
    snake_List = []
    Length_of_snake = 1

    # 食物位置
    foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
    foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0

    while not game_over:

        while game_close == True:
            dis.fill(white)
            message("游戏结束! 按Q退出或C重新开始", red)
            your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        # 检查是否撞墙
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True

        # 更新蛇的位置
        x1 += x1_change
        y1 += y1_change
        dis.fill(white)
        
        # 绘制食物
        pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
        
        # 更新蛇的身体
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        
        # 删除多余的蛇身
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        # 检查是否撞到自己
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        # 绘制蛇和分数
        our_snake(snake_block, snake_List)
        your_score(Length_of_snake - 1)

        pygame.display.update()

        # 检查是否吃到食物
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
            foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0
            Length_of_snake += 1

        # 控制游戏速度
        clock.tick(snake_speed)

    # 退出游戏
    pygame.quit()
    quit()

# 启动游戏
gameLoop()

运行游戏

保存上面的代码为snake_game.py,然后使用Python运行:

python snake_game.py

游戏开发进阶技巧

1. 添加游戏音效

使用Pygame.mixer添加音效:

# 加载音效
eat_sound = pygame.mixer.Sound('eat.wav')
game_over_sound = pygame.mixer.Sound('game_over.wav')

# 吃到食物时播放
eat_sound.play()

2. 增加游戏难度

随分数增加速度:

# 根据分数调整速度
if score > 10:
    snake_speed = 20
elif score > 20:
    snake_speed = 25

3. 添加障碍物

增加游戏挑战性:

# 创建障碍物
obstacles = [
    [200, 200],
    [400, 300],
    [600, 100]
]

# 检查碰撞障碍物
for obs in obstacles:
    if x1 == obs[0] and y1 == obs[1]:
        game_over = True

更多Python游戏项目

打砖块

经典街机游戏

俄罗斯方块

益智方块游戏

太空侵略者

射击类游戏

扫雷

策略解谜游戏

© 2023 Python游戏开发教程 | 通过实际项目学习编程

发表评论