As found in bullet game.
The first kind of sprite we used is a simple kind of sprite that we drew ourselves.
In Bullet game, we have a “class Zombie”. Here is a brief analysis of the code.
To create the image of the sprite, we create a pygame surface large enough to hold the sprite. In this particular case we just want a square so we will use image.fill() on the surface to paint it a certain color. Then we're done. We get the rect info and set the rect.center and we're done. dx and dy is directional information we will use in update().
In this case, update() is a somewhat special function that is intended to be called at regular intervals, in this case every frame (ex. 60 fps is 60 times per second). Understanding update() is very easy:
The update function is usually the only hook function you will need, but you can create others to help you control the sprite in your game. One idea is to make an explosion routine that replaces the image with an explosion temporarily before removing it from the game.
# Define the Zombie Sprite class SpaceShip(pygame.sprite.Sprite): HEIGHT = 20 WIDTH = 50 SPEED = 60 def __init__(self, x, y, dx = 0, dy = -1): super().__init__() # Create a surface for the bullet self.image = pygame.Surface((self.WIDTH, self.HEIGHT)) # Fill the surface with a color self.image.fill(self.COLOR) # Get the rectangle for positioning self.rect = self.image.get_rect() # directional info self.dx = dx self.dy = dy self.speed = self.SPEED # Set the initial position self.rect.center = (x, y) self.timer = 0 self.start = time.time() * 1000 def update(self): self.timer = (time.time() * 1000) - self.start # Wait to move zombie self.speed -= 1 if self.speed > 0: return # alternate image every time we move. if self.frame == 0: self.frame = 1 self.image = self.image_b else: self.frame = 0 self.image = self.image_a # Speed is 0, 'tick' to move: self.speed = self.SPEED # Move the zombie directionally self.rect.x += self.dx * self.STEP self.rect.y += self.dy * self.STEP if self.rect.bottom < 0: self.kill() print("zombie escaped n") if self.rect.top > Screen.HEIGHT: self.kill() print("zombie escaped s") if self.rect.left < 0: self.kill() print("zombie escaped w") if self.rect.right > Screen.WIDTH: self.kill() print("zombie escaped e")