0

I'm making a game where a ship flies and shoots. I tried to use the ready-made class "pygame.sprite.Sprite", but it was not possible to correctly draw sprites after rotation. So I'm trying to create a new class. How to create a common variable, for example "list_sprites", where instances of different sprites (ships, bullets and ng) will be placed after initialization, and then in a loop go through the list "list_sprites" and call the ".draw()" method. How to inherit correctly so that the "list_sprites" variable can be edited with the ".shoot()" method?

class Sprite():
    list_sprites = []
    list_bullets = []
#--------------------------------
class Ship(Sprite):
    def __init__(self, img):
        self.img = img
        self.x = 10
        self.y = 10
        Sprite.list_sprites.append(self)

    def draw(self, screen):
        screen.blit(self.img, (self.x, self.y))

    def shoot(self):
        Bullet(img_bullet, self.x, self.y)
#--------------------------------
class Bullet(Sprite):
    def __init__(self, img, x, y):
        self.img = img
        self.x = x
        self.y = y
        Sprite.list_sprites.append(self)        
        Sprite.list_bullets.append(self)  
#--------------------------------
WIDTH = 1280  
HEIGHT = 720 
FPS = 60 
WHITE = (255,255,255)
#--------------------------------
pygame.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
#--------------------------------
ship_1 = Ship(img_ship)
#--------------------------------
running = True
while running:   
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                ship_1.shoot()
    #--------------------------------
    screen.fill(WHITE)
    screen.blit(background, background_rect)
    for sprite in Sprite.list_sprites:
        sprite .draw(screen)
    #--------------------------------
    pygame.display.flip()
    clock.tick(FPS)
pygame.quit()

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 2
    `super().__init__()`, read about [Inheritance](https://docs.python.org/3/tutorial/classes.html#inheritance) – Rabbid76 Jul 07 '22 at 17:57
  • Also [entity component systems](https://en.wikipedia.org/wiki/Entity_component_system), as a potential alternative. [Favor composition over inheritance](https://www.google.com/search?q=favor+composition+over+inheritance&oq=favor+composi&aqs=chrome.0.0i512l2j69i57j0i512l5j0i22i30l2.2785j0j7&sourceid=chrome&ie=UTF-8). – Jared Smith Jul 07 '22 at 17:58

0 Answers0