Utilize Python and Rich to Create a Wordle Clone
Would you like to create a game that can be as addictive as a word search puzzle? In this article, we will discuss how to develop a Wordle clone using Python and Rich. Wordle is a guessing game where players try to guess the hidden word by providing feedback based on their previous guesses. With the help of Python and Rich, it is possible to create such a game that can provide hours of entertainment.
What is Rich?
Rich is a Python library that makes it simple and easy to add sophisticated formatting to your terminal. It allows developers to utilize features like colors, Unicode, emojis, and tables to create text that appears aesthetically pleasing. This elegant library is an excellent tool for visualizing results, logging output, or formatting messages.
What is Wordle?
Nate Parrott created Wordle in 2020. This game has become popular because it is straightforward, challenging, and addictive. The hidden word is a five-letter word chosen randomly by the computer. You have six attempts to correctly guess the word by supplying your response. With every incorrect guess, the game will provide feedback to help you in future guesses. The game will end if you try to guess for the seventh time.
How to Create a Wordle Clone?
Here we will discuss how to recreate the Wordle puzzle from scratch. We will utilize two libraries: Rich and Random. Python’s Random module will help in generating random words for the player to guess. This is done by reading a file that contains a list of over 65000 valid English words, one per line. The word is then generated by selecting a line at random.
Steps
Set up the Environment
To start creating the game, we will create an environment using the following command in bash:
python3 -m venv wordle_clone
Then activate the virtual environment:
source wordle_clone/bin/activate
We can see that the virtual environment has been activated by checking the command prompt that should appear like the following:
(wordle_clone) $
Install Dependencies
In the next phase, we will install Rich as a terminal-based library that provides a number of options to improve the output format. It is installable via pip. We can install it with the following command:
pip install rich
Import Libraries
We start by importing the libraries required for this project: Rich and Random.
from rich.console import Console
from rich.table import Table
import random
Generate Word
Next, we create a function that generates a random word from a list of English words. Here we open the file that contains over 65000 English words, then pick a random line from the file, and return it as the function’s value:
def generate_word():
with open("words_alpha.txt") as word_file:
valid_words = list(word_file)
word_choice = random.choice(valid_words).strip()
return word_choice.lower()
Did You Know?
The word_choice is converted to lowercase since the game only uses lowercase letters.
Create Feedback Function
Next, we will create a feedback function that checks each guess against the word choices and determines the correct responses to provide feedback to the player. Here is the function that produces the feedback.
def check_guess(guess, secret_word):
response = []
for i in range(len(guess)):
if guess[i] == secret_word[i]:
response.append('O')
elif guess[i] in secret_word:
response.append('o')
else:
response.append('x')
return response
The feedback function iterates over the characters for each guess and provides feedback based on the match. ‘O’ shows that the character in that position is right, ‘o’ shows that the character is right but in the wrong position, and ‘x’ shows that it isn’t in the chosen word.
Create a Game Loop
You will create a game loop that allows the player to guess the word while also providing feedback to aid future guesses. The player is given up to six attempts before the game ends.
MAX_GUESSES = 6
secret_word = generate_word()
guesses = []
console = Console()
table = Table(title=f"[red]Wordle: Can You Guess the {len(secret_word)} Letter Word?")
table.add_column("Guesses", justify="right")
table.add_column("Feedback", justify="right")
for attempt in range(MAX_GUESSES):
guess = input("Enter your guess?")
if guess == secret_word:
console.print(f"[green]You win after {attempt} guesses!!")
break
guesses.append(guess)
feedback = check_guess(guess, secret_word)
table.add_row(guess, (" ").join(feedback))
console.print(table)
if guess != secret_word:
console.print(f"[red]You lost! The word was {secret_word}")
In this loop, the player enters a guess which is being added to the list of guesses. The check_guess() function is then called to validate guess accuracy. A table is created to show the player each guess and its corresponding feedback. The game loop ends when the player correctly guesses the word, or after six attempts.
Conclusion
In conclusion, employing the power of Rich and Random libraries coupled with Python, one can easily create an entertaining Wordle clone that can be as addictive as the original game. With Rich’s sophisticated formatting options, it is possible to improve the presentation of output results. Python allows you to do this easily without breaking a sweat. You could package your Python code into an executable and share it with friends and family to see if they can guess the words.
References
NateParrott. (2020). Wordle Classic. New York Times. Retrieved from https://www.nytimes.com/interactive/2021/04/26/briefing/25-wordle-questions.html.
Jxmorris12. (2021). jxmorris12/word-guessing-game. Github Repository. Retrieved from https://github.com/Jxmorris12/word-guessing-game.