尝试添加Bullet类的实例时出现属性错误

2024-10-06 12:06:48 发布

您现在位置:Python中文网/ 问答频道 /正文

https://github.com/TheManhattan/ErrorCode

我提供了一个到存储库的链接,其中包含完整的代码,因为我觉得有必要完全理解这个问题。我正在使用pygame创建一个游戏,我正在尝试添加子弹行为。追踪把我拉向子弹课。你知道吗

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.矩形但是我能找到的关于这个主题的一切都告诉我用法和语法确实是正确的。你知道吗

所以,从这里开始,假设我只是手动输入宽度和高度,而不是引用Settings类。。我得到了相同的回溯,错误对应于它下面的一行。这对我来说更让人困惑,因为在为项目符号矩形定义属性时,我甚至看不到Settings类是如何发挥作用的。Ship类是从run\u 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'

任何你们能提供的见解都将不胜感激。你知道吗

先谢谢你


Tags: inpyprojectgamesettingslinepygameusers
1条回答
网友
1楼 · 发布于 2024-10-06 12:06:48

问题出在游戏中_函数.py. 您对check_keydown_events的调用与其签名不匹配。你知道吗

注意,check_keydown_events需要5个参数,依次为“event”、“ship”、“ai\u settings”、“screen”和“bullets”。在check_events内调用check_keydown_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.表面对象。你知道吗

您可以将任何您想要的内容传递到方法中,但是如果它没有方法所期望的属性,您将得到这种异常。更改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):
     ...

相关问题 更多 >