【发布时间】:2021-12-30 20:38:23
【问题描述】:
我只是按照“python 速成课程第 2 版”一书编写代码,然后 它的代码与书中的完全相同。
这是正在运行的 main.py 文件。
import pygame
import sys
from settings import Settings
from ship import Ship
class AlienInvasion:
"""overall class to manage game assets and behavios"""
def __init__(self):
"""initialize the game, and create game resources"""
pygame.init()
self.settings = Settings()
# Window
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Kelvis Invasion")
self.ship = Ship(self)
def run_game(self):
"""main loop for the game"""
while True:
# watch for ketboard and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# redraw the screen
self.screen.fill(self.settings.bg_color)# set background color
self.ship.blitme()
# draw the most recent screen
pygame.display.flip()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
这是 Ship 类所在的第二个文件。
import pygame
class Ship:
"""a class to manage the ship"""
def __init__(self, ai_game):
"""initialize the ship and set its starting position"""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
# load the ship image and get its rect.
self.image = pygame.image.load("Alieninvasion\\images\\ship.png")
self.rect = pygame.image.get_rect()
# start euch ship at the midbottom of the screen
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""draws the ship"""
self.screen.blit(self.image, self.rect)
这是错误代码。
Traceback (most recent call last):
File "c:\Python\Python 3.10\Scripts\projects\Alieninvasion\main.py", line 44, in <module>
ai = AlienInvasion()
File "c:\Python\Python 3.10\Scripts\projects\Alieninvasion\main.py", line 22, in __init__
self.ship = Ship(self)
File "c:\Python\Python 3.10\Scripts\projects\Alieninvasion\ship.py", line 13, in __init__
self.rect = pygame.image.get_rect()
AttributeError: module 'pygame.image' has no attribute 'get_rect'
也许这是解决我的问题的简单方法,但我不明白这是怎么回事 功能
【问题讨论】:
-
这是一个错字。
self.rect = self.image.get_rect()而不是self.rect = pygame.image.get_rect() -
就是这样。谢谢你,我真的很沮丧......
标签: pygame attributeerror