我试图从Python Crash Course中完成项目,在项目中间我遇到了这个错误,我无法弄明白为什么,我已经得到了alien_invasion.py,settings.py和ship.py文件,这里是:
这是主文件alien_invasion.py
import sys
import pygame
from settings import Settings
from ship import Ship
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width,
ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
ship = Ship(screen)
bg_color = (230, 230, 230)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme()
pygame.display.flip()
run_game()
这是settings.py
class Settings():
def __init__(self):
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (230, 230, 230)
这个是ship.py
import pygame
class Ship():
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
def blitme(self):
self.screen.blit(self.image, self.rect)
和它说:
Traceback (most recent call last):
File "alien_invasion.py", line 26, in <module>
run_game()
File "alien_invasion.py", line 22, in run_game
ship.blitme()
AttributeError: 'Ship' object has no attribute 'blitme'
答案 0 :(得分:2)
问题是你有一个blitme函数嵌套在ship.py中的init中。与 init 一致的功能选项卡,您将能够引用blitme()。
import pygame
class Ship():
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
def blitme(self):
self.screen.blit(self.image, self.rect)