This challenge consists in creating the hangman game from Python code.
First, we’ll make the different hangman drawings with text strings.
drawings list we will place the text strings that represent
the hangman drawings.
We will solve the challenge progressively.
Create two variables, one called “correct” and the other “incorrect”. Both should be assigned to an empty string.
Do you remember the lesson on APIs? Let’s apply what we learned from that lesson.
To play hangman we need words to guess. In this case we will retrieve those words from the University Domains API.
These words will be world cities.
requests library to access the University Domains API. The url is the following
choose function that will randomly choose a city within the cities of the
cities list. This city will be returned by the function. It should be noted that the name of each city
is given in English.
Let’s define another function to print the hangman.
print_hangman function prints the corresponding hangman drawing according to
the number of correct and incorrect letters so far. It takes a single parameter
p_aleatoria which represents the word to guess.
It’s time to create the main function of our program, which asks the user for a letter to guess.
guess function. It receives a string as a parameter (
letters) with all the letters already
tested (correct + incorrect). It returns a lowercase letter that has not been tested before.
If the user enters more than one letter or another special character, a message should be printed
alerting the user of their error. For example:
This function will have a loop that will make sure that all the data is coherent and will only pass
to the main program the lowercase letter that has not been already tested. Save what the user enters in the
x. Note: The function will be run once and will ask for a letter to verify if the unit tests pass.
Let’s make it possible for the user to decide whether or not they want to play again.
play_again function that asks the user if they want to play again. The answer should be s or n (S/N).
Regardless of whether the user enters the response in uppercase or lowercase, the program should transform it to lowercase.
The function returns
False depending on the response. Note: The function will be run twice to check if it passes the unit tests.
In the console, you will see instructions on what to enter for each test.
Now develop the
win function. It takes two parameters:
p_aleatoria, which represents the word to be guessed, and
letras_adivinadas. It should return
True if all the letters of
p_aleatoria are in the
letras_adivinadas string. Otherwise, it returns False.
You have already defined all the necessary functions and variables for the program. If you have made it this far, you should have completed everything and passed all the unit tests. If so, you can run the following program to test your game. You have 5 minutes to play.