首页 智能家居

Python 飞机大战:从零打造你的童年回忆(附源码)

分类:智能家居
字数: (9535)
阅读: (2498)
内容摘要:Python 飞机大战:从零打造你的童年回忆(附源码),

还记得小时候街机厅里的《飞机大战》吗?简单的操作,刺激的射击体验,总能让人沉迷其中。今天,我们就将使用 Python 和 Pygame 库,一步步实现一个简易版的飞机大战游戏,带你重温童年经典。

技术选型:Python + Pygame

选择 Python 作为开发语言,是因为其语法简洁易懂,上手快,非常适合快速开发游戏原型。而 Pygame 库则是 Python 中一个强大的游戏开发库,它封装了 SDL 库,提供了图像、声音、事件处理等游戏开发所需的各种功能。

游戏框架搭建

首先,我们需要安装 Pygame 库。可以使用 pip 命令:

pip install pygame

接下来,创建一个主程序文件 main.py,并引入 Pygame 库:

Python 飞机大战:从零打造你的童年回忆(附源码)
import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 480
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏标题
pygame.display.set_caption("飞机大战")

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 填充背景色
    screen.fill((0, 0, 0)) # 黑色

    # 更新屏幕显示
    pygame.display.flip()

# 退出 Pygame
pygame.quit()

这段代码创建了一个简单的游戏窗口,并设置了游戏标题。pygame.display.flip() 用于更新屏幕显示,类似于前端开发中的 Vue 的 nextTick() 或者 React 的 setState() 后的渲染。

添加英雄飞机

接下来,我们添加英雄飞机。首先,准备一张飞机图片,并将其加载到游戏中:

# 加载飞机图片
player_img = pygame.image.load("images/hero.png")
player_x = screen_width / 2
player_y = screen_height - 100
player_speed = 5

def player(x, y):
    screen.blit(player_img, (x, y))

screen.blit() 函数用于将图片绘制到屏幕上。我们可以通过修改 player_xplayer_y 的值来控制飞机的位置。 飞机大战游戏的核心玩法在于操控飞机躲避敌机和发射子弹,所以我们需要添加相应的事件处理代码:

Python 飞机大战:从零打造你的童年回忆(附源码)
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 键盘事件
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x_change = -player_speed
            if event.key == pygame.K_RIGHT:
                player_x_change = player_speed
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                player_x_change = 0

    # 更新飞机位置
    player_x += player_x_change

    # 边界检测
    if player_x <= 0:
        player_x = 0
    elif player_x >= screen_width - 64:
        player_x = screen_width - 64

这段代码监听键盘事件,当按下左箭头键时,飞机向左移动;当按下右箭头键时,飞机向右移动。同时,我们还添加了边界检测,防止飞机飞出屏幕。

添加敌机

敌机的添加与英雄飞机类似,首先加载敌机图片,并随机生成敌机的位置:

# 加载敌机图片
enemy_img = pygame.image.load("images/enemy.png")
enemy_x = random.randint(0, screen_width - 64)
enemy_y = random.randint(50, 150)
enemy_speed = 2
enemy_x_change = 2

def enemy(x, y):
    screen.blit(enemy_img, (x, y))

同样,我们需要更新敌机的位置,并添加边界检测:

Python 飞机大战:从零打造你的童年回忆(附源码)
    # 更新敌机位置
    enemy_x += enemy_x_change

    # 敌机边界检测
    if enemy_x <= 0:
        enemy_x_change = enemy_speed
        enemy_y += 40
    elif enemy_x >= screen_width - 64:
        enemy_x_change = -enemy_speed
        enemy_y += 40

添加子弹

子弹的添加也类似,首先加载子弹图片,并设置子弹的初始位置:

# 加载子弹图片
bullet_img = pygame.image.load("images/bullet.png")
bullet_x = 0
bullet_y = screen_height - 100
bullet_speed = 10
bullet_state = "ready" # ready - 可以发射, fire - 发射中

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bullet_img, (x + 16, y + 10))

当按下空格键时,发射子弹:

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bullet_x = player_x
                    fire_bullet(bullet_x, bullet_y)

    # 子弹移动
    if bullet_state == "fire":
        fire_bullet(bullet_x, bullet_y)
        bullet_y -= bullet_speed

    if bullet_y <= 0:
        bullet_state = "ready"
        bullet_y = screen_height - 100

碰撞检测

最后,我们需要添加碰撞检测,判断子弹是否击中敌机。可以使用 Pygame 提供的 pygame.Rect.colliderect() 函数:

Python 飞机大战:从零打造你的童年回忆(附源码)
import math

def isCollision(enemy_x, enemy_y, bullet_x, bullet_y):
    distance = math.sqrt(math.pow(enemy_x - bullet_x, 2) + math.pow(enemy_y - bullet_y, 2))
    if distance < 27:
        return True
    else:
        return False

并在主循环中调用该函数:

    # 碰撞检测
    collision = isCollision(enemy_x, enemy_y, bullet_x, bullet_y)
    if collision:
        bullet_state = "ready"
        bullet_y = screen_height - 100
        enemy_x = random.randint(0, screen_width - 64)
        enemy_y = random.randint(50, 150)

提升游戏体验:优化与避坑

  1. 图片资源优化:使用压缩后的图片,减少资源加载时间,提升游戏运行效率。可以使用 Tinypng 等工具进行图片压缩。
  2. 帧率控制:使用 pygame.time.Clock().tick(60) 控制游戏帧率,保证游戏运行的流畅性。
  3. 声音效果:添加背景音乐和射击音效,增强游戏体验。可以使用 Pygame 的 pygame.mixer 模块播放声音。
  4. 防止内存泄漏:及时释放不再使用的资源,例如图片和声音文件,避免内存泄漏。
  5. 性能分析:使用 cProfile 等工具分析代码性能,找出性能瓶颈,进行优化。 比如,避免在循环中创建对象,尽量复用对象。

总结:基于 Python 的飞机大战,开源与共享

通过以上步骤,我们就实现了一个简易版的飞机大战游戏。这个 基于 Python 的飞机大战游戏 项目已经开源,你可以在 GitHub 上找到完整的源代码。希望这篇文章能帮助你入门 Pygame 游戏开发,重温童年经典。

Python 飞机大战:从零打造你的童年回忆(附源码)

转载请注明出处: 代码一只喵

本文的链接地址: http://m.acea4.store/article/10228.html

本文最后 发布于2026-04-22 22:52:11,已经过了5天没有更新,若内容或图片 失效,请留言反馈

()
您可能对以下文章感兴趣
评论
  • 单身狗 1 天前
    mark一下,正好最近在学Python,可以练练手。