class EventObj: "sample class for dealing with events" # # Event handlers # def touch(self, s): print 'Touched by ' + s def wounded(self, pts, part): print'Wounded at ' + part + ' by %(pts)d points' % vars() # # Insert event at the end of list # def newEvent(self, evtName, *args): # Keep incoming event for processing if self.evtTable.has_key(evtName): # if event exists in evtTable, evtTuple = (evtName, args) # make the event structure, and self.evtQueue.append(evtTuple) # insert it at the queue end # # Returns true if queue is empty # def hasEvents(self): return self.evtQueue != [] # # Process next event # def forceEvent(self): # Force next event to be processed evt = self.evtQueue[0] # get next event, and self.evtQueue.remove(evt) # remove it from queue # # separate event methods by argument number (not pretty, I now...) if self.evtTable[evt[0]][1] == 0: self.evtTable[evt[0]][0]() if self.evtTable[evt[0]][1] == 1: self.evtTable[evt[0]][0](evt[1][0]) if self.evtTable[evt[0]][1] == 2: self.evtTable[evt[0]][0](evt[1][0], evt[1][1]) if self.evtTable[evt[0]][1] == 3: self.evtTable[evt[0]][0](evt[1][0], evt[1][1], evt[1][2]) # ... until max argument list allowed # def __init__(self): # evtTable associates an event name with a tuple (function, n-args) self.evtTable = {'touch' : (self.touch, 1), 'wounded' : (self.wounded, 2) } self.evtQueue = [] class newEventObj(EventObj): "An extended class with a new event" # def patrol(self): print 'Patrolling' # def __init__(self): # superclass init method. This call reuses all important # data structures of superclass, like evtQueue self.__class__.__bases__[0].__init__(self) # add new event to this subclass self.evtTable['healed'] = (self.patrol, 0) ##################### x = EventObj() y = newEventObj() x.newEvent('touch', 'dragon') x.newEvent('wounded',500,'head') y.newEvent('touch', 'troll') y.newEvent('touch', 'orc') y.newEvent('wounded',400,'right leg') y.newEvent('healed') print '='*40 print x.evtTable print x.evtQueue print '-'*40 print y.evtTable print y.evtQueue print '='*40 while x.hasEvents(): x.forceEvent() while y.hasEvents(): y.forceEvent()