Warm tip: This article is reproduced from stackoverflow.com, please click
bullet class pygame python updates

First shot fired is superimposed by second shot or simply disappears after second shot and etc

发布于 2020-05-03 00:11:40

I am trying to resolve the cause of my triggered bullet disappearing if in a short period of seconds I fire a second bullet. I imagine that screen.fill(GRAY) might be a cause and it should be inside the Class Bullet() or maybe I need to use all_sprites_list.update() elsewhere.

Here is my MWE code:

import pygame
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (128,128,128)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Cowboy(pygame.sprite.Sprite):
      def __init__(self):
          super().__init__()

          self.image = pygame.Surface([14,20])
          self.image.fill(BLUE)
          self.rect = self.image.get_rect()
class Bullet(pygame.sprite.Sprite):
      def __init__(self):
          super().__init__()
          self.image = pygame.image.load("bullet.png").convert()
          self.rect = self.image.get_rect()
      def update(self):
         self.rect.y += -3
def main():
    pygame.init()
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size, pygame.RESIZABLE) 
    all_sprites_list = pygame.sprite.Group()
    bullet_list = pygame.sprite.Group() 
    enemies_list = pygame.sprite.Group()
    bullet = Bullet()
    enemy = Cowboy()
    enemies_list.add(enemy)
    all_sprites_list.add(enemy)
    enemy.rect.y = 50
    enemy.rect.x = 50
    done = False
    clock = pygame.time.Clock()
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                bullet_list.add(bullet)
                all_sprites_list.add(bullet)
                bullet.rect.x = 340
                bullet.rect.y = 200
        screen.fill(GRAY)
        all_sprites_list.draw(screen)
        clock.tick(60)
        pygame.display.flip()
    pygame.quit()
if __name__ == "__main__":
    main()
Questioner
Diego Bnei Noah
Viewed
59
Rabbid76 2020-02-14 01:00

You have to create a new instance of Bullet, when the mouse button is pressed and you have to invoke the update method of the bullets calling update on the bullet_list:

def main():
    # [...]

    # bullet = Bullet() <--- DELETE

    # [...]
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.MOUSEBUTTONDOWN:

                # create new bullet and add it to the groups
                bullet = Bullet()
                bullet.rect.center = enemy.rect.center
                bullet_list.add(bullet)
                all_sprites_list.add(bullet)

        # update the bullets
        bullet_list.update()

        # [...]