Code your own Python text adventure
Nate Drake guides you through creating your own interactive text adventure with Python. This time, we LOOK at items…
CORDING ACADEMY
MU
Credit: https://codewith.mu
Part Two!
Don’t miss next issue, subscribe on page 16!
OUR EXPERT
Nate Drake wants to dedicate this series to his dad, who once told him that no one was ever going to pay him to sit around and play video games.
QUICK TIP
If you find following the code changes difficult, download the sample scripts first and run them to see how everything works. Find the repository here: https://github. com/azuregate/ lxfpython textadventure.
Inthe first part of this series, we explored how to create and move between rooms, which is the basis for any solid text adventure. Hopefully by now you’ll have mapped out your own adventure, either using good old-fashioned grid paper or specialist software such as IFMapper.
Moving between areas is all well and fine but the essence of any text adventure centres around the items you find. Sometimes these are things you can pick up to use later. In other cases, examining items might give you clues on how to progress to other areas.
Setting up an inventory for your player is simply a matter of adding the attribute to the Player class:
The previous move function we used is going to get unwieldy if we keep adding the full code for player actions. It’s better to spin off commands like listing the player inventory into a separate function after Room and Player classes and attributes have been listed:
This function is simple in that it just lists the player’s name, then goes through their inventory listing items. Players can invoke it any time by typing INVENTORY . This is part of the revised action_input that allows you to do more than just explore rooms (more on this later).
Intriguing items
Currently there are no items to fill the inventory. You could simply add text strings to the inventory, such as
This would work for the INVENTORY command, in that it would list all these items one at a time, but it’s a bit thin on detail. Part of the fun of text adventures is knowing which items to pick up and use to interact with your environment. This is why it’s best to create a new Item class at the top of your script: