Page 46 - Programming the Raspberry Pi Getting Started with Python
P. 46
Run this program a few times to check that it is picking different words from the list.
This is a good start, but it needs to fit into the structure of the game. The next thing to do is to
define a new variable called lives_remaining. This will be an integer that we can start off at 14 and
decrease by 1 every time a wrong guess is made. This type of variable is called a global variable,
because unlike variables defined in functions, we can access it from anywhere in the program.
As well as a new variable, we are also going to write a function called play that controls the game.
We know what play should do, we just don’t have all the details yet. Therefore, we can write the
function play and make up other functions that it will call, such as get_guess and process_guess, as
well as use the function pick_a_word we’ve just written. Here it is:
A game of Hangman first involves picking a word. There is then a loop that continues until either
the word is guessed (process_guess returns True) or lives_remaining has been reduced to zero.
Each time around the loop, we ask the user for another guess.
We cannot run this at the moment because the functions get_guess and process_guess don’t exist
yet. However, we can write what are called stubs for them that will at least let us try out our play
function. Stubs are just versions of functions that don’t do much; they are stand-ins for when the full
versions of the functions are written.
The stub for get_guess just simulates the player always guessing the letter a, and the stub for
process_guess always assumes that the player guessed wrong and, thus, decreases lives_remaining
by 1 and returns False to indicate that they didn’t win.
The stub for process_guess is a bit more complicated. The first line tells Python that the
lives_remaining variable is the global variable of that name. Without that line, Python assumes that