Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class StatePool:
- def GetInst(self, cls):
- if cls in self.__dict__.keys():
- return self.__dict__[cls];
- else:
- self.__dict__[cls] = cls();
- return self.__dict__[cls];
- def __init__(self):
- self.__dict__ = dict();
- class HeroState:
- __pool__ = StatePool();
- def __init__(self, name = 'default_name'):
- self.name = name;
- @classmethod
- def GetInst(self, cls):
- return HeroState.__pool__.GetInst(cls);
- class Standing(HeroState):
- def __str__(self):
- return 'Hero is Standing';
- def on_event(self, event):
- if event == 'go':
- return HeroState.GetInst(Moving);
- elif event == 'shoot':
- HeroState.GetInst(Shooting).prev = self
- return HeroState.GetInst(Shooting);
- else:
- return self;
- class Moving(HeroState):
- def __str__(self):
- return 'Hero is Moving';
- def on_event(self, event):
- if event == 'shoot':
- HeroState.GetInst(Shooting).prev = self
- return HeroState.GetInst(Shooting);
- elif event == 'stop':
- return HeroState.GetInst(Standing);
- else:
- return self;
- class Shooting(HeroState):
- def __init__(self):
- self.prev = HeroState.GetInst(Standing);
- def __str__(self):
- return 'Hero is Shooting';
- def on_event(self, event):
- return self.prev;
- class Hero:
- def __init__(self):
- self.current_hero_state = HeroState.GetInst(Standing);
- def ProcessEvents(self):
- while True:
- print(self.current_hero_state.__str__())
- event = input('Enter event:')
- if event == 'exit':
- break;
- else:
- self.current_hero_state = self.current_hero_state.on_event(event);
- hero = Hero();
- hero.ProcessEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement