卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79551本站已运行4415

如何构建您的第一个 Python 游戏:使用 PyGame 创建简单射击游戏的分步指南

如何构建您的第一个 python 游戏:使用 pygame 创建简单射击游戏的分步指南

亲爱的读者们大家好,

你有没有想过创建自己的视频游戏?也许您已经考虑过构建一款简单的射击游戏,您可以在其中四处移动、躲避来袭的敌人并攻击目标。好吧,今天是你的幸运日!我们将深入了解 pygame 的奇妙世界,这是一个出色的 python 库,即使您只涉足 python 和基本的控制台应用程序,它也可以使游戏开发变得简单且有趣。

如果您已经了解 python 的基础知识(例如变量、循环、条件和函数),那么您就处于开始构建自己的游戏的最佳位置。如果您以前从未使用过 pygame,请不要担心;在这篇文章结束时,您将拥有一个基本但实用的游戏可以展示。那么让我们开始吧!

为什么选择 pygame?

在我们开始编写代码之前,让我们花点时间讨论一下为什么 pygame 是构建游戏的绝佳工具,特别是如果您是初学者。 pygame 是一个 2d 桌面游戏库,它是:

立即学习“Python免费学习笔记(深入)”;

  • 易于学习:pygame 简单明了且适合初学者。它抽象了游戏开发的许多复杂部分,让您专注于构建游戏。
  • 跨平台:使用 pygame 制作的游戏可以在 windows、mac 和 linux 上运行,无需更改代码。
  • 活跃:有一个庞大且乐于助人的使用 pygame 的开发者社区。您可以找到大量教程、示例和论坛,您可以在其中提出问题并分享您的项目。

设置您的环境

在我们开始编码之前,您需要在计算机上安装 python。如果您还没有,请访问 python.org 并下载最新版本。正确设置 python 非常重要,因为它是 pygame 运行的基础。

接下来,您需要安装 pygame。这个库提供了创建游戏所需的工具,例如管理窗口、绘制形状和处理用户输入。安装 pygame 很简单 - 只需打开终端(如果使用 windows,则打开命令提示符)并输入:

pip install pygame

完成后,您就可以开始创建游戏了!

第 1 步:设置游戏窗口

我们需要做的第一件事是创建一个运行游戏的窗口。此窗口是所有操作发生的地方,因此请将其视为游戏的舞台。让我们编写代码来进行设置。

import pygame
import sys

# initialize pygame
pygame.init()

# set up the game window
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("simple shooter game")

# set the frame rate
clock = pygame.time.clock()

# main game loop
while true:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            pygame.quit()
            sys.exit()

    # fill the screen with a color (black in this case)
    screen.fill((0, 0, 0))

    # update the display
    pygame.display.flip()

    # cap the frame rate at 60 frames per second
    clock.tick(60)

让我们分解一下:

  1. 导入库:我们首先导入 pygame 和 sys.libraries。 pygame 库是我们用来创建游戏的库,而 sys 则帮助我们在需要时干净地退出程序。

  2. 初始化 pygame:pygame.init() 行至关重要——它设置了 pygame 需要运行的所有模块。您应该始终在 pygame 项目开始时调用它。

  3. 创建游戏窗口:我们使用 pygame.display.set_mode() 创建一个宽度为 800 像素、高度为 600 像素的窗口。这是我们游戏中所有内容都将显示的地方。 pygame.display.set_caption() 函数让我们将窗口的标题设置为有意义的内容,例如“简单射击游戏”。

  4. 设置帧速率:clock = pygame.time.clock() 行创建一个时钟对象,帮助我们控制游戏运行的速度。通过将帧率设置为每秒60帧,我们保证游戏运行流畅。

  5. 主游戏循环: while true 循环是我们游戏的核心。它持续运行,使我们能够更新游戏并检查关闭窗口等事件。在这个循环中:
    * 事件处理:我们使用 pygame.event.get() 来检查玩家是否想要退出游戏。如果他们这样做,我们调用 pygame.quit() 进行清理,并调用 sys.exit() 退出程序。
    * 绘制背景: screen.fill((0, 0, 0)) 行用黑色填充屏幕,本质上是为下一帧清除它。
    * 更新显示:最后,pygame.display.flip() 更新窗口以显示我们绘制的内容。

当您运行此代码时,您应该看到一个纯黑色的窗口。恭喜!您刚刚建立了游戏的基础。

第 2 步:添加播放器

现在我们有了一个游戏窗口,让我们添加一些更有趣的东西——玩家角色。为简单起见,我们将玩家表示为一个可以左右移动的矩形。敌人也将被表示为矩形,保持简单并专注于游戏逻辑而不是复杂的图形

# player settings
player_width = 50
player_height = 60
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 10
player_speed = 5

# main game loop
while true:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            pygame.quit()
            sys.exit()

    # handle player movement
    keys = pygame.key.get_pressed()
    if keys[pygame.k_left] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.k_right] and player_x 



<p>事情是这样的:</p>

<ol>
<li><p>玩家设置:我们定义玩家的大小(player_width和player_height)、起始位置(player_x和player_y)和速度(player_speed)。计算起始位置,以便玩家在窗口底部附近水平居中显示。</p></li>
<li><p>处理玩家移动:在主游戏循环中,我们使用 pygame.key.get_pressed() 检查按下了哪些键。此函数返回键盘上所有键的列表,其中当前按下的键为 true 值。如果按下左箭头键,并且玩家不在屏幕边缘,我们通过从player_x中减去player_speed来将玩家向左移动。同样,如果按下右箭头键,我们会将玩家移动到右侧。</p></li>
<li><p>绘制玩家: pygame.draw.rect() 函数在屏幕上绘制一个矩形(我们的玩家)。参数是要绘制的屏幕、矩形的颜色(在本例中为蓝色阴影)以及矩形的位置和大小。</p></li>
</ol><p>当您运行此代码时,您将看到一个蓝色矩形,您可以使用箭头键左右移动。这个矩形是我们的玩家,它将成为我们游戏的英雄。</p>

<h2>
  
  
  第三步:射击子弹
</h2>

<p>没有射击的射击游戏算什么?让我们添加发射子弹的能力。每次玩家按下空格键时,我们都会创建一颗子弹。<br></p>

<pre class="brush:php;toolbar:false"># bullet settings
bullet_width = 5
bullet_height = 10
bullet_speed = 7
bullets = []

# main game loop
while true:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            pygame.quit()
            sys.exit()
        if event.type == pygame.keydown:
            if event.key == pygame.k_space:
                # create a bullet at the current player position
                bullet_x = player_x + player_width // 2 - bullet_width // 2
                bullet_y = player_y
                bullets.append(pygame.rect(bullet_x, bullet_y, bullet_width, bullet_height))

    # handle player movement
    keys = pygame.key.get_pressed()
    if keys[pygame.k_left] and player_x &gt; 0:
        player_x -= player_speed
    if keys[pygame.k_right] and player_x  0]

    # fill the screen with black
    screen.fill((0, 0, 0))

    # draw the player
    pygame.draw.rect(screen, (0, 128, 255), (player_x, player_y, player_width, player_height))

    # draw the bullets
    for bullet in bullets:
        pygame.draw.rect(screen, (255, 255, 255), bullet)

    # update the display
    pygame.display.flip()

    # cap the frame rate at 60 fps
    clock.tick(60)

让我们分解一下:

  1. 项目符号设置:我们定义项目符号的大小(bullet_width 和bullet_height)、速度(bullet_speed)和一个列表(项目符号)来跟踪所有活动的项目符号。

  2. 发射子弹:在主循环内,我们检查 keydown 事件,该事件在按下任意键时发生。如果按下空格键(pygame.k_space),我们会在玩家当前位置创建一个新子弹。子弹的 x 位置计算为与玩家水平居中,然后将子弹添加到子弹列表中。

  3. 更新项目符号位置:项目符号列表中的每个项目符号通过从其 y 位置减去bullet_speed 来向上移动。从屏幕顶部移出的项目符号将从列表中删除以节省内存。

  4. 绘制子弹:我们循环遍历子弹列表并使用 pygame.draw.rect() 在屏幕上绘制每个子弹。

现在,当你运行游戏时,按空格键将从玩家的位置发射白色子弹。子弹向上移动,就像您在射击游戏中所期望的那样。

第四步:添加敌人

让我们通过添加玩家需要射击的敌人来使游戏更具挑战性。我们将首先创建一些沿着屏幕向玩家移动的敌人。再次强调,为了简单起见,我们将敌人表示为红色矩形。

import random

# enemy settings
enemy_width = 50
enemy_height = 60
enemy_speed = 2
enemies = []

# spawn an enemy every 2 seconds
enemy_timer = 0
enemy_spawn_time = 2000

# main game loop
while true:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            pygame.quit()
            sys.exit()
        if event.type == pygame.keydown:
            if event.key == pygame.k_space:
                bullet_x = player_x + player_width // 2 - bullet_width // 2
                bullet_y = player_y
                bullets.append(pygame.rect(bullet_x, bullet_y, bullet_width, bullet_height))

    # handle player movement
    keys = pygame.key.get_pressed()
    if keys[pygame.k_left] and player_x &gt; 0:
        player_x -= player_speed
    if keys[pygame.k_right] and player_x  0]

    # update enemy positions and spawn new ones
    current_time = pygame.time.get_ticks()
    if current_time - enemy_timer &gt; enemy_spawn_time:
        enemy_x = random.randint(0, screen_width - enemy_width)
        enemy_y = -enemy_height
        enemies.append(pygame.rect(enemy_x, enemy_y, enemy_width, enemy_height))
        enemy_timer = current_time

    for enemy in enemies:
        enemy.y += enemy_speed

    # remove enemies that are off the screen
    enemies = [enemy for enemy in enemies if enemy.y 



<p>以下是我们添加敌人的方法:</p>

<ol>
<li><p>敌人设置:我们定义大小(enemy_width和enemy_height)、速度(enemy_speed)和列表(敌人)来跟踪所有活动的敌人。</p></li>
<li><p>生成敌人:我们使用计时器每 2 秒生成一个新敌人。当前时间通过 pygame.time.get_ticks() 进行跟踪。如果自最后一个敌人生成以来已经过去了足够的时间,我们会在屏幕上方的随机水平位置创建一个新的敌人(因此它向下移动)。然后,该敌人将被添加到敌人列表中。</p></li>
<li><p>更新敌人位置:敌人列表中的每个敌人都会通过将敌人速度添加到其 y 位置来向下移动。如果敌人移出屏幕底部,它就会从列表中删除。</p></li>
<li><p>绘制敌人:我们循环遍历敌人列表并使用 pygame.draw.rect() 在屏幕上绘制每个敌人。</p></li>
</ol><p>当您运行此代码时,您会看到红色矩形(我们的敌人)从屏幕顶部掉落。游戏已经初具规模!</p>

<h2>
  
  
  第 5 步:检测碰撞
</h2>

<p>现在,让我们添加一些逻辑,以便当子弹击中敌人时,子弹和敌人都会消失。这涉及检测子弹和敌人之间的碰撞。<br></p>

<pre class="brush:php;toolbar:false"># collision detection function
def check_collision(rect1, rect2):
    return rect1.colliderect(rect2)

# main game loop
while true:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            pygame.quit()
            sys.exit()
        if event.type == pygame.keydown:
            if event.key == pygame.k_space:
                bullet_x = player_x + player_width // 2 - bullet_width // 2
                bullet_y = player_y
                bullets.append(pygame.rect(bullet_x, bullet_y, bullet_width, bullet_height))

    # handle player movement
    keys = pygame.key.get_pressed()
    if keys[pygame.k_left] and player_x &gt; 0:
        player_x -= player_speed
    if keys[pygame.k_right] and player_x  0]

    # update enemy positions and spawn new ones
    current_time = pygame.time.get_ticks()
    if current_time - enemy_timer &gt; enemy_spawn_time:
        enemy_x = random.randint(0, screen_width - enemy_width)
        enemy_y = -enemy_height
        enemies.append(pygame.rect(enemy_x, enemy_y, enemy_width, enemy_height))
        enemy_timer = current_time

    for enemy in enemies:
        enemy.y += enemy_speed

    # check for collisions
    for bullet in bullets[:]:
        for enemy in enemies[:]:
            if check_collision(bullet, enemy):
                bullets.remove(bullet)
                enemies.remove(enemy)
                break

    # remove enemies that are off the screen
    enemies = [enemy for enemy in enemies if enemy.y 



<p>这就是我们所做的:</p>

<ol>
<li><p>碰撞检测:我们定义了一个函数 check_collision,它获取两个矩形的位置和大小,并使用 colliderect() 检查它们是否重叠。这就是我们检测子弹是否击中敌人的方法。</p></li>
<li><p>移除碰撞对象:在主循环内,更新子弹和敌人的位置后,我们检查是否有子弹与任何敌人发生碰撞。如果有,子弹和敌人都会从各自的列表中删除。</p></li>
</ol><p>现在,当你运行游戏时,击中敌人的子弹将使敌人消失。您已经创建了一款基本但功能齐全的射击游戏!</p>

<p><strong>重要提示</strong>:在这个简单的游戏中,与敌人碰撞不会受到惩罚。玩家可以穿过敌人而不会受到伤害或输掉游戏。这使事情变得简单,但可能是您想要在更高级的版本中更改的内容。</p>

<h2>
  
  
  把它们放在一起
</h2>

<p>如果您需要,这里是我们写的所有内容:<br></p>

<pre class="brush:php;toolbar:false">import pygame
import sys
import random

# Initialize PyGame
pygame.init()

# Set up the game window
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Simple Shooter Game")

# Set the frame rate
clock = pygame.time.Clock()

# Player settings
player_width = 50
player_height = 60
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 10
player_speed = 5

# Bullet settings
bullet_width = 5
bullet_height = 10
bullet_speed = 7
bullets = []

# Enemy settings
enemy_width = 50
enemy_height = 60
enemy_speed = 2
enemies = []

# Spawn an enemy every 2 seconds
enemy_timer = 0
enemy_spawn_time = 2000

# Collision detection function
def check_collision(rect1, rect2):
    return pygame.Rect(rect1).colliderect(pygame.Rect(rect2))

# Main game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Create a bullet at the current player position
                bullet_x = player_x + player_width // 2 - bullet_width // 2
                bullet_y = player_y
                bullets.append([bullet_x, bullet_y])

    # Handle player movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x &gt; 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x  0]

    # Update enemy positions and spawn new ones
    current_time = pygame.time.get_ticks()
    if current_time - enemy_timer &gt; enemy_spawn_time:
        enemy_x = random.randint(0, screen_width - enemy_width)
        enemy_y = -enemy_height
        enemies.append([enemy_x, enemy_y])
        enemy_timer = current_time

    for enemy in enemies:
        enemy[1] += enemy_speed

    # Check for collisions
    for bullet in bullets[:]:
        for enemy in enemies[:]:
            if check_collision((bullet[0], bullet[1], bullet_width, bullet_height),
                               (enemy[0], enemy[1], enemy_width, enemy_height)):
                bullets.remove(bullet)
                enemies.remove(enemy)
                break

    # Remove enemies that are off the screen
    enemies = [enemy for enemy in enemies if enemy[1] 



<h2>
  
  
  接下来是什么?
</h2>

<p>恭喜,您刚刚使用 pygame 构建了第一个简单的射击游戏!但这只是开始——您还有很多事情可以做:</p>

  • 添加评分系统:跟踪玩家消灭了多少敌人并在屏幕上显示分数。
  • 创造不同的敌人类型:让敌人以不同的方式移动、反击或多次击中来消灭。
  • 增强图形:用玩家、子弹和敌人的图像替换矩形。
  • 添加音效:通过添加射击、击中敌人和其他动作的声音,让游戏更加身临其境。
  • 引入关卡:添加不同关卡或一波敌人,以随着玩家的进步而增加难度。
  • 添加玩家生命值和伤害:允许玩家在与敌人碰撞时受到伤害,如果生命值为零,则输掉游戏。

pygame 非常灵活,因此请尽情发挥您的想象力并不断进行实验。您使用代码的次数越多,您学到的就越多,您的游戏就会变得越好。

这是一个包裹!

就是这样!只需几个步骤,您就可以从一个空窗口变成一个正常运行的射击游戏。无论您是计划扩展该项目还是转向新的事物,您都在游戏开发之旅中迈出了一大步。请随时分享您的进展或提出问题——我随时为您提供帮助!

您有任何问题或意见吗?请务必将它们留在这里或在大多数社交媒体平台上通过@lovelacecoding 与我联系。感谢您一起编码!

卓越飞翔博客
上一篇: Laravel 入门:查询生成器初学者指南
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏