Interactive Fiction in Python Part I

In a recent blog post, I talked about the early days of computer gaming and the then-popular genre of Interactive Fiction, also popularly known as text adventures. As promised, here is the first part in a tutorial series on how to create a simple text adventure in Python.

Using Python, we will have the player entering text commands to move around a virtual world and interact with the environment. The player will be expected to solve puzzles in order to move through the game world and achieve the objective. This tutorial assumes that you have a basic knowledge of Python programming fundamentals such as raw_input, print, loops, and functions. Later tutorials will cover topics such as conditionals and classes.

Scenario: The user plays the role of Harry Potter. Harry's friends Ron and Hermione have been captured by the Evil Lord Voldemort and he has to rescue them. I already have a playable online version of this game written in JavaScript that you can play by clicking here. Note that the online version has images while the Python version we are working on does not.

Getting Started

We will need to take care of the following to get our game started.

1) Initialize the game. This involves importing the necessary modules, and setting variables to their starting values.

2) We will have to set up the player and any attributes associated with the player. In our simple game, we only really need to keep track of the player's location, which will be an integer value. Later, we can add health and a score if we so desire.

3) Print the game title (header) and explain the scenario to the user.

4) Create the main game loop. Inside the main loop we will want to print the header and get the user's commands.

Here is what the screen should look like after the player has made it through the splash screen:

As you can see, the header is nicely drawn using ASCII Art. You can create your own ASCII Art text by going to this website (which was discovered by one of my students).

The code is listed below and you should be able to copy and paste it into your favorite code editor. Be sure to save it with the .py extension.

Here are some key points to look at:

1) The only real variable we have regarding the player at this point is the player location which is stored in the variable player_location. Later, each location (room) in our virtual world with have an id number.

2) We use a while loop to keep the game going.

3) We have some code to print the player's location. Since the rooms have not been set up yet, we are simply printing the integer value of the player's location.