Game Development Reference
In-Depth Information
9 - Hangman
67. print(HANGMANPICS[len(missedLetters)])
68. print()
This code defines a new function named displayBoard() . This function has four
parameters. This function will implement the code for the "Show the board and blanks to the
player" box in our flow chart. Here is what each parameter means:
— HANGMANPICS - This is a list of multi-line strings that will display the board as
ASCII art. We will always pass the global HANGMANPICS variable as the argument
for this parameter.
— missedLetters - This is a string made up of the letters the player has guessed that
are not in the secret word.
— correctLetters - This is a string made up of the letters the player has guessed
that are in the secret word.
— secretWord - This string is the secret word that the player is trying to guess..
The first print() function call will display the board. HANGMANPICS will be a list of
strings for each possible board. HANGMANPICS[0] shows an empty gallows,
HANGMANPICS[1] shows the head (this happens when the player misses one letter),
HANGMANPICS[2] shows a head and body (this happens when the player misses two
letters), and so on until HANGMANPICS[6] when the full hangman is shown and the player
loses.
The number of letters in missedLetters will tell us how many incorrect guesses the
player has made. We can call len(missedLetters) to find out this number. This
number can also be used as the index to the HANGMANPICS list, which will allow us to print
the correct board for the number of incorrect guesses. So, if missedLetters is 'aetr'
then len('aetr') will return 4 and we will display the string HANGMANPICS[4] . This
is what HANGMANPICS[len(missedLetters)] evaluates to. This line shows the
correct hangman board to the player.
70. print('Missed letters:', end=' ')
71. for letter in missedLetters:
72. print(letter, end=' ')
73. print()
Line 71 is a new type of loop, called a for loop. A for loop is kind of like a while
loop. Line 72 is the entire body of the for loop. The range() function is often used with
for loops. I will explain both in the next two sections.
Remember that the keyword argument end=' ' uses only one = sign, not two.
Search WWH ::




Custom Search