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()
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()
# [...]
ThankXD! I had used all of this missing code before posting the question but maybe I haven't figured out how to combine them in the correct order of your answer. So, with your explanation, I can move forward in learning to use the pygame module correctly.
@DiegoBneiNoah You're welcome.