Pygame - The Sprite Module

Any bitmap that is drawn in our game window and that can move around is called a Sprite. The pygame.sprite module contains classes and functionality useful in game development. Along with a Sprite class to create collection of sprite objects, there are functions that enable collision of sprite objects.

The Sprite class serves as a base class for different objects in the game. You may have to put one more objects in groups. for that purpose, group classes are also provided.

Let us first develop a Sprite class by subclassing the sprite.Sprite class. Each object of this Block class is a rectangular block filled with black color.

class Block(pygame.sprite.Sprite):

   def __init__(self, color, width, height):

      self.image = pygame.Surface([width, height])

      self.rect = self.image.get_rect()

We shall create 50 block objects and put them in a list.

for i in range(50):
   block = Block(BLACK, 20, 15)

   # Set a random location for the block
   block.rect.x = random.randrange(screen_width)
   block.rect.y = random.randrange(screen_height)
   # Add the block to the list of objects

We create a block with red color call it player, and add it too to the list.

# Create a RED player block
player = Block(RED, 20, 15)

Inside the game’s event loop, detect the collision of red block (player) as it moves along with mouse motion and black block and count the collisions.


The event loop code is as follows −

while not done:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         done = True
   # Clear the screen

   # Get the current mouse position. This returns the position
   # as a list of two numbers.
   pos = pygame.mouse.get_pos()

   # Fetch the x and y out of the list,
      # just like we'd fetch letters out of a string.
   # Set the player object to the mouse location
   player.rect.x = pos[0]
   player.rect.y = pos[1]

   # See if the player block has collided with anything.
   blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

   # Check the list of collisions.
   for block in blocks_hit_list:
      score += 1

   # Draw all the spites

   # Go ahead and update the screen with what we've drawn.

   # Limit to 60 frames per second



Run the above code. Move the player block to capture as many black blocks. The score will be echoed on the console.

Sprite Module
Kickstart Your Career

Get certified by completing the course

Get Started