外星人入侵 - Pygame - 外星人走出屏幕

我正在根据 Python 速成课程书制作外星人入侵游戏项目,并陷入了外星人舰队应该向右行驶直到到达屏幕右边缘、改变方向并向左行驶等部分。

问题是我的外星人确实改变了方向,但只有当方块中的第一个外星人(第一个一直在左边)击中屏幕的右边缘时。他右边的所有外星人都经过了右边的边缘。

似乎它无法识别右侧外星人的矩形,该矩形应该首先击中右侧边缘,但只能识别左侧第一个外星人的矩形......


我严格按照书上的说明进行操作,并且检查了 3 次,问题可能出在哪里。你能帮我找出问题所在吗?


settings.py


class Settings:

    """A class to store all settings for Alien Invasion."""


    def __init__(self):

        """Initialize the game's settings."""

        # Screen settings

        self.screen_width = 1200

        self.screen_height = 800

        self.bg_color = (230, 230, 230)

        self.ship_speed = 1.5


        # Bullet settings

        self.bullet_speed = 1.0

        self.bullet_width = 3

        self.bullet_height = 15

        self.bullet_color = (60, 60, 60)

        self.bullets_allowed = 3


        # Alien settings

        self.alien_speed = 1.0

        self.fleet_drop_speed = 10

        # fleet_direction of 1 represents right; -1 represents left.

        self.fleet_direction = 1

alien.py


import pygame

from pygame.sprite import Sprite


class Alien(Sprite):

    """A class to represent a single alien in the fleet."""


    def __init__(self, ai_game):

        """Initialize the alien and set its starting postion."""

        super().__init__()

        self.screen = ai_game.screen

        self.settings = ai_game.settings


        # Load the alien image and set its rect attribute.

        self.image = pygame.image.load('images/alien.bmp')

        self.rect = self.image.get_rect()


        # Start each new alien near the top left of the screen.

        self.rect.x = self.rect.width

        self.rect.y = self.rect.height


        # Store the alien's exact horizontal position.

        self.x = float(self.rect.x)


    def check_edges(self):

        """Return True if an alien is at edge of screen."""

        screen_rect = self.screen.get_rect()

        if self.rect.right >= screen_rect.right or self.rect.left <= 0:

            return True




波斯汪
浏览 29回答 1
1回答

温温酱

这是缩进的问题。你需要找到第一个撞到边缘的外星人,然后打破循环。实际上,你总是在列表中的第一个敌人之后中断循环:class AlienInvasion:    # [...]    def _check_fleet_edges(self):        """Respond appropriately if any aliens have reached an edge."""        for alien in self.aliens.sprites():            if alien.check_edges():                self._change_fleet_direction()                #-->| INDENTATION                break                        # break <-- DELETE
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python