[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Collision handling algorithm



Not pygame related directly, but thought I would get good feedback here.
I'm trying to abstract collision handling as much as possible to my
level configuration file.  My game is an asteroids-type space shooter
with a variety of different objects that can collide.  For each level, I
have a dict whose keys are composed of "collision pairs", or two objects
whose collisions I want to handle.  The values at these dict locations
contain the point value of the collision, the resultant object to create
at the point of collision (e.g. explosion), and handler functions for
each object involved.  For example, the collision between my
user-controlled starship and raygun powerup might look like this:

'starship-rgpowerup' : {
    'value' : 0,
    'result' : {'name' : 'explosion', offset : 60, 'parms' : []},  #
    create an explosion
    'starship' : {'name' : 'use_raygun', parms : []},              #
    call starship.use_raygun()
    'rgpowerup' : {'name' : 'destroy', parms : []}                 #
    destroy powerup
}

The game scene module loops through the objects, builds the dict key,
and if the collision pair exists in the hash table and if they collide,
it uses the info from the hash to handle the collision.  I check for
both orderings of collision pairs using __class__.__name__ (e.g.
'starship-rgpowerup' and 'rgpowerup-starship').

Anyway, seems to be working pretty well for me.  What do you think?  See
any holes?  How would you improve it?