__main__.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """Offer Adventure at a custom command prompt.
  2. Copyright 2010-2015 Brandon Rhodes. Licensed as free software under the
  3. Apache License, Version 2.0 as detailed in the accompanying README.txt.
  4. """
  5. import argparse
  6. import os
  7. import re
  8. import readline
  9. import sys
  10. from time import sleep
  11. from . import load_advent_dat
  12. from .game import Game
  13. BAUD = 1200
  14. def baudout(s):
  15. for c in s:
  16. sleep(9. / BAUD) # 8 bits + 1 stop bit @ the given baud rate
  17. sys.stdout.write(c)
  18. sys.stdout.flush()
  19. class AdventureArgumentParser(argparse.ArgumentParser):
  20. """ Command-line argument parser for this program. """
  21. default_description = 'Adventure into the Colossal Caves.'
  22. def __init__(self, *args, **kwargs):
  23. super().__init__(*args, **kwargs)
  24. if self.description is None:
  25. self.description = self.default_description
  26. self._add_arguments()
  27. def _add_arguments(self):
  28. """ Add arguments specific to this program. """
  29. self.add_argument(
  30. 'savefile', nargs='?',
  31. help='The filename of game you have saved.')
  32. def make_or_resume_game(gamefile_path=None):
  33. """ Make a new game, or resume from the `gamefile_path`.
  34. :param gamefile_path: The filesystem path of the saved game to
  35. restore, or ``None`` to create a new game.
  36. :return: The `Game` instance.
  37. """
  38. if gamefile_path is None:
  39. game = Game()
  40. load_advent_dat(game)
  41. game.start()
  42. baudout(game.output)
  43. else:
  44. game = Game.resume(gamefile_path)
  45. baudout('GAME RESTORED\n')
  46. return game
  47. def loop(game):
  48. """ The main Read-Eval-Print Loop for this program.
  49. :param game: The `Game` instance to play.
  50. :return: None.
  51. """
  52. while not game.is_finished:
  53. line = input('> ')
  54. words = re.findall(r'\w+', line)
  55. if words:
  56. baudout(game.do_command(words))
  57. def main(argv=None):
  58. """ Main-line code for this program.
  59. :param argv: Sequence of command-line arguments to the process.
  60. If ``None``, defaults to `sys.argv`.
  61. :return: Exit status (integer) for the process.
  62. """
  63. if argv is None:
  64. argv = sys.argv
  65. exit_status = 0
  66. try:
  67. parser = AdventureArgumentParser(prog=argv[0])
  68. options = parser.parse_args(argv[1:])
  69. game = make_or_resume_game(options.savefile)
  70. loop(game)
  71. except EOFError:
  72. # End of command input.
  73. exit_status = 0
  74. return exit_status
  75. if __name__ == '__main__':
  76. exit_status = main(sys.argv)
  77. sys.exit(exit_status)