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