In this exercise, we will finish building Hangman. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game.
In Part 1, we loaded a random word list and picked a word from it. In Part 2, we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses.
Copy your code from Parts 1 and 2 into a new file as a starting point. Now add the following features:
"You have 4 incorrect guesses left", display some picture art for the Hangman. This is challenging - do the other parts of the exercise first!
Your solution will be a lot cleaner if you make use of functions to help you!
We already discussed sets in Exercise 14, but here is a brief summary:
The only “gotcha” is that you cannot have a set of lists - each element in the set must be hashable. Basically this means you can’t have elements that can change in a set, so the objects in your set should be integers or strings. The reason and distinction are not super important; the most important thing to know is that sets are most useful when you want a set of integers or strings, rather than a set of lists.
To add elements to a set, use the
The advantage of sets is that all the elements in it are unique. This makes it very easy to check whether an element is already in the set. All you need to do is ask
elem in my_set:
And this check is very fast - much faster than doing the same
in check with a list. (The reason it is fast is a concept called hashing, which you can read about in detail in this StackOverflow post.)
We briefly discussed some tips on working with lots of code in Exercise 29, and I’ll add a few more here:
If you have any other code organization tips, leave them in the comments, would love to get a good discussion going.
Forgot how to submit exercises?comments powered by Disqus