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

Re: [pygame] Event Handling and Collision Detection



Why are you making events for draw, update start, collisions, etc? Seems like that would just make it more complicated. 

Most of your events 'draw', 'end', 'begin', 'update' are states, so you could have a 'game_state' variable that you set as the current state. ( Allows you to branch code if you add a title screen 

if state == "title":
    self.title_loop()
else:
    self.loop()

==

I would do something like this: ( You can keep event callbacks if you want. I think sending copies makes it cleaner )

Then on collisions, I'm calling 'oncollide(other)' on both actors. So they both can do class-specific stuff and know who hit them.

# psuedo-code

class Actor():
def oncollide( self, other ):
# might be useful to know what with or where you where hit.
self.dead = True
def update(self,delta):
self.loc += self.vel *delta # ...

class Game():
def init(self): # do non-__init__ stuff
def loop(self):
"""main loop: events; update(); draw()"""
while not self.done:
for event in eventlist():
self.handle_event(event)
player.handle_event(event)
self.handle_keys()
self.update()
self.draw()
def update(self, delta):
"""physics / collisions"""
for u in self.unit_list[:]: # iterate on copy cause may delete some
u.move(delta)
if u.dead:
self.unit_list.remove( u )
continue
# brute force collision
for other in self.unit_list:
if colliderect( u, other):
a.oncollide(other)
other.oncollide( a )

def draw(self):
draw_it()
for unit in self.unit_list: unit.draw()
display.flip()
def handle_event(self, event):
"""Game()'s handling of events.
events also get copied to anyone else that is 'registered', ie: player.
ATM all types are sent and he just ignores what he doesn't want"""
if key == ESC: self.done = True
def handle_keys(self): # if you need non event input


--
Jake