Frei
Frei

Reputation: 53

Pygame only one image/sprite is displaying

# Import the library PyGame
import pygame; pygame.init()

# Create the window/GUI
global window
window = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Space Invaders')


class sprite:
    """A class that you assign to the a sprite, it has the functions     draw() and resize()"""

    def __init__(self, fileto):
        self.x = 330
        self.y = 700
        self.width = 100
        self.height = 100
        self.image = pygame.image.load(fileto).convert()

    # Blit the sprite onto the screen, ex: plane.draw()
    def draw(self):
        window.fill(255)
        window.blit(self.image, (self.x, self.y))
        self.image = pygame.transform.scale(self.image, (self.width, self.height))
        pygame.display.flip()


bakgrunn = pygame.image.load("stars.png").convert()

# Assign the variable plane to the class "sprite"
plane = sprite("plane.gif")
projectile = sprite("projectile.png")

while True:
    # Draw the plane and set the size
    plane.draw()
    plane.width = 100
    plane.height = 100

    projectile.draw()

I am making a Space Invaders game in PyGame, but when I try to draw the projectile it overrides/changes with the main sprite(plane). How could I fix this problem so I can have several sprites showing on the screen?

Upvotes: 0

Views: 577

Answers (1)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9746

Your sprite's draw function is causing you problems. It fills and refresh the display every time a sprite is drawn. Which means that if you have two or more objects, only the last one will show. Use only the blit function for each object, and fill/refresh the screen only once each game loop.

# Import the library PyGame
import pygame; pygame.init()

# Create the window/GUI
window = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Space Invaders')


class Sprite:
    """A class that you assign to the a sprite, it has the functions     draw() and resize()"""

    def __init__(self, fileto):
        self.x = 330
        self.y = 700
        self.width = 100
        self.height = 100
        self.image = pygame.image.load(fileto).convert()

    # Blit the sprite onto the screen, ex: plane.draw()
    def draw(self):
        window.blit(self.image, (self.x, self.y))    

# Assign the variable plane to the class "sprite"
plane = Sprite("plane.gif")
projectile = Sprite("projectile.png")

while True:
    # Clear the screen.
    window.fill((255, 255, 255))

    # Draw all objects to the screen.
    plane.draw()
    projectile.draw()

    # Make all everything you've drawn appear on your display.
    pygame.display.update()  # pygame.display.flip() works too

This will draw all sprites correctly. However, it'll crash after a few seconds because you're not handling events. You'll need to look up a tutorial on that before you can advance further.

Upvotes: 1

Related Questions