Python Crash Course横向射击项目:右上角生成外星人多列失败求助
问题:横向射击游戏外星人多列生成失败排查
我正在做《Python Crash Course》里的横向射击项目,想从屏幕右上角生成外星人网格。现在只能成功生成右上角的单列外星人,但加代码尝试生成向左延伸的多列时,完全出不来外星人。下面是两段代码:一段是没法生成多列的完整代码,一段是能正常生成单列的代码。我要实现从右到左填充屏幕的多列外星人布局,求问问题出在哪。
无法生成多列的代码
def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_x > (3 * alien_width): while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height current_y = alien_height current_x -= 3 * alien_width
可正常生成单列的代码
def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height
问题分析与修复
你的代码有两个核心问题:
外层循环条件完全不成立:初始
current_x设为alien_width,而循环条件是current_x > 3 * alien_width,显然单个外星人宽度不可能大于3倍自身宽度,外层循环直接跳过,根本不会生成多列。未设置外星人的X坐标:即使外层循环执行了,你也没给外星人设置
rect.x属性,所有外星人都会默认在屏幕左侧(初始位置),根本看不到右上角的多列效果。
修复后的代码
def _create_fleet(self): """创建外星人舰队""" alien = Alien(self) alien_width, alien_height = alien.rect.size # 从屏幕右上角开始,留出一个外星人宽度的边距 current_x = self.settings.screen_width - alien_width current_y = alien_height # 当左侧还有足够空间放下外星人时,继续生成列 while current_x >= alien_width: while current_y < (self.settings.height - alien_height): new_alien = Alien(self) # 设置外星人的X、Y坐标 new_alien.x = current_x new_alien.rect.x = current_x new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) # 纵向间隔2个外星人高度 current_y += 2 * alien_height # 重置Y坐标,开始新的一列 current_y = alien_height # 向左移动3个外星人宽度,控制列与列的间距 current_x -= 3 * alien_width
关键修复点说明
- 把初始
current_x改为屏幕右侧位置(self.settings.screen_width - alien_width),确保从右上角开始生成 - 外层循环条件改为
current_x >= alien_width,保证左侧还有空间生成下一列 - 给每个外星人设置
rect.x和x属性,让它们出现在正确的横向位置 - 如果你的设置里屏幕高度是
screen_height而非height,记得对应替换
内容的提问来源于stack exchange,提问作者Mr Cs
相关产品推荐
相关产品推荐

