Home arrow Python arrow PyGame for Game Development: Sprite Groups and Collision Detection

PyGame for Game Development: Sprite Groups and Collision Detection

In this second part of a tutorial covering PyGame, you will learn how to manage entire groups of sprites. You'll also learn how to test for collisions within your applications.

TABLE OF CONTENTS:
  1. PyGame for Game Development: Sprite Groups and Collision Detection
  2. Explaining the Group Class
  3. Collision
  4. Explaining the Collision Code
By: Peyton McCullough
Rating: starstarstarstarstar / 13
January 31, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Sprite Groups

While managing sprites individually may be ideal for small applications, think about managing dozens of sprites in more complex applications. Obviously, there has to be a way to efficiently manage all of them, and sprite groups do just that. The definition of a sprite group is pretty simple and true to the term. Sprite groups are simply groups of sprites that are related in some way. Sprites can also belong to multiple groups, rather than just being limited to one group. Besides providing a convenient way to iterate over related sprites, some sprite groups contain special features to aid with development, which we'll take a look at later. First, though, let's put together a simple program that uses a sprite group to move three stick men up and down the screen.


We'll start with the most basic sprite group, the Group class:

import pygame
import sys

class StickMan(pygame.sprite.Sprite):

   # We'll just accept the x-position here
   def __init__(self, xPosition):

      pygame.sprite.Sprite.__init__(self)
      self.old = (0, 0, 0, 0)
      self.image = pygame.image.load('stickMan.gif')
      self.rect = self.image.get_rect()
      self.rect.x = xPosition

   # The x-position remains the same
   def update(self, yPosition):

      self.old = self.rect
      self.rect = self.rect.move([0, yPosition - self.rect.y])

# Define a function to erase old sprite positions
# This will be used later
def eraseSprite(screen, rect):
   screen.blit(blank, rect)

pygame.init()
screen = pygame.display.set_mode((256, 256))
pygame.display.set_caption('Sprite Groups')
screen.fill((255, 255, 255))

# Create the three stick men
stick1 = StickMan(25)
stick2 = StickMan(75)
stick3 = StickMan(125)

# Create a group and add the sprites
stickGroup = pygame.sprite.Group()
stickGroup.add((stick1, stick2, stick3))

# Add a variable for the direction, y-position and height of the
sprite we are dealing with
stickGroup.direction = "up"
stickGroup.y = screen.get_rect().centery
stickGroup.height = stick1.rect.height

# Create a blank piece of background
blank = pygame.Surface((stick1.rect.width, stick1.rect.height))
blank.fill((255, 255, 255))

pygame.display.update()

# Create an event that will appear ever 100 milliseconds
# This will be used to update the screen
pygame.time.set_timer(pygame.USEREVENT + 1, 100)

while True:

   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         sys.exit()

      # Check for our update event
      if event.type == pygame.USEREVENT + 1:

         # Update the y-position
         if stickGroup.direction == "up":
            stickGroup.y = stickGroup.y - 10
         else:
            stickGroup.y = stickGroup.y + 10

         # Check if we have gone off the screen
         # If we have, fix it
         if stickGroup.direction == "up" and stickGroup.y <= 0:
            stickGroup.direction = "down"
         elif stickGroup.direction == "down" and stickGroup.y >=
(screen.get_rect().height - stickGroup.height):
            stickGroup.direction = "up"
            stickGroup.y = screen.get_rect().height -
stickGroup.height

         # Clear the old sprites
         # Notice that we pass our eraseSprite function
         # This will be called, and the screen and old position
will be passed
         stickGroup.clear(screen, eraseSprite)

         # Update the sprites
         stickGroup.update(stickGroup.y)

         # Blit the sprites
         stickGroup.draw(screen)

         # Create a list to store the updated rectangles
         updateRects = []

         # Get the updated rectangles
         for man in stickGroup:
            updateRects.append(man.old)
            updateRects.append(man.rect)
         pygame.display.update(updateRects)



 
 
>>> More Python Articles          >>> More By Peyton McCullough
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: