AttributeError: 'Alieninvationupdown' object has no attribute 'screen'

Python 从入门到实践
p227:AttributeError: 'Alieninvationupdown' object has no attribute 'screen'

img

img

img

img

问题如上。

你的screen是在Alieninvationupdown里面定义的,类ship里面的screen是传参进去的,你都没有实例化ship当然就没有sreen了

帮你改了,

import pygame
from up_down_settings import Settings
from up_down_ship import Ship

class Alieninvationupdown:
    def __init__(self):
        # 创建'screen'属性
        self.screen = pygame.display.set_mode(self.setting.screen_width, self.setting.screen_height)
        pygame.init()
        self.setting = Settings()
        # 将'screen'属性传入Ship对象
        self.ship = Ship(self)
        pygame.display.set_caption("UP AND DOWN ALIEN INVASION")
    
    def run_game(self):
        while True:
            self._update_screen()
    
    def _update_screen(self):
        self.screen.fill(self.setting.bg_color)
        self.ship.draw_ship()
        pygame.display.flip()

if __name__ == "__main__":
    ai=Alieninvationupdown()
    ai.run_game()