Python
  Home arrow Python arrow PyGame for Game Development: Sprite Gr...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
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: 5 stars5 stars5 stars5 stars5 stars / 10
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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


       · Hello, all,This is ment to be a continuation of the last article, so if you...
       · No, no artist - :), but I a great tutor. Thanks for writing up the into to PyGame....
       · On your last example I had a problem. You create 3 groups and added the three...
       · Hey, Jeff,Try upgrading to the latest version of PyGame. Sorry for the late...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway