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
orf() -> EnterYesNoLoop
that should get called if player answeres ‘yes’ to the questionno – same as yes
-
class
textgame.parser.
Parser
(player)[source]¶ Bases:
object
- Parameters
player –
textgame.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