123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- """Offer Adventure at a custom command prompt.
- Copyright 2010-2015 Brandon Rhodes. Licensed as free software under the
- Apache License, Version 2.0 as detailed in the accompanying README.txt.
- """
- import argparse
- import os
- import re
- import readline
- import sys
- from time import sleep
- from . import load_advent_dat
- from .game import Game
- BAUD = 1200
- def baudout(s):
- for c in s:
- sleep(9. / BAUD) # 8 bits + 1 stop bit @ the given baud rate
- sys.stdout.write(c)
- sys.stdout.flush()
- class AdventureArgumentParser(argparse.ArgumentParser):
- """ Command-line argument parser for this program. """
- default_description = 'Adventure into the Colossal Caves.'
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- if self.description is None:
- self.description = self.default_description
- self._add_arguments()
- def _add_arguments(self):
- """ Add arguments specific to this program. """
- self.add_argument(
- 'savefile', nargs='?',
- help='The filename of game you have saved.')
- def make_or_resume_game(gamefile_path=None):
- """ Make a new game, or resume from the `gamefile_path`.
- :param gamefile_path: The filesystem path of the saved game to
- restore, or ``None`` to create a new game.
- :return: The `Game` instance.
- """
- if gamefile_path is None:
- game = Game()
- load_advent_dat(game)
- game.start()
- baudout(game.output)
- else:
- game = Game.resume(gamefile_path)
- baudout('GAME RESTORED\n')
- return game
- def loop(game):
- """ The main Read-Eval-Print Loop for this program.
- :param game: The `Game` instance to play.
- :return: None.
- """
- while not game.is_finished:
- line = input('> ')
- words = re.findall(r'\w+', line)
- if words:
- baudout(game.do_command(words))
- def main(argv=None):
- """ Main-line code for this program.
- :param argv: Sequence of command-line arguments to the process.
- If ``None``, defaults to `sys.argv`.
- :return: Exit status (integer) for the process.
- """
- if argv is None:
- argv = sys.argv
- exit_status = 0
- try:
- parser = AdventureArgumentParser(prog=argv[0])
- options = parser.parse_args(argv[1:])
- game = make_or_resume_game(options.savefile)
- loop(game)
- except EOFError:
- # End of command input.
- exit_status = 0
- return exit_status
- if __name__ == '__main__':
- exit_status = main(sys.argv)
- sys.exit(exit_status)
|