| 1 |
"""Routines that install Adventure commands for the Python 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 inspect |
| 8 |
|
| 9 |
class ReprTriggeredPhrase(object): |
| 10 |
"""Command that happens when Python calls repr() to print them.""" |
| 11 |
|
| 12 |
def __init__(self, game, words): |
| 13 |
self.game = game |
| 14 |
self.words = tuple(words) # protect against caller changing list |
| 15 |
|
| 16 |
def __repr__(self): |
| 17 |
"""Run this command and return the message that results.""" |
| 18 |
output = self.game.do_command(self.words) |
| 19 |
return output.rstrip('\n') + '\n' |
| 20 |
|
| 21 |
def __call__(self, arg=None): |
| 22 |
"""Return a compound command of several words, like `get(keys)`.""" |
| 23 |
if arg is None: |
| 24 |
return self |
| 25 |
words = arg.words if isinstance(arg, ReprTriggeredPhrase) else (arg,) |
| 26 |
return ReprTriggeredPhrase(self.game, self.words + words) |
| 27 |
|
| 28 |
def __getattr__(self, name): |
| 29 |
return ReprTriggeredPhrase(self.game, self.words + (name,)) |
| 30 |
|
| 31 |
|
| 32 |
def install_words(game): |
| 33 |
# stack()[0] is this; stack()[1] is adventure.play(); so, stack()[2] |
| 34 |
namespace = inspect.stack()[2][0].f_globals |
| 35 |
words = [ k for k in game.vocabulary if isinstance(k, str) ] |
| 36 |
words.append('yes') |
| 37 |
words.append('no') |
| 38 |
for word in words: |
| 39 |
identifier = ReprTriggeredPhrase(game, [ word ]) |
| 40 |
namespace[word] = identifier |
| 41 |
if len(word) > 5: |
| 42 |
namespace[word[:5]] = identifier |