Python
  Home arrow Python arrow PyGame for Game Development: Sprite Groups and Collision Detection
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

PyGame for Game Development: Sprite Groups and Collision Detection
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 11
    2006-01-31


    Table of Contents:
  • PyGame for Game Development: Sprite Groups and Collision Detection
  • Explaining the Group Class
  • Collision
  • Explaining the Collision Code

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    PyGame for Game Development: Sprite Groups and Collision Detection
    ( Page 1 of 4 )

    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.

    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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT