1. Action模式实现

今天看到 这篇好文, 里面有一部分讲到Action模式在游戏里面的应用, 感觉有点意思就随手写了写, 总算赶在熄灯之前搞定, 呵呵。 希望这半桶水的英文注释不会让你感觉太头疼 :)

   1 class Action(object):
   2         reg_after = {}
   3         reg_before = {}
   4         def __init__(self,func):
   5                 self.internal = func
   6         def __call__(self):
   7                 '''excute all actions registered to excute before self,
   8                 then excute self,
   9                 last excute all actions registered to excute after self.'''
  10                 if self.reg_before.has_key(self):
  11                         acs = self.reg_before[self]
  12                         for a in acs:
  13                                 a()
  14                 self.internal()
  15                 if self.reg_after.has_key(self):
  16                         acs = self.reg_after[self]
  17                         for a in acs:
  18                                 a()
  19         def before(self,action):
  20                 'register self take place before action' 
  21                 self.register(action,self,self.reg_before)
  22         def after(self,action):
  23                 'register self take place after action' 
  24                 self.register(action,self,self.reg_after)
  25         @staticmethod
  26         def register(ac1,ac2,reg):
  27                 if reg.has_key(ac1):
  28                         reg[ac1].append(ac2)
  29                 else:reg[ac1]=[ac2]
  30 
  31 class Door(object):
  32         def __init__(self,no):
  33                 self.no = no
  34                 self.Open = Action(self.ac_Open)
  35         def ac_Open(self):
  36                 print 'door',self.no,'open'
  37 
  38 class Player(object):
  39         def __init__(self,name):
  40                 self.name = name
  41                 self.Die = Action(self.ac_Die)
  42         def ac_Die(self):
  43                 print self.name,'player die'
  44 
  45 class Beer(object):
  46         def __init__(self,no):
  47                 self.no = no
  48                 self.Start = Action(self.ac_Start)
  49         def ac_Start(self):
  50                 print 'beer',self.no,'start' 
  51 
  52 if __name__ =='__main__':
  53         player = Player('hy')
  54         door = Door(1)
  55         beer = Beer(1)
  56         door.Open.before(player.Die)
  57         beer.Start.after(door.Open)
  58         player.Die()

...



个人网页分类

HuangYi/action_pattern_implement (last edited 2009-12-25 07:16:26 by localhost)