PROGRAMMING WITH SCRATCH can be a lot of fun, but as you become more skillful at creating games and graphics using this application, you may notice that there are limits to what you can achieve with Scratch. Most computer programmers use text-based languages to create computer programs, including games, desktop applications and mobile apps. Although text-based programming may seem more complicated at first, you will soon find that it is easier to achieve your goals by using code. The Python code language is used by millions of programmers worldwide, including developers at organisations like NASA, Google and CERN.
In this adventure, you’ll discover what you need in order to set up Python on your Raspberry Pi. You’ll write a short program, and learn to use a text editor. After that, you’ll delve deeper into Python, learning about modules and their applications, how to get user input and how to use conditionals. Finally, you’ll put all your new knowledge to use, creating a text-based adventure game in which your user (player) will answer questions and your game will respond based on the answers.
Although this may seem like a major departure from the graphical world of Scratch programming, the good news is that all of the programming concepts you learned in Scratch apply to other languages as well, even those that seem very different. Concepts such as using a sequence of instructions to make something happen, loops, conditionals and variables are common throughout all programming languages. By the end of this adventure, you’ll be able to write some basic Python programs on your Raspberry Pi!
The Raspbian operating system includes the programming environment called Python IDLE. This section introduces you to the programming language and environment used to create Python files and execute them.
The Raspberry Pi operating system Raspbian comes with a text-based computer programming language, Python, already installed. The Pi in Raspberry Pi is a nod towards this programming language, as it is considered an easy language to pick up and is used by coders all over the world.
To work with Python, you use the IDLE programming environment, or integrated development environment (IDE).
In order to create programs on the Raspberry Pi using Python, you use the Python programming environment, which is called IDLE. Notice that there are two versions in the menu system: Python 2 and Python 3 (see Figure 5-1). The projects in this book require Python 3, which you will remember you used in Adventure 4. Just like the English language, Python has evolved through different versions and some of the commands you will learn in this adventure will not work in older versions of IDLE like Python 2 on the Raspbian.
To begin working with Python, open the main menu, navigate to Programming and select Python 3. You will be using Python 3 throughout this book rather than earlier versions, which use a different syntax. The Python shell, or command-line interface, opens and a prompt of three angle symbols (>>>) appears to indicate where you should type your code, as shown in Figure 5-2.
For your first Python program, you’ll write only one line of code, using a function, a piece of code that tells the computer to perform a specific task. For this program, you use the print() function to tell the computer to print some text on the screen. Place the string of text you want the computer to display inside the brackets, with quotation marks around it.
Place your cursor directly after the >>> prompt and type the following line:
print("I am an Adventurer")
Press Enter and see what happens (see Figure 5-3).
You used a text editor to create code files in Python in Adventure 4 when using the turtle module. As you learned in Adventure 4, it makes sense to type all your code into a text file using a text editor and save it, before you test that it works by running it using IDLE. Using a text editor has the added bonus of syntax highlighting, which works by adding colour to different words in your code to make it easier to read. If you use a command-line editor like nano (which you used in Adventure 2) that does not have syntax highlighting, you may find it hard to read a long program. For the projects in this adventure, you use the Python 3 IDLE text editor as you did in Adventure 4.
In the Python programming language, you can create lists to store data—for example, you might want a list of names of the students in your class to use in a program that sends out invitations, or a list of favourite restaurants that your program could suggest when you need an idea for dinner.
The following steps walk you through using a text editor to create a list of objects that you will use later in your adventure game. In this exercise, you will create a new file, add the code to create an inventory, and then save the file.
inventory = ["Torch", "Pencil", "Rubber Band", "Catapult"]
This code creates a list named inventory. Each string, or piece of text data, represents an item on that list.
print(inventory)
print(inventory[3])
As you learned in Adventure 4, Python has a large number of modules—useful blocks of code that you can reuse to avoid having to rewrite the same code over and over each time you need a program that performs the same task. For example, each time you need a program that selects objects from a list randomly, you could write a new function or you could simply use the Python random module and save yourself a lot of time.
In order to use a module within a Python program, you use the Python word import followed by the name of the module. You can then access functions of that module in your program.
In this section, you use the random module along with the inventory list you created in Python to make a program that will select an item from the list randomly.
Starting with the Python file Inventory.py that you created earlier, you will adapt the code to create a new, interactive program that requests user input and responds appropriately.
As you write the code, you will include comments. Comments are notes within your code that explain what a line or section of code in intended to do. Each comment line begins with the # symbol, which tells the computer running the program to ignore that line. If a comment wraps over several lines you need to include a # sign at the beginning of each line so that it is passed over by the IDE.
There are many good reasons for including comments inside your code. Comments can help you remember what each part of the code is doing, should you leave it unfinished for a while. In school, you may use comments to explain to your teacher what each part of your code is doing. If you are working with others, comments help them see what you have done already.
# Adventures in Raspberry Pi Python – Inventory
Note the # symbol at the start of the line, identifying it as a comment.
# You will need the random module and the time module.
import random
import time
# Enter a blank line here
print("You have reached the opening of a cave")
print ("you decide to arm yourself with a ")
time.sleep(2)
quest_item = input("Think of an object
")
print("You look in your backpack for ", quest_item)
time.sleep(2)
print("You could not find ", quest_item)
print("You select any item that comes to hand from the
backpack instead
")
time.sleep(3)
The at the end of the string in the first line doesn’t get printed to the screen; instead, an extra new line is printed. This is helpful for breaking up the text and making it easier to read.
inventory = ["Torch", "Pencil", "Rubber band", "Catapult"]
print(random.choice(inventory))
Functions can take a number of arguments and return a result. Here you pass an argument to the time.sleep() function, to tell the program how many seconds to wait, and then print the result of random.choice.
Figure 5-6 shows the completed code.
Check that your program works by saving the file as inventory1.py in the Documents folder on the Raspberry Pi and then clicking RunRun Module from the toolbar. Enter input when the program prompts for it. You should see results similar to those shown in Figure 5-7.
Text adventure games are fun to create because they are stories written by yourself that your friends and families can interact with. All you need is a bit of imagination and, of course, some programming skills.
In this tutorial, you will create your own adventure game that uses text to direct the player through the game. The program will ask the player to make decisions on what to do next. This may be as simple as finding out the direction in which she wants to turn next.
As the text adventure game relies on the player (user) to interact with the game to make decisions, you will need to use the input() function.
direction1 = input("Do you want to go left or right? ")
This line of code asks the player to answer the question, “Do you want to go left or right?” The program will wait for the player to type in an acceptable response—one that the program can understand.
Once the player has responded, you want something to happen based on her answer. You therefore need to use conditionals. You used conditionals in your Scratch adventure game in Adventure 3 to control the movement of the adventurer sprite, using the forever if control block.
Remember that creating a conditional is like asking a question where there are two or more outcomes. For example, you could ask the question “Is it raining?” If the answer is yes, you should put on a raincoat; if the answer is no, you should go out without a jacket. The key word used here is “if”.
You will use if in Python 3 to create your game conditions. Open a new Python IDLE 3 text editor window and save the file as AdventureGame.py.
import time
hp = 30
print("You are standing on a path at the edge of a
jungle. There is a cave to your left and a beach
to your right.")
time.sleep(1)
direction1 = input("Do you want to go left or right? ")
if direction1 == "left":
print("You walk to the cave and notice there is an
opening.")
elif direction1 == "right":
print("You walk to the beach but remember you do
not have any swimwear.")
else:
print("You think for a while")
if, elif and else are the Python words used to check conditions. In the preceding code, if the player types left, the program prints the statement, “You walk to the cave and notice there is an opening”; else if (elif) the player types in right, the program prints a different piece of text. Finally, if the player types in any answer that is not left or right (else), the program prints, “You think for a while”. Figure 5-8 shows this code in the text editor.
So far, the player has not been required to input specific answers in order for the game to move on. If the player does not input anything at all, the game simply stalls; and if the player types an unrecognized answer, the game says, “You think for a while”. You want the player to input one of the responses that you have defined, left or right, to move on to the next location. You can ensure she inputs one of the desired responses by adding a while loop to your code. This will loop the user input question until the player types in a response that you were looking for—left or right—to move on. For example:
# Loop until we get a recognised response
while True:
direction1 = input("Do you want to go left or right? ")
direction1 = direction1.lower()
if direction1 == "left":
print("You walk to the cave and notice there is an
opening.")
break # leave the loop
elif direction1 == "right":
print("You walk to the beach but remember you do not
have any swimwear.")
break # leave the loop
else:
print("You think for a while")
In this code, shown also in Figure 5-11, you can see in bold text the Python words while True: added before the user input question, and break added within the conditionals for left and right. The while True: condition will loop the question over and over until the player enters either left or right so that the game does not end if the player types anything else.
In the text adventure game so far, you have created a variable for health points (hp = 30), like the variable you created in the Scratch adventure game in Adventure 3. Here you have given an initial value that will change as the player plays the game. The value you have given is 30, but this could be any value of your choosing.
Now code can be added that will change the hp value based on the decisions made by the player. You name a variable using the form name = value, as in the following example:
hp = 30
Here are two ways to change the value of the hp variable in Python 3:
To subtract 10, use hp = hp – 10 or hp -= 10
To add 10, use hp = hp + 10 or hp += 10
To make the game more interesting for the player, you can add some code to the end of what you have already written to tell her how many health points she has after each move:
# Check health points after the player has made a move
print("You now have ", hp, "health points")
if hp <= 0:
print("You are dead. I am sorry.")
The last two lines add a conditional so that if the value of the hp variable is less than or equal to 0, the statement “You are dead. I am sorry.” is displayed and the game ends.
Now put all the elements together in your text adventure game by typing the following program into a new Python 3 IDLE text editor window:
Test to see if your code works by saving the file as AdventureGame1.py in your Documents directory on the Raspberry Pi and then running it (see Figure 5-12). (Be sure to add the 1 in the filename to keep this file separate from your original AdventureGame.py file.)
Although the game works, you will find it difficult to scale it up to include more locations and directions, such as going into the cave and then deeper into the cave, especially if the game relies on input from players to make decisions. You could add more conditionals by copying and pasting those you have already created but your code will get messy and out of control very quickly. It will also be difficult to locate any bugs, or make changes without introducing even more bugs!
The best solution is to create your own functions. Until now you have been using pre-existing functions from other Python modules such as time and random, but you can also create your own. Writing your own functions is easy; for example, this is how you would write a function called multiply that multiplies its two arguments and returns the result:
def multiply(m, n):
return m * n
Just like the functions you used earlier in this adventure, these can take a number of arguments and return a result. They are a very useful way of organising your code. You can use various ways to reorganise your code into different functions. This process is called refactoring and is a logical process when developing computer programs. One way of reorganising the adventure game you have created so far is to create and use two functions: get_input() and handle_room().These functions are described in the following sections.
The get_input() function will keep asking the player to enter input (using the text in the prompt argument) until it matches one of the accepted inputs. For example:
get_input("Do you want to go left or right? ", ["left", "right"])
This function will keep asking the player the same question until she types one of the accepted inputs, which in this case are left and right.
The handle_room() function will contain the main logic for changing locations in the adventure game. The function will take the current location as its argument, and then use conditionals to decide what to do based on that location. For most locations, the function will ask the player to input a direction. The specific input determines which location the player will move to next.
Up to this point, you wrote all of your game logic in the while loop. With the following code, you move most of the logic into separate functions, avoiding repetitive code. The new loop calls the handle_room() function to perform a task appropriate for the current room, and then updates the location variable with the new room. This is a little more advanced than the code you have written so far. It will require you to check and double-check that your indentation is correct and you have not made any syntax errors!
Open a new text editor window and save the file as AdventureGame2.py in your Documents directory. Follow the steps below to add functions to your adventure game.
# Create health points variable
hp = 30
def get_input(prompt, accepted):
while True:
value = input(prompt).lower()
if value in accepted:
return value
else:
print("That is not a recognised answer,
must be one of ", accepted)
def handle_room(location):
global hp
if location == "start":
print("You are standing on a path at the edge of a ↩
jungle. There is a cave to your left and a beach to ↩
your right.")
direction = get_input("Do you want to go left or right? ",
["left", "right"])
if direction == "left":
return "cave"
elif direction == "right":
return "beach"
elif location == "cave":
print("You walk to the cave and notice there is an ↩
opening.")
print("A small snake bites you, and you lose 20 ↩
health points.")
hp = hp - 20
answer = get_input("Do you want to go deeper?",
["yes", "no"])
if answer == "yes":
return "deep_cave"
else:
return "start"
elif location == "beach":
print("You walk to the beach but remember you do
not have any swimwear.")
print("The cool water revitalizes you. You have never
felt more alive, gain 70 health points.")
hp += 70
return "end"
else:
print("Programmer error, room ", location, " is
unknown")
return "end"
location = "start"
# Loop until we reach the special "end" location
while location != "end":
location = handle_room(location) # update location
# Check we are not dead each turn
print("You now have ", hp, "health points.")
if hp <= 0:
print("You are dead. I am sorry.")
break
print("Your adventure has ended, goodbye.")
Each time around, the loop checks that the health points are greater than or equal to zero (checking that the player is not dead!) so that the game can continue. The loop will also end if the location returned by handle_room is end, a special room name indicating the end of the game. Figure 5-13 shows the refactored code using functions in the Python adventure game.
If you want to learn more about programming in Python on your Raspberry Pi, you can find a wide assortment of resources. Here are a few to try:
Python Command Quick Reference Table |
|
Command |
Description |
# |
The # symbol is used at the beginning of a code line to indicate the line is a comment, not part of the program’s instructions to the computer. |
|
Returns a new line in a string. |
break |
Breaks out of a for or while loop. |
def |
Allows you to define a function of your creation. |
elif |
Short for ‘else if’, the elif syntax allows you to create multiple conditions that make something happen when they return a value of true. |
for |
for loops are traditionally used when you have a piece of code which that you want to repeat x number of times. |
if |
Sets a condition which, if true, makes something happen. |
if…else |
Sets a condition which, if true, makes one set of things happen, or if false makes a different set of things happen. |
import |
Imports modules and libraries to add more functionality to your code. |
input() |
A function that asks for user input and converts it into a string. |
inventory = ["Torch", "Pencil", "Rubber Band", "Catapult"] |
An example of a list in python. Lists can contain values or strings that are separated by commas and encased in square brackets. |
name = value |
An example of a variable. |
print() |
A function that prints anything inside the brackets. |
print(inventory[3]) |
An example of using the print() function to print item number 3 in the inventory list. |
random |
A Python module that returns a random value. |
return |
The return keyword is used when a function is ready to return a value. |
time |
Python module that provides various time-related functions, such as sleep. |
while |
A while loop continually repeats if a given condition is true. |