Creating Supporting Functions
That’s a bad situation because if you can’t run your function, then you can’t test it to make sure that it does what you expect it to do. Now you’ll implement these three functions, mostly by moving existing code that you wrote earlier on. Start by considering
00:28 What should the function do? You can use these requirements as a guide when implementing it: choose a random word from an existing word list and ensure that the word is five letters long. When implementing a new function, an important decision is which parameters the function should accept.
The original code is now pasted back in and indented appropriately. There are a couple of changes to make to the code. Firstly, changing the reference to the
WORDLIST constant to the new
and secondly, returning the random choice rather than assigning it to the variable
word. As earlier, you read a word list from a file and then filter the list so that you are left with words at the correct length.
The next function you need to implement is
show_guess(). Move the code into the following function, firstly by finding it in the original code, selecting it, and cutting it. Then move to the bottom of the file, start the function definition, and paste the code in, making sure it’s indented appropriately.
02:45 This new function first categorizes the letters in the user’s guess into correct, misplaced, and wrong letters as earlier. Then these are printed to the console. The code is the same as before, just reimplemented as a function.
The last function that you’ll implement for now is
game_over(). At the moment, it might be overkill to refactor this into a separate function, as it will only print a message to the screen. But by dividing your code like this, you are naming that particular part of the code, clearly indicating what it’s doing. You can also expand on this later on if needed.
Become a Member to join the conversation.