18. Adventure Game with Structural Pattern Matching
By Bernd Klein. Last modified: 10 Nov 2023.
Introduction
In this section of our Python tutorial, we introduce structural pattern matching through an intriguing scenario—a hypothetical text-based adventure game.
Text adventure games, often referred to as interactive fiction, are a type of computer game that relies primarily on text-based descriptions and typed language commands for user input, rather than graphics and sound. Typical user input for most of these games look like:
- 'help'
- 'show inventory'
- 'go north'
- 'go south'
- 'drop shield'
- 'drop all weapons'
A notable example of such a game is "Hack," a text-based role-playing game developed in the 1980s at the Massachusetts Institute of Technology (MIT) and more commonly recognized as "NetHack."
We will showcase Python code snippets that simulate scenarios within a text adventure game, while also elucidating significant aspects and features of structural pattern matching.
command = input("What are you doing next? ")
action, object = command.split()
print(f"{action=}, {object=}")
OUTPUT:
action='take', object='sword'
What if the user types less or more than 2 words?
command = input("What are you doing next? ")
words = command.split()
no_of_words = len(words)
if no_of_words == 1:
print(f"action without object: {action=}")
elif no_of_words == 2