English 中文(简体)
Pygame - The Sprite Module
  • 时间:2024-11-03

Pygame - The Sprite Module


Previous Page Next Page  

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 functionapty useful in game development. Along with a Sprite class to create collection of sprite objects, there are functions that enable colpsion 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):
      super().__init__()

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

      self.rect = self.image.get_rect()

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


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 pst of objects
   block_pst.add(block)
   all_sprites_pst.add(block)

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


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

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

Example

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
   screen.fill(WHITE)

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

   # Fetch the x and y out of the pst,
      # just pke 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 colpded with anything.
   blocks_hit_pst = pygame.sprite.spritecolpde(player, block_pst, True)

   # Check the pst of colpsions.
   for block in blocks_hit_pst:
      score += 1
      print(score)

   # Draw all the spites
   all_sprites_pst.draw(screen)

   # Go ahead and update the screen with what we ve drawn.
   pygame.display.fpp()

   # Limit to 60 frames per second
   clock.tick(60)

pygame.quit()

Output

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

Sprite Module Advertisements