[Tutor] affecting all classes if one class is affected by an event - pygame

Marc Tompkins marc.tompkins at gmail.com
Fri Nov 16 23:49:05 CET 2007

Thus spake ted b:

I am trying to figure out how to make a class instance respond the same way
> as another class instance if the other is affected by some event. I have
> been playing around with inheritance, and have tried other stuff, but i am
> somewhat of a newbie and I have been having difficulty (but you guys,
> particularly Kent, have really been helping me a lot :))))
> For example, in the pygame code below, i have set it up so that the boxes
> will stop if they are above the barrier and hit it. Well, that's what i want
> to happen, but if one of the boxes hits the barrier, the other box keeps
> going. Is there a way i can have both boxes stop if either of them hit the
> barrier. I was hoping there was a way that i could have the info from one
> class get passed to the other classes so i could stop the other box (or stop
> all  or only some other boxes if i add lots more). Should i make another
> class? Another method? Globals?

You need to have some way for information to be passed around between
objects, or communicated to them by some central authority (which is much,
much simpler to implement.)  You're already collecting your objects into
"allSprites"; go ahead and use that.

This needs tuning, but off the top of my head I'd say:

1) add a bool attribute (let's call it "collided") to your sprites; in
 __init__ for each object add:
  self.collided = False

2) in your checkPos method, if there was a collision, set self.collided =
  Also, don't do the actual reversal / stopping here - add another method to
do it, like so:
def oopsie(self):
    pass # replace this with whatever you want to have happen

3) put this somewhere in your "while KeepGoing:" loop:
collision - False
for sprite in AllSprites:  # run through the list of sprites once to check
   if sprite.collided:
      collision = True
      sprite.collided = False # reset this sprite's flag for next time
if collision:  # if there was a collision,
    for sprite in AllSprites:  # then run through the list of sprites again
and update them

I agree with Kent - don't derive Box2 from Box1; use parameters to
initialize them.

I've never looked at pygame - some of this might already be built-in, but
this is how I'd go about it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071116/6c85415a/attachment.htm 

More information about the Tutor mailing list