3.4. textgame.parser

This module’s main class is textgame.parser.Parser. The parser can take user input, call a function that’s associated to the input and return to the user a message describing what happened.

Use actionmap and legal_verbs to define how verbs should be mapped to functions, eg:

parser.actionmap.update({
 "scream": player.scream
})
parser.legal_verbs.update({
 "scream": "scream",
 "shout": "scream"
})

You can use legal_nouns to define synonyms for nouns.

A parser is the only thing needed to during the main loop of a game:

parser = textgame.parser.Parser(player)
while player.status["alive"]:
    response = parser.understand( input("> ") )
    print(response)

This module also provides textgame.parser.EnterYesNoLoop. If a function called by the parser returns an EnterYesNoLoop instead of a string, the parser falls into a mode where it only allows ‘yes’ and ‘no’ as an answer. An object of type EnterYesNoLoop also provides strings/functions to print/call for each case.

Example: a player method that saves the user from drinking poison

@action_method
def drink(self, noun):
    if noun == "poison":

        def actually_do_it():
            self.status["alive"] = False
            return "You drink the poison and die."

        return textgame.parser.EnterYesNoLoop(
             question = "Do you really want to drink poison?",
             yes = actually_do_it,
             no = "You stay alive")
    else:
        # ...
class textgame.parser.EnterYesNoLoop(question, yes, no)[source]

Bases: object

Parameters
  • question (string) – a yes/no question

  • yes – string to return or a function with signature f() -> str or f() -> EnterYesNoLoop that should get called if player answeres ‘yes’ to the question

  • no – same as yes

no()[source]

if no is callable, return its result, else return it

yes()[source]

if yes is callable, return its result, else return it

class textgame.parser.Parser(player)[source]

Bases: object

Parameters

playertextgame.player.Player object

check()[source]

check if every verb in self.legal_verbs has a function mapped to. if not, the game will crash on the input of this verb

logs the error

check_result(result)[source]

checks if result is EnterYesNoLoop or str, if it’s EnterYesNoLoop, return the question and fall back to yes/no mode

do(verb, noun)[source]

call function associated with verb with noun as argument

lookup_noun(noun)[source]
lookup_verb(verb)[source]
understand(input)[source]

based on the input, perform player method and return its output the return value is what can be printed to the user