The Hangman
Rules
The computer chooses a random word from a file, a word of up to eight letters. The player tries to find the letters composing the word. At each turn, he chooses a letter. If the letter is in the word, the computer displays the word with the letters already found. Those that are not yet found are replaced by underscore _
. The player has 8 chances. After that, he lost.
You will also ask the player to give his name at the beginning of the game and give him a score. The player's score is simple to calculate, it is the number of moves remaining. If, for example, I still have three chances when I find the word, I gain three points.
Technical side
We will divide our program into at least four different functions:
getWord()
addLetter(letter,userWord,word)
displayWord(word)
mainGame()
Feel free to divide those functions into smaller functions. It is your program, you do it the way you want, I am just explaining one way to do it. It is very important to think before starting, take a piece of paper and a pen if it can help you to organize your thoughts. Now it is your turn, Good luck !
Help
- Start with the
getWord()
function. Try to randomly select one word from the filewords.txt
and print it to make sure it works. - Then start your
mainGame()
function, initialize all your variables (includingword
anduserWord
) and make sure that based on the length of the randomly selected word, userWord has the correct number of “_”. (print word and userWord to be sure). - We can now start the actual code of the mainGame function by starting the while loop, asking a letter to the user, add that letter in the alreadyTried if it hasn’t been tried yet and check if the letter is in the word or not. Don’t forget to print specific message to make sure that your code works.
- We can then create the addLetter(letter,userWord,word) function. We have to go through the word, count each time the letter given by the user appears and replace the _ in userWord at the correct positon by the letter. Make sure it works before going to the next step.
- We can update the mainGame function by calling the addLetter function each time the user found a new letter.
- Time to finish the game. For that, once you are outside of the loop, check if the user won or lost and print the appropriate message.
- For the moment, when you print your userWord list, it doesn’t look very nice. It is time to code the displayWord function so it looks nicer. It should go from:
- Make sure you understand everything and that everything is working. After that you can improve your code as much as you can and add some new features.