重构:_check_events()方法和_update_screen()方法

在大型项目中,您通常会在添加更多代码之前重构您编写的代码。重构可以简化您已经编写的代码的结构,使其更易于构建。在本节中,我们将把越来越冗长的 run_game() 方法分解为两个辅助方法。辅助方法确实可以在类内部工作,但不适合由类外部的代码使用。在 Python 中,单个前导下划线表示辅助方法。

_check_events()方法

我们将把管理事件的代码移至一个名为 _check_events() 的单独方法。 这将简化 run_game() 并隔离事件管理循环。 隔离事件循环允许您将事件与游戏的其他方面分开管理,例如更新屏幕。

下面是带有新 _check_events() 方法的 AlienInvasion 类,它只影响 run_game() 中的代码:

alien_invasion.py
    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events() (1)
            self._update_screen()
            self.clock.tick(60)

    def _check_events(self): (2)
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

我们创建一个新的 _check_events() 方法❷,并将检查玩家是否单击关闭窗口的代码行移动到这个新方法中。

要从类内部调用方法,请使用变量 self 和点符号以及方法名称❶。 我们在 run_game() 的 while 循环内部调用该方法。

_update_screen()方法

为了进一步简化 run_game(),我们将更新屏幕的代码移至名为 _update_screen() 的单独方法中:

alien_invasion.py
    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events() (1)
            self._update_screen()
            self.clock.tick(60)

    def _check_events(self): (2)
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        pygame.display.flip()

我们将绘制背景和船舶以及翻转屏幕的代码移至 _update_screen()。 现在 run_game() 中的主循环主体更加简单。 很容易看出我们正在寻找新事件,更新屏幕,并在每次循环中滴答时钟。

如果您已经构建了许多游戏,您可能会首先将代码分解为这样的方法。 但如果您从未处理过这样的项目,您一开始可能不会确切地知道如何构建代码。 这种方法让您了解现实的开发过程:您开始尽可能简单地编写代码,然后随着项目变得更加复杂而重构它。

现在我们已经重组了代码以使其更容易添加,我们可以致力于游戏的动态方面!

自己试试
12-1.Blue Sky

制作一个蓝色背景的 Pygame 窗口。

12-2.Game Character

查找您喜欢的游戏角色的位图图像或将图像转换为位图。 创建一个在屏幕中心绘制字符的类,然后将图像的背景颜色与屏幕的背景颜色相匹配,反之亦然。