Advertisement
Guest User

Untitled

a guest
May 21st, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. class StatePool:
  2.  
  3. def GetInst(self, cls):
  4. if cls in self.__dict__.keys():
  5. return self.__dict__[cls];
  6. else:
  7. self.__dict__[cls] = cls();
  8. return self.__dict__[cls];
  9.  
  10. def __init__(self):
  11. self.__dict__ = dict();
  12.  
  13. class HeroState:
  14. __pool__ = StatePool();
  15. def __init__(self, name = 'default_name'):
  16. self.name = name;
  17.  
  18. @classmethod
  19. def GetInst(self, cls):
  20. return HeroState.__pool__.GetInst(cls);
  21.  
  22. class Standing(HeroState):
  23. def __str__(self):
  24. return 'Hero is Standing';
  25.  
  26. def on_event(self, event):
  27. if event == 'go':
  28. return HeroState.GetInst(Moving);
  29. elif event == 'shoot':
  30. HeroState.GetInst(Shooting).prev = self
  31. return HeroState.GetInst(Shooting);
  32. else:
  33. return self;
  34.  
  35.  
  36. class Moving(HeroState):
  37. def __str__(self):
  38. return 'Hero is Moving';
  39.  
  40. def on_event(self, event):
  41. if event == 'shoot':
  42. HeroState.GetInst(Shooting).prev = self
  43. return HeroState.GetInst(Shooting);
  44. elif event == 'stop':
  45. return HeroState.GetInst(Standing);
  46. else:
  47. return self;
  48.  
  49. class Shooting(HeroState):
  50. def __init__(self):
  51. self.prev = HeroState.GetInst(Standing);
  52.  
  53. def __str__(self):
  54. return 'Hero is Shooting';
  55.  
  56. def on_event(self, event):
  57. return self.prev;
  58.  
  59.  
  60.  
  61. class Hero:
  62. def __init__(self):
  63. self.current_hero_state = HeroState.GetInst(Standing);
  64.  
  65. def ProcessEvents(self):
  66. while True:
  67. print(self.current_hero_state.__str__())
  68. event = input('Enter event:')
  69. if event == 'exit':
  70. break;
  71. else:
  72. self.current_hero_state = self.current_hero_state.on_event(event);
  73.  
  74.  
  75.  
  76.  
  77. hero = Hero();
  78. hero.ProcessEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement