https://github.com/TheManhattan/ErrorCode
我提供了一个包含完整代码的存储库链接,因为我觉得可能有必要完全掌握问题。我正在使用pygame创建游戏,我正在尝试添加子弹行为。追溯将我拉向Bullet类。
Traceback (most recent call last):
File "C:/Users/Andrew/Desktop/Shooting Game Project/shooting_game.py", line 32, in <module>
run_game()
File "C:/Users/Andrew/Desktop/Shooting Game Project/shooting_game.py", line 26, in run_game
gf.check_events(ai_settings, screen, ship, bullets)
File "C:\Users\Andrew\Desktop\Shooting Game Project\game_functions.py", line 17, in check_events
check_keydown_events(event, ai_settings, screen, ship, bullets)
File "C:\Users\Andrew\Desktop\Shooting Game Project\game_functions.py", line 35, in check_keydown_events
new_bullet = Bullet(ai_settings, screen, ship)
File "C:\Users\Andrew\Desktop\Shooting Game Project\bullet.py", line 14, in __init__
self.rect = pygame.Rect(0, 0, self.ai_settings.bullet_width, self.ai_settings.bullet_height)
AttributeError: 'pygame.Surface' object has no attribute 'bullet_width'
我认为这必须是pygame.Rect的错误语法或用法,但我能在主题上找到的一切告诉我,用法和语法确实是正确的。
所以,继续这个并假设我只是手动输入宽度和高度而不是引用Settings类..我得到相同的回溯,其错误对应于它下面的行。这对我来说更加令人困惑,因为在定义项目符号矩形的属性时,我无法看到Settings类是如何发挥作用的。 Ship类是从run_game()函数中创建的Ship实例引用的,但Ship类的rectangle属性不引用存储在Settings类中的任何信息。
File "C:\Users\Andrew\Desktop\Shooting Game Project\bullet.py", line 15, in __init__
self.rect.center.x = ship.rect.centerx
AttributeError: 'Settings' object has no attribute 'rect'
我们非常感谢您提供的任何见解。
提前谢谢
答案 0 :(得分:1)
问题在于game_functions.py。您对check_keydown_events
的来电与其签名不符。
请注意,check_keydown_events
期望按顺序称为“event”,“ship”,“ai_settings”,“screen”和“bullets”的5个参数。你在check_keydown_events
内调用check_events
并传入相同的5个参数,但顺序错误。
def check_events(ai_settings, screen, ship, bullets):
...
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
...
def check_keydown_events(event, ship, ai_settings, screen, bullets):
...
check_keydown_events
的第三个参数是ai_settings
,但是当你调用它时,第三个参数是一个名为screen
的变量,它是一个pygame.Surface对象。
您可以将任何想要的内容传递给方法,但如果它没有该方法所期望的属性,您将获得此类异常。更改check_keydown_events
的签名以匹配调用应该有效:
def check_events(ai_settings, screen, ship, bullets):
...
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
...
def check_keydown_events(event, ai_settings, screen, ship, bullets):
...