Developing a text-based adventure game (Part 4)

Developing a battle system

In this tutorial we will look at the development of a simple battle system. We restrict our attention to a one-on-one battle.
We will implement a Dungeons and Dragons like battle system, where the player and the monster they are facing have a number of hitpoints. The player and monster will take it in turns to attack the other entity. Each attack causes damage that reduces the hitpoints of the entity that was hit. The damage caused by an attack will be randomly determined, but must lie between a predetermined minimum and maximum damage. The battle ends when the hitpoints of either the player or monster are reduced to zero or below.

Initial implementation

The battle mechanics will be encapsulated within the battle function.
The function takes seven inputs. The first three inputs are used for player information, describing the number of hitpoints that they had at the beginning of the combat, the minimum damage that one of their attacks does, and the maximum damage done by their attack. The remaining inputs are used for the title/name of the monster, the monster’s hitpoints and the minimum and maximum damage done by their attack.

The code for the battle mechanics is shown below. The battle function is tested by calling the function at the end of the code listing.

import random

def battle(hitpoints, minDamage, maxDamage,
           monsterTitle, monsterHitpoints,
           monsterMinDamage, monsterMaxDamage):
    playerAttack=True
    while (hitpoints>0 and monsterHitpoints>0):
        if (playerAttack):
            damage=random.randint(minDamage, maxDamage)
            monsterHitpoints=monsterHitpoints-damage
            print("You did {0:d} hitpoints damage".format(damage))
            if (monsterHitpoints <= 0):
                print("The {0} is dead".format(monsterTitle))
            playerAttack=False
        else:
            damage=random.randint(monsterMinDamage, monsterMaxDamage)
            hitpoints=hitpoints-damage
            print("You took {0:d} hitpoints damage".format(damage))
            if (hitpoints <= 0):
                print("You have been killed".format(monsterTitle))
            playerAttack=True

battle(20, 1, 8, "Ogre", 25, 1, 12)

Download source code [Battle mechanics (version 1)].

To randomise the amount of damage done we need to import the random module. From this module we use the randint function, which generates a random integer between the lower and upper bounds which are passed as inputs to the function. To keep track of whether it is the player’s turn or the monster’s turn we use a boolean-valued variable called playerAttack (line 6). This variable can be set to either true or false. A while loop is used to provide a sequence of attacks that continue until either the player or monster is reduced to zero or less hitpoints (line 7). Lines 8-14 of the code implement the player’s attack. The randint function is used to determine the amount of damage done, this is then subtracted from the monster’s hitpoints. If the monster’s hitpoints are reduced below zero, then the monster is declared dead. Lines 15-21 use a similar sequence of code to implement the monster’s attack. The boolean-valued playerAttack variable is updated after each attack to ensure that the player and monster have alternate attacks.

Determining if attacks hit

In the first version of the battle mechanics code all attacks hit. However it is more realistic that only some attacks hit – the attacker may have just swung wildly and missed their target, or the defender may have managed to dodge the attack, or perhaps even parry the attack with their shield. The improve the battle mechanics we adapt the code so that only some of the attacks hit their target. In the code shown below we assume that the player has a 50% chance of hitting their opponent, while the monster only has a 25% chance of hitting.

def battle(hitpoints, minDamage, maxDamage,
           monsterTitle, monsterHitpoints,
           monsterMinDamage, monsterMaxDamage):
    playerAttack=True
    while (hitpoints>0 and monsterHitpoints>0):
        if (playerAttack):
            hitRoll=random.randint(1,20)
            if (hitRoll>=11):
                damage=random.randint(minDamage, maxDamage)
                monsterHitpoints=monsterHitpoints-damage
                print("You hit!")
                print("You did {0:d} hitpoints damage".format(damage))
                if (monsterHitpoints <= 0):
                    print("The {0} is dead".format(monsterTitle))
            else:
                print("You missed")
            playerAttack=False
        else:
            hitRoll=random.randint(1,20)
            if (hitRoll>=16):
                damage=random.randint(monsterMinDamage, monsterMaxDamage)
                hitpoints=hitpoints-damage
                print("{0} hit".format(monsterTitle))
                print("You took {0:d} hitpoints damage".format(damage))
                if (hitpoints <= 0):
                    print("You have been killed".format(monsterTitle))
            else:
                print("{0} missed".format(monsterTitle))
            playerAttack=True

Download source code [Battle mechanics (version 2)].

Lines 7 and 8 of the above code are used to determine whether or not the player hits the monster. A random integer between 1 and 20 is generated and if this number if 11 or larger the player hits the monster, otherwise the attack results in a miss. Similar code is given on lines 19-20 to determine whether or not the monster hits.

Improvements

We improve the code by firstly generalising the hit chances of the player and monster by adding these as variables. We also add a return statement at the end of the code showing how many hitpoints the player has at the end of the battle. This will be used when we call the function in the game to keep track of the ongoing health of the player as well as to determine whether or not the game continues.

def battle(hitpoints, minDamage, maxDamage, toHit,
           monsterTitle, monsterHitpoints,
           monsterMinDamage, monsterMaxDamage, monsterToHit):
    playerAttack=True
    while (hitpoints>0 and monsterHitpoints>0):
        if (playerAttack):
            hitRoll=random.randint(1,20)
            if (hitRoll>=toHit):
                damage=random.randint(minDamage, maxDamage)
                monsterHitpoints=monsterHitpoints-damage
                print("You hit!")
                print("You did {0:d} hitpoints damage".format(damage))
                if (monsterHitpoints <= 0):
                    print("The {0} is dead".format(monsterTitle))
            else:
                print("You missed")
            playerAttack=False
        else:
            hitRoll=random.randint(1,20)
            if (hitRoll>=monsterToHit):
                damage=random.randint(monsterMinDamage, monsterMaxDamage)
                hitpoints=hitpoints-damage
                print("{0} hit".format(monsterTitle))
                print("You took {0:d} hitpoints damage".format(damage))
                if (hitpoints <= 0):
                    print("You have been killed".format(monsterTitle))
            else:
                print("{0} missed".format(monsterTitle))
            playerAttack=True
    return hitpoints

Testing the balance of the battle mechanics

Before we add the battle mechanics to the game we need to test it to make sure it has the right balance. We don’t want to always die when they battle a monster, but at the same time the monster should not be a pushover. Furthermore, if the player acquires an item that is supposed to give them an edge in combat then it should indeed give them and edge. To test the battle function we need to call it many times and then analyse the number of player wins versus the number of player losses. The best way to do this to use a for loop as shown in the code below.

wins=0
for i in range(0,1000):
    hps=battle(20, 1, 8, 11, "Ogre", 25, 1, 12, 16)
    if (hps>0):
        wins=wins+1

print(wins)

In this case the player has 20 hitpoints and a to-hit-roll of 11 (meaning they will need at least an 11 on a roll between 1 and 20 to hit). The monster has 25 hitpoints, does more damage, but is only half as likely to hit. Running the battle mechanics 1000 times with the given configuration results in the player winning 60.5% of the battles. This is probably too high in the situation when the player has not found the sword, but too low if they have found the sword. This suggests we need to adjust the player statistics for these two scenarios. We will use trial an error to get a 20% win chance if they don’t have the sword and an 80% win chance if they do have the sword.

Modifying the player’s damage to 1-4 hps and increase the to-hit-roll to 12 gives the player a win percentage of approximately 20%. On the other hand, if we change the player’s damage to 4-10 and decrease the to-hit-roll to 11, the player will have a win percentage of 79%.

Integrating battle mechanics into the game

To integrate the battle mechanics into the game we modify the playLocation3 function. When the player selects the attack option, the code will call the battle function. The values passed to the battle function depend on whether or not the player has picked up the sword earlier in the game, remembering that possessing the sword gives the player a much better chance of defeating the Ogre (compare lines 20 and 23).

def playLocation3():
    global inventory
    print("You reach what looks like a rudimentary camp site.")
    print("You notice a fire pit in the middle of the camp site.")
    print("Scattered around the fire pit are the many bones picked clean of flesh.")
    print("Ominously some of the bones look human like.")
    print("Just as you finish surveying the scene you here a roar.")
    print("Running towards you, wielding a large club is an Ogre.")
    print("You can either (f)lee to the south, (a)ttack the Ogre or try to (t)alk with the Ogre.")
    response=input("> ")
    if (response=="f"):
        print("You run away from the Ogre at full speed")
        print("The Ogre pursues for a while but eventually gives up.")
        print("You survive another day.")
        print("Once you know you are safe you continue your journey southward at a slower pace.")
        location="location1"
    elif (response=="a"):
        if ("sword" in inventory):
            print("As the Ogre draws near you draw your sword.")
            hps=battle(20, 4, 10, 11, "Ogre", 25, 1, 12, 16)
        else:
            print("You pick up a fallen branch from the ground and prepare to battle the Ogre")
            hps=battle(20, 1, 4, 12, "Ogre", 25, 1, 12, 16)
        if (hps >0):
            print("You have felled the evil beast.")
            print("You search the body of the Ogre and find a key.")
            print("You take the key and head back towards the clearing with the chest.")
            location="location1"
            inventory.append("key")
        else:
            print("You fight valiantly with the Ogre.")
            print("You manage to inflict several telling blows against it but it fights on.")
            print("Having dodged several sweeping blows, the Ogre brings its club down upon you with a crash.")
            print("...")
            location="finish"    
    elif (response=="t"):
        print("You attempt to make conversation with the Ogre but this only makes it more angry.")
        location="location3"
    else:
        location="location3"
    return location

Download source code [Stage 4 code]

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.