How to code your own adventure game in Python

How to code your own adventure game in Python
(Image credit: Future)

How to code your own adventure game in Python

Python

(Image credit: Future)

The Raspberry Pi is a wonderful piece of technology, but many people don't use it to its full potential. With your Raspberry Pi you can create anything you want – a robot that senses its environment, a media centre to watch movies, or a world of fantasy and adventure created from some simple lines of code and a lot of imagination from yourself.

In the 1980s, computer graphics were still in their infancy, with blocky game characters and a limited palette of colours to work with. It was very common for adventure and role-playing games to be completely text-driven, with the player using their imagination to create visions of the game world.

Games such as Zork created rich worlds, with engaging stories and characters, but with very few graphics to illustrate the environments. This remained the case until the late 1980s and early 90s, and only changed due to some fantastic work by LucasArts, which created a collection of classic graphic adventure games such as Loom, Monkey Island and Full Throttle.

For this tutorial, we will be using our Raspberry Pi and a programming language called Python to create our very own text adventure, with our own game world and some characters to inhabit that world. And all of this will be created using some Python code and a few programming concepts.

Python is an easy-to-learn programming language, which has become a firm favourite for Raspberry Pi users and schools across the UK.

So what is Python?

Python is a textual programming language, and by that we mean that it is typed into an editor. Python uses a very forgiving syntax and is very easy to read, which makes learning to code a really enjoyable experience.

On the Raspberry Pi, we already have a great code editor installed as standard – it's called IDLE and we will be using it to build our game. You can find a link to IDLE on the Raspberry Pi desktop.

Python comes pre-installed on every Raspberry Pi that is running the Raspbian operating system. If you haven't got Raspbian installed on your Pi, you can grab a copy from the Raspberry Pi website.

It is part of the easy-to-use NOOBS (New Out Of the Box Software) archive, which can be downloaded and then extracted to a blank 4GB (or greater) SD card.

Currently there are two versions of Python available: versions 2.7 and 3. For this tutorial, we will be using 2.7, because it has the greatest amount of support and documentation. Python 3 is an excellent language to learn and it is certainly the future of the language, but it is currently in a state of flux and should only be used by experienced Python programmers.

Creating a narrative

Our game needs two things: a story to keep the player entertained, and logic to control how the story unfolds. For our story we're creating the world of Narule, where magic and adventure are around every corner. And we're creating a hero – you – who must travel the land, visiting new villages and settlements, and talking to people to learn more about this land and the dark shadow cast upon it.

To start our project off, we've created some narrative for you to expand upon. Feel free to make the story your own – that's the whole point of this tutorial. This is your game. To get you started, we've created some code to act as a starter template. You can download a free copy here.

Download the code, then open it using IDLE ('File > Open' and navigate to where you downloaded the code). Now take a look at the code and pay particular attention to any lines that start with a #, because these are comments in the code, which have been added to help you understand what the code is doing at that point.

Currently our code has a basic story for us to expand upon, and we will do that during the course of this tutorial. Our story unfolds via blocks of text that form our narrative, and you will see that each block looks similar to this:

chapter1 = "It was a cold night, and the rain swept in from

the west with a ferocity known only to the gods"

These are called variables, and they enable us to store lots of text or numbers. We use them to contain our story, and then when we want to use them, we use the print function like this:

print chapter1

The print function looks inside the variable and prints its contents on the screen, which is really handy and means that we only have to write the story once and we can re-use it as many times as we wish.

Programming concepts

Python

(Image credit: Future)

Python is a really great language to learn because it is very easy to understand, and once you master the concepts of programming logic with Python, you will be well on your way to developing larger applications.

No matter what language you use, the underlying concepts of coding provide a firm foundation that can be used across many languages. The main concepts are:

Sequences

A series of tasks required to be completed in a certain order. For example, the steps needed to solve a maze.

Loops

A way to repeat a sequence. Can be run for ever (while True) or controlled using a for statement (for x in range(0,3)).

Parallelism

Running more than one sequence of code at the same time.

Events

An event is a trigger that starts a sequence of code, and the most visible event in the game we're creating is entering the name of our hero to start the game.

Data

We use a variable to store the value of our hero's name, and then we can later retrieve and manipulate the variable to show the player's name throughout the game, personalising the gaming experience.

Conditionals

Conditionals form the basis of our logic, and they provide a method for us to compare data against the input given by the player. We used conditionals in our game to compare the answer given to the expected answer. If they matched, in Boolean logic this would be classed as TRUE.

Operators

These are the basic mathematical rules that we learned back in school. We can apply operators to text and numbers, which enables us to perform calculations in our code and iterate data if required.

1. Play the game

Python

(Image credit: Future)

IDLE has two windows to work with: the editor, containing our code, and a shell, where our game is played. To launch the game, in the editor click on 'Run', then 'Run Module'.

The shell window appears in front of every other window and our game starts to play.

2. Import modules

Python

(Image credit: Future)

Modules created by other coders can be imported into your code. We're importing two modules: Random, which contains code that enables us to use random choice for our character; and Time, which enables us to work with time and pause the game.

3. Create functions

Python

(Image credit: Future)

You can group lots of code into a function. To create one, we use def name(): – this creates a function called name, and we can call the function whatever we want.

We press [Enter] and Python indents our code by four spaces, and awaits the code to be run in this function.

4. Use variables

Python

(Image credit: Future)

We use variables to store information we can use later. For example, we save our narrative and re-use it many times. Think of variables as empty boxes – we can put anything in them and write their name on the side.

You will see the term 'global' used with some variable names; this enables us to use them inside and outside of functions.

5. Get input

Python

(Image credit: Future)

Raw input is the Python way of asking for input from the player. We use it to capture the name of the player and to capture their decisions in the game.

Raw input captures keyboard input as a string of text, so any numbers captured need to be converted to an integer or float, and this can be done using the int() and float() helper functions.

6. Make choices

Python

(Image credit: Future)

Conditional statements are logical choices; we use them to control the flow of the game – for example, which direction do you go?

We store the direction that the player wishes to go as a variable called move, then compare the value stored in the variable with the key we asked the user to press. If the two match, the related code is run.

7. Else and else if

Python

(Image credit: Future)

If..elif..else are further conditional statements and they work as follows: the first condition is looked at, and if that is correct (or true in Python), the code underneath this condition is run. Else if (elif) this condition is true, the code is run for this statement.

Else is all the above conditions are false, then this must be true, so this code is run.

8. Use lists

Python

(Image credit: Future)

Lists are large containers that can hold lots of data. Think of them as a filing cabinet filled with documents. In our game, we used a list to store our inventory of items (our sword and shield).

We firstly create an empty list by using:

"weapons = []"

Just like variables, we can give our list any name we wish. To add to our list we use:

weapons.append("sword")

9. Pick a number

Python

(Image credit: Future)

Random numbers help our hero to be completely unique. To randomly select these numbers, we use the random module, in particular a function called randint, or random integer.

To use randint, we must tell it what range of numbers to work with, and this is done as follows:

randint(5,20)

This creates a range between 5 and 20, and asks randint to pick a random number in that range.

10. Introduce people

Python

(Image credit: Future)

Our game needs interesting people to speak to, so let's create one. You will see on line 57 of the code that we have a new function that handles a random villager.

Their name is random and is chosen from a list, but first we shuffle the list and then select the first item from the list, which in Python is always 0 (zero) or npcnamechoice[0].

11. Expand the story

Python

(Image credit: Future)

Adding new content to your game is easy. If you wish to add new characters or villagers, the best way is to create a new function. That way the code for each new entry is contained in its own function, but can be easily used in your game.

Your narrative should piece together these functions and provide a linear story for the player to follow.

12. Pick a fight

Python

(Image credit: Future)

What about combat? Enemies can be created in the same way as villagers, but perhaps you would like to give them randomly assigned health and magic points (HP and MP in adventure speak), just as you have given your hero.

Create a new function that contains an enemy and place it into your code at a set point, then test your code.

13. Join strings and numbers

Python

(Image credit: Future)

When working with text or, in Python speak, strings, we may want to join a string and a number together. If we try to do it like this:

print "Hello" + 1

Python produces an error saying that the two cannot be joined. But if we wrap the integer in a helper function called str() we can join them both together like so:

print "Hello" + str(1)