微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 速成课程,外星人入侵,第 12 章,“未解析的属性引用 'draw_bullet' 用于类 'Sprite'”

如何解决Python 速成课程,外星人入侵,第 12 章,“未解析的属性引用 'draw_bullet' 用于类 'Sprite'”

我正在一步一步地学习这本书,但由于警告“类'Sprite'的未解析属性引用'draw_bullet'”而卡住了。没有错误或崩溃,但按空格键时没有任何反应。 代码运行并且飞船可以正确移动,只是没有开火。

此外,在 bullet.py 中,方法 update(self) 覆盖了 Sprite.update()。我不确定它应该是怎样的,我觉得那里有问题,但无法弄清楚原因以及如何解决它。

作为一名编程爱好者,对于本文的任何误用,我提前道歉,并提前感谢您提出的任何建设性建议。

下面附上代码

alien_invasion.py

import pygame
from pygame.sprite import Sprite


class Bullet(Sprite):
    def __init__(self,ai_game):
        super().__init__()

        self.screen = ai_game.screen
        self.settings = ai_game.settings
        self.color = self.settings.bullet_color

        # create bullet rect
        self.rect = pygame.Rect(0,self.settings.bullet_width,self.settings.bullet_height)
        self.rect.midtop = ai_game.ship.rect.midtop
        self.y = float(self.rect.y)

    def draw_bullet(self):  
        pygame.draw.rect(self.screen,self.color,self.rect)

    def update(self): # <<<=== overrides method in Sprites <<<===
        self.y -= self.settings.bullet_speed
        self.rect.y = self.y

bullet.py

class Settings:
    """A class with all the functionalities of AI"""
    def __init__(self):
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230,230,230)
        self.ship_speed = 1.5

        # bullet
        self.bullet_speed = 1.0
        self.bullet_height = 15
        self.bullet_width = 3
        self.bullet_color = (60,60,60)

设置.py

import pygame


class Ship:
    """A class to manage ships"""
    def __init__(self,ai_game):
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()
        self.moving_right = False  # FLAG
        self.moving_left = False
        self.settings = ai_game.settings

    # Load the ship image and get its rect
        self.image = pygame.image.load('images/ship_aigame.bmp')
        self.rect = self.image.get_rect()

        # drawing the ship in the middle-bottom of the screen
        self.rect.midbottom = self.screen_rect.midbottom
        self.x = float(self.rect.x)  # ship x position stored as a float

    def blitme(self):
        """Draw the ship in the current location"""
        self.screen.blit(self.image,self.rect)

    def update(self):
        if self.moving_right and (self.rect.right - 30) < self.settings.screen_width:
            self.x += self.settings.ship_speed
        elif self.moving_left and (self.rect.left + 22) > 0:
            self.x -= self.settings.ship_speed
        self.rect.x = self.x

ship.py

{{1}}

感谢阅读

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。