Use a Word List
00:00 Use a Word List. In this part of the course, you won’t change the functionality of your game, but you’ll make it more fun and replayable by adding a word list. So far, the secret word is always the same. That is about to change.
00:15 To do this, you’ll first create a small word list manually and integrate it into the game. Then you’ll explore how to turn any text into a word list. Your word list will be a plain text file containing one word per line.
This follows a long tradition on Unix systems where a file named
words is used by spell checkers and similar applications. To get started, create a new file you call
wordlist.txt with the content seen on-screen.
Before creating the better word list, you’ll see how you can read the list of words into your program. Python’s
pathlib module is great for working with files and reading them into memory. You can try it out in the REPL.
.strip() to remove any extra lines at the end of the file and
.split() to convert the file into a list of words. To avoid having to care about lower and uppercase, you convert all the words to uppercase.
02:36 As you can see, sometimes randomness gives you the same answer twice in a row. Your results will likely be different from the one seen on-screen, but it’s time to add word list functionality to the Wordle clone.
Edit the game as seen on-screen. First, the constant
WORD is removed, as you’ll be replacing it with the code you’re about to enter. You import
random, as they’ll be used as you saw previously in the REPL.
It’s not common to use the
else clause with
for, but it’s quite powerful in the right situation. The code inside the
else will only run if the
for loop terminates naturally, but it won’t run if that isn’t the case—here, if
break stops the loop. In practice, this means that the secret word is printed if all the guesses are different from
word. While you’re developing your game, you’ll run it many times. To test your code effectively, you may want to cheat and know the secret word up front. While testing your code, add the line seen on-screen just before calling
input(), and this will print the secret word to the console.
Become a Member to join the conversation.