账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    外星人飞船报错'pygame.Surface' object has no attribute 'alien_speed'
    87
    0

    我是按照书上的内容写到外星人群移动,发现game_function.py中的 def update_aliens(aliens):aliens.update()无法正常读取setting.py中的alien_speed取值,我将alien.py中的def update(self):self.x += self.ai_screen.alien_speed改成self.x += 1,外星人群就可以正常右移了,请问是哪里出现问题了?新人请多多指教,困扰半天了。

    alien_invasion.py

    import sys
    import pygame
    from settings import Settings
    from ship import Ship
    import game_functions as game_expand
    from pygame.sprite import Group
    from alien import Alien
    from bull import Bullet
    def run_game():
    pygame.init()#pygame初始化背景设置,让pygame能够正确工作
    ai_screen = Settings()
    #设置实例获取setting模块下Settings方法中的参数设置
    screen = pygame.display.set_mode((ai_screen.width,ai_screen.height))
    #创建显示窗口,通过实例传递setting模块下self.width和self.height的具体参数
    pygame.display.set_caption('Alien Invasion')
    #创建游戏窗口标题,这些都属于游戏元素
    ship = Ship(screen,ai_screen)
    #获取ship模块下的Ship方法,调用飞船图片,创造出飞船
    black_color = ai_screen.black_color
    #设置背景颜色,以RGB值指定,每个取值范围0-255
    bullets = Group()
    aliens = Group()
    #将外星人添加到一个数组中
    game_expand.create_fleet(ai_screen,screen,aliens)
    #创建外星人群
    while True:#使用无限循环的目的是可以在每次刷新时都打印输出
            ship.update()
            # 每次循环时都调用飞船的update方法
            game_expand.check_events(ai_screen, screen, ship, bullets)
            #将ship模块作为实参传递给game_functions模块下的check_events方法,目的是当检测到事件是按键并且是特定的方向键是将飞船做出相应的位置调整
            game_expand.update_bullets(aliens,bullets,ai_screen,screen,ship)
            game_expand.update_aliens(aliens)
            game_expand.update_screen(ai_screen,screen,ship,bullets,aliens)
    
    run_game()
    
    

    game_function.py

    import sys
    import pygame
    from bull import Bullet
    from alien import Alien
    #响应按键和鼠标事件
    def check_keydown_events(event,ship,ai_screen,screen,bullets):
    if event.key == pygame.K_RIGHT:
        ship.move_right = True
            # 上边代码表示持续移动属性被修改为true,允许持续移动
    elif event.key == pygame.K_LEFT:
        ship.move_left = True
    elif event.key == pygame.K_UP:
        ship.move_up = True
    elif event.key == pygame.K_DOWN:
        ship.move_down = True
    elif event.key == pygame.K_SPACE:
            #创建一颗子弹,并将其加入到编组bullets中
        fire_bullets(bullets,ai_screen,screen,ship)
    elif event.key == pygame.K_q:
            #创建一颗子弹,并将其加入到编组bullets中
        sys.exit()
    
    def check_keyup_events(event,ship):
    if event.key == pygame.K_RIGHT:
        ship.move_right = False
            # 上边代码表示持续移动属性被修改为false,不允许持续移动
    if event.key == pygame.K_LEFT:
        ship.move_left = False
    if event.key == pygame.K_UP:
        ship.move_up = False
    if event.key == pygame.K_DOWN:
        ship.move_down = False
    
    def check_events(ai_screen, screen, ship, bullets):
    for event in pygame.event.get():
    # 为让程序响应事件,我们编写一个事件循环,监听事件,如果有事件发生,执行相应任务
        if event.type == pygame.QUIT:
            sys.exit()  # 退出进程
        elif event.type == pygame.KEYDOWN:
            #如果pygame检测到KEYDOWN事件,做出以下反应
            check_keydown_events(event,ship,ai_screen,screen,bullets)
        elif event.type == pygame.KEYUP:
            #如果pygame检测到KEYUP事件,做出一下反应
            check_keyup_events(event,ship)
    def fire_bullets(bullets,ai_screen,screen,ship):
    if len(bullets) <= ai_screen.bull_allow:
        # 检查如果同屏子弹数小于等于setting.py中设置的要求数量,执行下列命令,将子弹添加到bullets列表中
        new_bullet = Bullet(ai_screen, screen, ship)
        bullets.add(new_bullet)
    
    def update_bullets(aliens,bullets,ai_screen,screen,ship):
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    bullets.update()
    
    def get_number_aliens_x(ai_screen,alien_width):
    #计算每行可容纳多少个外星人
    available_space_x = ai_screen.width - 2 * alien_width
    #可放置外星人的水平空间有多大
    number_aliens_x = int(available_space_x / (2 * alien_width))
    #计算一行可容纳外星人数量
    return number_aliens_x
    
    def create_alien(ai_screen,screen,aliens,alien_number):
    alien = Alien(ai_screen,screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    aliens.add(alien)
    
    def create_fleet(ai_screen,screen,aliens):
    #创建外星人群
    alien = Alien(ai_screen,screen)
    #先创建一个外星人
    number_aliens_x = get_number_aliens_x(ai_screen,alien.rect.width)
    for alien_number in range(number_aliens_x):
        create_alien(ai_screen,screen,aliens,alien_number)
    
    def update_aliens(aliens):
    aliens.update()
    
    def update_screen(ai_screen,screen,ship,bullets,aliens):
    #更新屏幕中的图片,并切换到新屏幕
    screen.fill(ai_screen.black_color)
    #用屏幕填充背景颜色,只接受一个实参,一种颜色
    for bull in bullets.sprites():
    #在飞船和外星人后面重绘所有子弹,该方法中的所有函数必须在pygame.display.flip()前执行,否则无法正常显示
        bull.draw_bull()
    ship.blitme()
    #将飞船图片绘制到屏幕中
    aliens.draw(screen)
    #在屏幕上绘制编组中的每个外星人
    pygame.display.flip()
    # 绘制最近屏幕的显示,通过不断更新屏幕,以显示元素的新位置,并在原来的位置隐藏元素,从而营造平滑移动效果
    
    

    aline.py

    import pygame
    from pygame.sprite import Sprite
    class Alien(Sprite):
    def __init__(self,screen,ai_screen):
        super(Alien,self).__init__()
        self.screen = screen
        self.ai_screen = ai_screen
        self.image = pygame.image.load('C:\\Users\\邢小星\\PycharmProjects\\Game\\Game_Windows\\aliens.bmp')
        #加载外星人图片
        self.rect = self.image.get_rect()
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height
        #设置每个外星人最初都在屏幕左上角附近出现
        self.x = float(self.rect.x)
    
    def update(self):
        self.x += self.ai_screen.alien_speed
        self.rect.x = self.x
    
    def blitme(self):
        self.screen.blit(self.image, self.rect)
    
    

    setting.py

    class Settings():
    def __init__(self):
        self.width = 960#宽度
        self.height = 600#高度
        self.black_color = (255,255,255)#背景颜色
        self.ship_speed = 1.5#飞船行驶速度
        self.bull_speed = 1
        self.bull_width = 3
        self.bull_height = 15
        self.bull_color = (10,10,10)
        self.bull_allow = 5#限制同屏的子弹数
        self.alien_speed = 1
        self.fleet_drop_speed = 2
        self.fleet_direction = 1
    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 愛到絶朢是離開 普通会员 1楼

      The error message "pygame.Surface object has no attribute 'alien_speed'" occurs when you are trying to access an attribute of a pygame.Surface object, but the attribute does not exist in the object. Here's a breakdown of the error message and possible solutions:

      1. Try importing the pygame.Surface module:

      python import pygame

      If you are using a different version of Python or are not importing the pygame module, you will need to import it before using the Surface class. You can do this by adding the following line at the beginning of your code:

      python import pygame

      1. Check if the Surface object was created correctly:

      python surface = pygame.Surface((100, 100))

      If you are trying to access an attribute of a Surface object that was not created, you will get this error. Make sure that you have initialized a Surface object using the pygame.Surface() function, as shown in the example above.

      1. Check if the attribute you want to access exists in the Surface object:

      python if 'alien_speed' in surface: print(surface.alien_speed)

      In this case, the error message suggests that the alien_speed attribute does not exist in the Surface object. To fix this, check if the attribute is defined in the Surface class or any of its subclasses. You can do this by looking at the __init__() or get_size() methods of the Surface class or any of its subclasses.

      Here's an example of how you can check if the alien_speed attribute exists in the Surface class:

      ```python class AlienSurface(Surface): def init(self): super(AlienSurface, self).init(100, 100)

      def get_size(self):
          return (self.size[0], self.size[1])
      

      ```

      In this example, the AlienSurface class inherits from the Surface class, and the get_size() method returns the size of the surface.

      If the alien_speed attribute does not exist in the Surface class or any of its subclasses, you will need to find a way to define it in the appropriate class or subclass. You can do this by defining a custom class that extends the Surface class and adding an attribute that you want to use. Here's an example:

      ```python class AlienSurface(Surface): def init(self): super(AlienSurface, self).init(100, 100)

      def get_size(self):
          return (self.size[0], self.size[1])
      
      def alien_speed(self):
          # Define your alien speed attribute here
          alien_speed = 10  # Example value
          return alien_speed
      

      ```

      In this example, the AlienSurface class has an additional attribute alien_speed that is set to 10. You can define any attribute you want to use, as long as it is a subclass of the Surface class and has a get_size() method.

      After defining the attribute in the AlienSurface class, you can create an instance of the class and access the attribute using the alien_speed method:

      python surface = AlienSurface() print(surface.alien_speed) # Output: 10

      With this approach, you should be able to access the alien_speed attribute of the Surface object, which will cause the "pygame.Surface object has no attribute 'alien_speed'" error to be resolved.

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部