Page 48 - Programming the Raspberry Pi Getting Started with Python
P. 48
This function starts with an empty string and then steps through each letter in the word. If the letter
is one of the letters that the player has already guessed, it is added to display_word; otherwise, a
hyphen (-) is added. The built-in function find is used to check whether the letter is in the
guessed_letters. The find function returns -1 if the letter is not there; otherwise, it returns the
position of the letter. All we really care about is whether or not it is there, so we just check that the
result is greater than -1. Finally, the word is printed out.
Currently, every time process_guess is called, it doesn’t do anything with the guess because it’s
still a stub. We can make it a bit less of a stub by having it add the guessed letter to
guessed_letters, like so:
Open the file 4_7_hangman_print_word.py and run it. You will get a result something like this:
It’s starting to look like the proper game now. However, there is still the stub for process_guess to
fill out. We will do that next:
When the player enters a guess, they have two choices: They can either enter a single-letter guess or
attempt to guess the whole word. In this method, we just decide which type of guess it is and call
either whole_word_ guess or single_letter_guess. Because these functions are both pretty
straightforward, we will implement them directly rather than as stubs: