Game Development Reference
In-Depth Information
9 - Hangman
We have added two new multi-line strings to the HANGMANPICS list, one with the
hangman's left ear drawn, and the other with both ears drawn. Because our program will tell
the player they have lost when the number of guesses is the same as the number of strings
in HANGMANPICS (minus one), this is the only change we need to make.
We can also change the list of words by changing the words on line 59. Instead of
animals, we could have colors:
59. words = 'red orange yellow green blue indigo violet white
black brown'.split()
60. Or shapes:
61. words = 'square triangle rectangle circle ellipse rhombus
trapazoid chevron pentagon hexagon septagon
octogon'.split()
62. Or fruits:
63. words = 'apple orange lemon lime pear watermelon grape
grapefruit cherry banana cantalope mango strawberry
tomato'.split()
Dictionaries
With some modification, we can change our code so that our Hangman game can use all
of these words as separate sets. We can tell the player which set the secret word is from
(like "animal", "color", "shape", or "fruit"). This way, the player isn't guessing animals all
the time.
To make this change, we will introduce a new data type called a dictionary . A
dictionary is a collection of other values much like a list, but instead of accessing the items
in the dictionary with an integer index, you access them with an index of any data type (but
most often strings).
Try typing the following into the shell:
>>> stuff = {'hello':'Hello there, how are you?',
'chat':'How is the weather?', 'goodbye':'It was
nice talking to you!'}
>>>
Those are curly braces { and }. On the keyboard they are on the same key as the square
braces [ and ]. We use curly braces to type out a dictionary value in Python. The values in
between them are key-value pairs . The keys are the things on the left of the colon and the
values are on the right of the colon. You can access the values (which are like items in lists)
in the dictionary by using the key (which are like indexes in lists). Try typing into the shell
stuff['hello'] and stuff['chat'] and stuff['goodbye'] :
Search WWH ::




Custom Search