A class for menu based terminal applications.

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Gribouillis Gribouillis is offline Offline Dec 20th, 2008, 3:17 pm |
0
Many threads in daniweb's python forum deal with menu based programs which run in a terminal. This snippet defines a handy class, MenuCrawler, to help writing such programs. Subclassing from this base classes and adding methods corresponding to a given set of menus allows one to build the menu-based application. See the example code included in the snippets for details.
Quick reply to this message  
Python Syntax
  1. # module menucrawler.py
  2. # (C) 2008 Gribouillis at www.daniweb.com
  3. """This module implements a base class MenuCrawler for menu based
  4. applications in a terminal.
  5. Note: uses module cbprint from the snippet
  6. http://www.daniweb.com/code/snippet1031.html
  7. """
  8. import re
  9. from cbprint import Print
  10. menu_pattern = re.compile("^\s*MENU\s+(\w+)")
  11.  
  12. class MenuCrawler(object):
  13. """A base class for menu based applications in a terminal.
  14. A MenuCrawler is initialized with a string containing several menus
  15. separated by lines of the form "MENU name".
  16. It can then be started by it's "run" method and it then displays
  17. a menu and prompt the user for an answer.
  18. Answers are handled by methods having the same names as the menus.
  19. These methods can be typically be implemented by subclassing MenuCrawler.
  20. See the example use in this module's source code.
  21. """
  22.  
  23. def __init__(self, menus):
  24. self.menu = None
  25. self.menus = {}
  26. if menus is not None:
  27. self.parse_menus(menus)
  28.  
  29. def parse_menus(self, menus):
  30. lines = menus.split("\n")
  31. name = ""
  32. for line in lines:
  33. match = menu_pattern.match(line)
  34. if match is None:
  35. if name:
  36. self.menus[name].append(line)
  37. else:
  38. if name:
  39. self.menus[name] = "\n".join(self.menus[name]).strip()
  40. name = match.group(1)
  41. self.menus[name] = []
  42. if name:
  43. self.menus[name] = "\n".join(self.menus[name]).strip()
  44.  
  45. def run(self, menu_name, prompt = "[choice] "):
  46. self.menu = menu_name
  47. while self.menu is not None:
  48. Print(self.menus[self.menu])
  49. choice = raw_input(prompt)
  50. if hasattr(self, self.menu):
  51. getattr(self, self.menu)(choice)
  52.  
  53.  
  54. #### Example use ###
  55. if __name__ == "__main__":
  56. my_menus = """
  57. MENU start
  58. Chose one of these
  59. [1] Fight a monster
  60. [2] Sleep under a tree
  61. [3] Eat the apple
  62.  
  63. MENU fight
  64. Chose a monster
  65. [1] Unicorn
  66. [2] Dragon
  67. [3] Ork
  68.  
  69. MENU sleep
  70. You slept for an hour, but you were awaken by a strange noise overthere.
  71. What will you do
  72. [1] Run away
  73. [2] Go see what caused the noise
  74. [3] Resume your sleep
  75.  
  76. MENU apple
  77. The apple is poisoined. You're dying.
  78. [1] Call the charming prince
  79. [2] Eat the other apple
  80. [3] Pronounce the magic words
  81.  
  82. MENU magic
  83. What is the magic formula ?
  84.  
  85. MENU quit
  86. Do you want to play again ?
  87. """
  88. class Game(MenuCrawler):
  89. def __init__(self):
  90. MenuCrawler.__init__(self, my_menus)
  91. print self.menus
  92. def start(self, choice):
  93. if choice == "1":
  94. self.menu = "fight"
  95. elif choice == "2":
  96. self.menu = "sleep"
  97. elif choice == "3":
  98. self.menu = "apple"
  99. elif choice == "quit":
  100. self.menu = "quit"
  101. def do_quit(self):
  102. Print("Thank you for playing")
  103. raise SystemExit
  104. def fight(self, choice):
  105. if choice in ("1", "2", "3"):
  106. Print("Fights are not yet implemented")
  107. self.menu = "quit"
  108. elif choice == "quit":
  109. self.menu = "quit"
  110. def quit(self, choice):
  111. if choice in ("y", "yes", "ok"):
  112. self.menu = "start"
  113. else:
  114. self.do_quit()
  115. def sleep(self, choice):
  116. Print("This feature is not yet implemented")
  117. self.menu = "quit"
  118. def apple(self, choice):
  119. if choice == "3":
  120. self.menu = "magic"
  121. elif choice == "quit":
  122. self.menu = "quit"
  123. else:
  124. Print("This feature is not yet implemented")
  125. def magic(self, choice):
  126. if choice == "abracadabra":
  127. Print("The magic words save your life!")
  128. self.menu = "start"
  129. elif choice == "quit":
  130. self.menu = "quit"
  131. else:
  132. Print("These are not the magic words ! You're dead.")
  133. self.menu = "quit"
  134. G = Game()
  135. G.run("start")

Message:


Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC