Developing a text-based adventure in Python (Part 1)

Getting started with basic commands

In this series we will develop a text-based adventure game using the Python programming language. Although various development environments exist that can be used to help design such games (e.g. Twine and ADRIFT) we will strip it down to the bare bones, relying only on the basic Python IDLE programming environment for programming and pencil and paper for design.

It is assumed that you have already setup Python with IDLE and are familiar with the basics of creating, saving and running a new program. Download an appropriate version of Python if you do not have it installed already.

Print and input statements

We begin by using print and input statements to tell part of the story to the player and to get their action. This is shown in the code snippet below.

print("You have reached a cross road. You can go north,\nwest or east, or return south from where you came.")
print("Enter 'n', 's', 'e' or 'w'")
direction=input("> ")

Line 1 of the code uses a print statement to provide contextual (narrative) information to the player. Note that the text within the print statement must be enclosed in quotes.
In line 2 the player options are presented using a print statement.
An input statement is used in line 3 of the code to get the responses from the player. The prompt for the input statement is a ‘>’ symbol followed by a space. The response entered by the player is assigned to a variable called direction.

Gotchas

  1. Make sure you the text used in print statements are enclosed in a pair of quotes.
  2. An open bracket, ‘(‘, must be placed immediately after the print and input keywords. A matching closed bracket, ‘)’ must be placed at the end of the the statement.
  3. Remember to use a backslash, not a forward slash, for special commands like the newline command \n.
  4. When assigning a value to a variable, as done on line 3, use a single = symbol.

Conditional statements

The next step in the development is to process the player’s response.
The code shown below takes the player’s response and determines an appropriate course of action using a conditional statement.

if (direction=="n" or direction=="N"):
    print("You meet a Bugbear")
elif (direction=="e" or direction=="E"):
    print("You discover a treasure chest. It is locked!!")
elif (direction=="w" or direction=="W"):
    print("You have come a dead end.")
elif (direction=="s" or direction=="S"):
    print("Running away are you? You big chicken!")
else:
    print("This is not an option")

Lines 4 and 5 represent the first case of the conditional statement. It tests whether the player inputted the direction ‘n’ or ‘N’ to move north. If the player did
enter this direction then the code uses a print statement to indicate that they have encountered a Bugbear. Lines 6-11 of the code handle the three other directions that the player may have selected. To do this elif statements are used, which is a shorthand for else if. The elif statements include a test condition that evaluates to either true or false – the code on the line following the condition is only executed when the condition is true. Lines 12 and 13 of the code handle all other inputs from the user. This is done using an else statement, which does not include condition since it covers all remaining cases not covered by the previous conditions.

Gotchas

There are several common mistakes to try avoid when using conditional statements:

  1. When testing equality in conditions, make sure you use double equal symbols, ==.
  2. A colon must be placed at the end of an if or elif condition.
  3. The statements that follow each of the if, elif and else lines of code must be indented by a full tab.
  4. You must not include a condition after the else keyword.

Nested if statements

The code shown above implements one step in the text adventure – the user is presented with a narrative, they select an option, a brief description of what they observe is given, then the game ends. This game is clearly not going to engage the player – the game needs to continue until some end resolution is achieved.

Consider the encounter with Bugbear that occurs when the player opts to move north. When this encounter occurs we want to again present the player with some options. One way to do this in code is to use a nested conditional statement, i.e. placing an additional conditional statement inside of the original conditional statement. This is shown in the code below where a nested conditional statement is used to handle the encounter with the Bugbear.

print("You have reached a cross road. You can go north,\nwest or east, or return south from where you came.")
print("Enter 'n', 's', 'e' or 'w'")
direction=input("> ")

if (direction=="n" or direction=="N"):
    print("You meet a Bugbear")
    print("You have the following options")
    print("[A]ttack the Bugbear")
    print("[T]alk to the Bugbear")
    print("[R]un away from the Bugbear")
    response=input("> ")
    if (response=="A" or response=="a"):
        print("Bad move - the Bugbear is too strong for you.")
        print("You are badly wounded. This is the end of your adventure.")
    elif (response=="T" or response=="t"):
        print("The Bugbear is very wise.")
        print("He imparts great wisdom upon you.")
        print("Your intelligence is increased.")
    elif (response=="R" or response=="r"):
        print("You manage to escape the Bugbear.")
        print("You have returned to the crossroad")
elif (direction=="e" or direction=="E"):
    print("You discover a treasure chest. It is locked!!")
elif (direction=="w" or direction=="W"):
    print("You have come a dead end.")
elif (direction=="s" or direction=="S"):
    print("Running away are you? You big chicken!")
else:
    print("This is not an option")

Download source code [conditionals.py].

Lines 6-21 are the updated portion of the code. Additional print statements are added to present options to the player. In this case the options are single word commands with the key letter highlighted, indicating the command that the player would need to enter. Line 11 uses an input statement to get the player’s response and store it in a variable. Lines 12-21 contain a conditional statement that selects an appropriate action based on the response given by the player. Note the indentation of commands used in the nested conditional statements. Indentation is critical in Python – it is used to determine where blocks of code start and end.

Limitations

Using nested conditional statements works in this case, but quickly becomes very messy, resulting in what is referred to as spaghetti code. Furthermore, if we want to be able to return to areas/encounters that have already been visited then this code solution will not work at all.

print

Leave a Reply

Your email address will not be published. Required fields are marked *