我一直收到这个错误。这是完整的追溯。
Traceback (most recent call last):
File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 23, in
<module>
run_game()
File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 13, in
run_game
player = Player(ai_settings, screen)
File "C:\Users\Luc\PycharmProjects\game_practice\player.py", line 8, in
__init__
self.rect.centerx = screen.rect.left
AttributeError: 'pygame.Surface' object has no attribute 'rect'
以下是有问题的“播放器”文件的代码:
class Player:
def __init__(self, ai_settings, screen):
self.screen = screen
self.screen_rect = screen.get_rect()
self.rect = pygame.Rect((0, 0), (ai_settings.player_width,
ai_settings.player_height))
self.rect.centerx = screen.rect.left
self.rect.centery = screen.rect.ai_settings.screen_height / 2
self.color = ai_settings.player_color
def draw_player(self):
pygame.draw.rect(self.screen, self.color, self.rect)
当我评论这两行时:
self.rect.centerx = screen.rect.left
self.rect.centery = screen.rect.ai_settings.screen_height / 2
程序运行的矩形初始化为(0,0),就像它应该的那样,所以当我包含其他行时,我不确定为什么对象有属性错误。
答案 0 :(得分:0)
screen
是一个没有rect
属性的pygame.Surface,但你可以通过调用screen.get_rect()
来获取表面大小的矩形:
self.screen_rect = screen.get_rect()
现在您只需使用self.screen_rect
代替screen.rect
,您的代码就可以了。
# To place the player at the midleft.
self.rect.midleft = self.screen_rect.midleft