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

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

打造 Boing!,我们用 Python 致敬 Pong 的作品

继昨天介绍 Pong 之后,今天我们来分享 Boing!,这是 Eben Upton 专为经典编程独家打造的基于 Python 的 Pong 致敬之作。请继续阅读,深入了解 Boing!的代码。

您可以在经典编程一书中找到 Boing!代码的下载链接,该书现已推出多种格式。请务必阅读完今天的博文,以获取专属经典编程优惠。

从 Pong 到 Boing!

为了展示如何编写类似 Pong 的游戏,我们使用 Pygame Zero 创建了 Boing!,这是一款对初学者友好的 Python 游戏制作工具。这是学习游戏运作原理的绝佳起点——游戏在单个屏幕上运行,无需任何滚动,游戏中只有三个移动物体(两个球拍和一个球),而且电脑玩家的人工智能可以非常简单——甚至完全不需要,如果您只打算做多人游戏的话。在本作中,我们同时提供了单人和双人模式。

代码可分为三个部分。首先是初始启动代码。我们从其他 Python 模块导入内容,以便在我们的代码中使用它们。然后我们进行检查,确保玩家拥有足够新版本的 Python 和 Pygame Zero。我们设置WIDTH and HEIGHT variables, which are used by Pygame Zero when creating the game window. We also create two small helper functions which are used by the code.

下一部分篇幅最大。我们创建了四个类:Impact, Ball, Bat, and Game. The first three classes inherit from Pygame Zero’s Actor class, which amongst other things keeps track of an object’s location in the game world, and takes care of loading and displaying sprites. Bat and Ball define the behaviour of the corresponding objects in the game, while Impact is used for an animation which is displayed briefly whenever the ball bounces off something. The Game class’s job is to create and keep track of the key game objects, such as the two bats and the ball.

再往下,我们会看到update and draw functions. Pygame Zero calls these each frame, and aims to maintain a frame rate of 60 frames per second. Gameplay logic, such as updating the position of an object or working out if a point has been scored, should go in update, while in draw we tell each of the Actor objects to draw itself, as well as displaying backgrounds, text, and suchlike.

我们的update and draw functions make use of two global variables: state and game. At any given moment, the game can be in one of three states: the main menu, playing the game, or the game-over screen. The update and draw functions read the state variable and run only the code relevant to the current state. So if state is currently State.MENU, for example, update checks to see if the 空间栏或上下方向键被按下,并相应地更新菜单,而draw displays the menu on the screen. The technical term for this kind of system is ‘finite state machine’.

Game 类的任务是创建并跟踪关键游戏对象

该game variable references an instance of the Game class as described above. The __init__ (constructor) method of Game optionally receives a parameter named controls. When we create a new Game object for the main menu, we don’t provide this parameter and so the game will therefore run in attract mode – in other words, while you’re on the main menu, you’ll see two computer-controlled players playing against each other in the background. When the player chooses to start a new game, we replace the existing Game instance with a new one, initialising it with information about the controls to be used for each player – if the controls for the second player are not specified, this indicates that the player has chosen a single-player game, so the second will be computer-controlled.

两种移动方式

在 Boing!中,Bat and Ball classes inherit from Pygame Zero’s Actor class, which provides a number of ways to specify an object’s position. In this game, as well as games in later chapters, we’re setting positions using the x and y attributes, which by default specify where the centre of the sprite will be on the screen. Of course, we can’t just set an object’s position at the start and be done with it – if we want it to move as the game progresses, we need to update its position each frame. In the case of a Bat, movement is very simple. Each frame, we check to see if the relevant player (which could be a human or the computer) wants to move – if they do, we either subtract or add 4 from the bat’s Y coordinate, depending on whether they want to move up or down. We also ensure that the bat does not go off the top or bottom of the screen. So, not only are we only moving along a single axis, our Y coordinate will always be an integer (i.e. a whole number). For many games, this kind of simple movement is sufficient. Even in games where an object can move along both the X and Y axes, we can often think of the movement along each axis as being separate. For example, in the next chapter’s game, Cavern, the player might be pressing the right arrow key and therefore moving along the X axis at 4 pixels per frame, while also moving along the Y axis at 10 pixels per frame due to gravity. The movement along each axis is independent of the other.

球能够以任意角度移动,因此无论方向如何,都需要保持相同的速度

对于Ball, things get a bit more complicated. Not only can it move at any angle, it also needs to move at the same speed regardless of its direction. Imagine the ball moving at one pixel per frame to the right. Now imagine trying to make it move at a 45° angle from that by making it move one pixel right and one pixel up per frame. That’s a longer distance, so it would be moving faster overall. That’s not great, and that’s before we’ve even started to think about movement in any possible direction.

解决方案是利用向量数学和三角学。在 2D 游戏的语境中,向量只是一对数字:X 和 Y。向量有多种用途,但最常见的是表示位置或方向。

您会注意到Ball class has a pair of attributes, dx and dy. Together these form a vector representing the direction in which the ball is heading. If dx and dy are 1 and 0.5, then each time the ball moves, it’ll move by one pixel on the X axis and a half a pixel on the Y axis. What does it mean to move half a pixel? When a sprite is drawn, Pygame Zero will round its position to the nearest pixel. So the end result is that our sprite will move down the screen by one pixel every other frame, and one pixel to the right every frame (Figure 1).

我们仍需确保对象无论朝哪个方向移动,都能保持一致的速度。我们需要做的是确保方向向量始终是“单位向量”——即表示距离为一的向量(在本例中,一代表一个像素,但在某些游戏中可能代表不同的距离,如一米)。在代码顶部附近,您会注意到一个名为normalised. This takes a pair of numbers representing a vector, uses Python’s math.hypot function to calculate the length of that vector, and then divides both the X and Y components of the vector by that length, resulting in a vector which points in the same direction but has a length of one (Figure 2).

向量数学是一个庞大的领域,我们在这里只是触及了皮毛。您可以在网上找到许多教程,我们还建议了解一下 Pygame(Pygame Zero 所基于的库)中的 Vector2 类。

体验 Boing!

更新 Raspbian体验 Boing!及其他经典编程在您的 Raspberry Pi 上畅玩游戏。

完整的 BOING! 教程,包括挑战任务、详细讲解以及可下载代码的链接,均收录于经典编程,这是 Raspberry Pi Press 出版的最新书籍。

我们提供£1 的优惠经典编程,如果您在明天午夜前从 Raspberry Pi Press 在线商店订购。立即访问商店,或在结账时使用折扣码PONG,前提是您在明天午夜前完成购买。

一如既往,Code the Classics 的免费 PDF 版本电子版可在 Wireframe 网站获取,但我们强烈推荐购买实体书,因为它装帧精美,是送给任何游戏和/或编程爱好者的绝佳礼物。

2条评论

Scott Whillas avatar

没法让它运行起来。可以在 1 人和 2 人模式之间切换,但就是无法开始游戏

Patrick avatar

您需要按空格键开始游戏。然后玩家可使用上/下方向键或和按键来控制,另一位玩家可使用和按键来控制。希望对您有所帮助!

评论已关闭