首页 > 解决方案 > Pygame:创建子弹 - 'Bullet' 对象不可调用

问题描述

我试图让 pygame 每次按下鼠标时都创建一个新的 Bullet 对象。它适用于第一个项目符号,但在第二个项目符号上我收到“'Bullet' 对象不可调用”错误。

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((20,40))
        self.image.fill(black)
        self.rect = self.image.get_rect()
        self.rect.x = player_1.rect.x
        self.rect.y = player_1.rect.y

        #self.image = pygame.image.load("C:/Users/Thomas/Desktop/rocket.png")
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.speed = 20
        self.damage_radius = 0
        self.damage = 0
        self.angle = 0


    def draw(self):
        self.image.fill(black)
        screen.blit(self.image, (self.rect.x, self.rect.y))

    def delete(self):
        pass

    def fire(self, mouse):
        """Determine agnle of which rocket is fired"""
        pass

    def update(self):
        self.rect.y -= self.speed


def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        screen.fill(intro_bg_color)
        large_text = pygame.font.Font("C:/Users/Thomas/Desktop/Python Sketches/Fonts/Quesat Black Demo.OTF", 100)


player_1 = Player((100,100), 20, blue)


while True:

    pygame.display.update()
    clock.tick(FPS)
    mouse = pygame.mouse.get_pos()
    gameEvent = pygame.event.get()

    """Draw"""

    """This wil be for advancing bullets in playing field"""

    screen.fill(bg_color)
    player_1.draw(mouse)

    for Bullet in bullet_list:
        Bullet.update()
        if Bullet.rect.y < 0:
            bullet_list.remove(Bullet)
        Bullet.draw()








    for event in gameEvent:
        if event.type == pygame.QUIT:
            pygame.quit()

        elif event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:
            mouse_is_pressed = True  # Used to determine if the mouse is held or not
            print("Mouse pressed")

            """Generate new bullet"""
            bullet = Bullet()
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)
            bullet.rect.x = player_1.rect.x
            bullet.rect.y = player_1.rect.y

        elif event.type == pygame.MOUSEBUTTONUP and pygame.mouse.get_rel()[0]:
            mouse_is_pressed = False
            print("Mouse button released")

当鼠标按下时,生成新的 Bullet,将其添加到 bullet_list。这是我查看的示例的完成方式,但我无法解决问题。非常感谢您的帮助!

标签: pygamebullet

解决方案


我拿了这段代码:

for Bullet in bullet_list:
    Bullet.update()
    Bullet.draw()

并将“子弹”更改为“子弹”,代码终于开始工作了。

for bullet in bullet_list:
    bullet.update()
    bullet.draw()

推荐阅读