我们使用一些必要的Cookie来确保网站正常运行。

我们使用可选的 Cookie,具体详情请参阅我们的Cookie政策,用于记住您的设置并了解您如何使用我们的网站。

编写致敬《Excitebike》的游戏代码 | 《Wireframe》第66期

动手打造一款横向卷轴竞速游戏,致敬NES经典之作《Excitebike》。马克·范斯通(Mark Vanstone)为你奉上完整源码,内容直接来自本期全新上市的《Wireframe》杂志——《线框图》杂志中所解释的那样,该期刊现已发布。

Nintendo's original Excitebike - the basis for this month's Source Code.
任天堂原版大作至今仍“轮”趣十足(抱歉,玩了个双关梗)

多数早期电子游戏最初均为街机(coin-op)形式,但1984年,任天堂首次在NES主机上推出《Excitebike》。同年晚些时候,任天堂又将其移植至街机平台;此时它已成为任天堂最畅销的主机游戏之一。这款流畅的横向卷轴摩托车竞速游戏,为后来《超级马里奥》中角色的移动方式奠定了关键技术基础。

《Excitebike》允许玩家与三名电脑控制的对手同场竞技,赛道上设有用于跳跃的坡道及需避开的障碍物。玩家需尽力维持摩托车的动量,以争取最佳圈速。本例中,我们将复刻该滚动式赛道——其滚动速度随玩家加速而加快;同时添加跳跃坡道与障碍物。

借助 Pygame Zero 及用于记录圈速的 time 模块,我们需要创建一个始终固定于同一X坐标位置的摩托车 Actor(游戏角色对象)。摩托车的Y坐标则会随其在不同赛道车道间切换或飞跃坡道而变化。我们可用一个整数列表来表示赛道数据,其中每个整数代表一个赛道区块:0 表示普通赛道区块,1 表示跳跃坡道区块,2 表示起/终点线。另设一列表标识障碍物位置,其中数字 1 至 4 对应四条赛道车道,0 表示无障碍物。

An image of our motocross racing homage to Excitebike.
我们向《Excitebike》致敬的越野摩托车竞速游戏

该draw() function is straightforward and just draws a background, then calls the drawTrack() function, draws the bike Actor, and then writes text to show us the lap timer and the last lap completion time. In the update() function, we need to capture the left and right keys to slow down and speed up the bike, and then calculate the track position based on the bike’s current speed. We can keep the track looping round by detecting when we’ve reached the end of the data, and then set the trackPos variable back to 0 and reset our lap time counter. We want to snap the bike to the four lanes of the track, but we also need to allow the player to move the bike from lane to lane, which we do by capturing the up and down keys in the on_key_down() function.

我们可设定bike.direction to -1 or 1, and the update() function will move the bike up or down one lane. We can also make the bike look like it’s vibrating a little by alternating between two frames, depending on how fast the bike is going.

该drawTrack() function looks at our track list, starting from the block determined by the trackPos variable. Each block is 100 pixels wide, and we get the smooth scrolling effect by drawing the blocks at an offset based on the trackOffset variable that cycles between 99 and 0. This is the remainder when we divide the trackPos variable by 100. We then draw nine blocks across the screen, depending on our track and debris data.

The Python/Pygame Zero code behind our arcade racer.
以下是马克编写的《Excitebike》风格竞速游戏代码。要在你的系统上运行此程序,首先需安装 Pygame Zero。完整安装说明请见此处。全部代码清单可于我们的 GitHub 仓库中查阅

我们还需检测摩托车是否撞上坡道;若发生碰撞,则需让摩托车开始向上倾斜,并使其Y坐标沿坡道轨迹运动。当摩托车抵达坡顶后,须令其回落至赛道表面。下落过程中,我们向前倾斜摩托车角度;若落地瞬间角度过大,则摩托车将减速并损失动量。玩家需精准判断入坡时的速度,方能提升单圈成绩。此外,还需检测障碍物——一旦摩托车碾过障碍区域,即刻减速。

这就是我们自制的《Excitebike》致敬作品。原版游戏包含AI对手及尺寸各异的坡道,这些进阶功能就留待你自行实现了。

获取《Wireframe》第66期纸质版

你可以在更多类似文章在《Wireframe》第66期中,可直接从树莓派出版社购买——我们支持全球配送。

The cover of Wireframe magazine issue #66, available now.
全新一期以街机竞速游戏为主题的《Wireframe》现已发售

若你更青睐数字版杂志,亦可下载《Wireframe》第66期的免费PDF版!

1条评论

Willems Davy avatar

我很惊讶,实现这样的游戏只需如此少的代码;以前我完全不知道如何制作这类游戏,现在我知道了!:) 再次感谢

评论已关闭