Skip to content

Unleashing the Power of the Built-in Wordle Game

[

Build a Wordle Clone With Python and Rich

by Geir Arne Hjelle

In this tutorial, you will learn how to build your own Wordle clone for the terminal using Python and the Rich library. Wordle is a popular word-guessing game created by Josh Wardle. You will create a command-line application that allows you to play the game and uses the Rich library to enhance the user interface.

Table of Contents

Demo: Your Python Wordle Clone

In this Wordle clone, you will have six attempts to guess a secret five-letter word. After each guess, you will receive feedback about which letters are correctly placed, which are misplaced, and which are wrong. The game will be played in the terminal.

Project Overview

This tutorial will guide you through the process of building a Python Wordle clone. You will start with a simple prototype and gradually develop it into a polished game. Throughout the tutorial, you will learn how to read and validate user input, create an attractive user interface using the Rich library, organize your code into functions, and provide actionable feedback to the users.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming. Familiarity with command-line applications and the Rich library will also be helpful.

Step 1: Guess a Word

In this step, you will implement the core functionality of the Wordle clone—guessing a word. You will collect user information using the input() function, use loops to avoid repetitive code, and check the letters using sets.

Get User Information With input()

The input() function allows you to collect user input in the terminal. You can use it to prompt the user for their guess in the Wordle game.

word = input("Enter your guess: ")

Use Loops to Avoid Repetitive Code

To provide the user with multiple chances to guess the word, you can use loops to repeat the guessing process. You can use a while loop to continue asking for guesses until the user either guesses the correct word or exhausts all their attempts.

guess_count = 0
max_attempts = 6
while guess_count < max_attempts:
word = input("Enter your guess: ")
# Check the guess and provide feedback
guess_count += 1

Check Letters With Sets

To determine which letters are correctly placed, which are misplaced, and which are wrong, you can use sets. By comparing the sets of the secret word and the guessed word, you can identify the correct and wrong letters.

secret_word = "apple"
guess = "apricot"
correct_letters = set(secret_word) & set(guess)
wrong_letters = set(guess) - set(secret_word)

Step 2: Use a Word List

In this step, you will add a word list to the Wordle clone. You will learn how to create a word list manually, choose a random word from a word list, and convert a text into a list of words.

Create a Word List Manually

You can create a word list manually by storing a collection of words as elements in a list.

word_list = ["apple", "banana", "orange"]

Choose a Random Word From a Word List

To provide variety in the game, you can choose a random word from the word list each time a new game is started. The random.choice() function can be used to select a random element from a list.

import random
random_word = random.choice(word_list)

Convert a Text Into a List of Words

To convert a block of text into a list of words, you can use the split() method of strings. This method splits the text into a list of words based on whitespace.

text = "Hello world! How are you?"
word_list = text.split()

Step 3: Organize Your Code With Functions

In this step, you will organize your code into functions to make it more modular and maintainable. You will set up a main loop, create supporting functions, and test your code.

Set Up Your Main Loop

To structure the game, you can set up a main loop that controls the flow of the game. This loop will continue running until the game is over.

def play_game():
# Game logic here
while True:
play_game()
play_again = input("Play again? (y/n): ")
if play_again.lower() != "y":
break

Create Supporting Functions

Supporting functions can be used to encapsulate smaller pieces of functionality. For example, you can create a function to check the correctness of a guess.

def check_guess(secret_word, guess):
correct_letters = set(secret_word) & set(guess)
wrong_letters = set(guess) - set(secret_word)
return correct_letters, wrong_letters

Test Your Code

To ensure that your code is functioning as expected, you can write test cases for each function and verify their outputs.

def test_check_guess():
secret_word = "apple"
guess = "apricot"
correct_letters, wrong_letters = check_guess(secret_word, guess)
assert correct_letters == {"a", "p"}
assert wrong_letters == {"r", "i", "c", "o", "t"}

Step 4: Style Your Game With Rich

In this step, you will use the Rich library to style your Wordle game in the terminal. You will learn how to use the Rich console printer, keep track of previous guesses, and add color to them.

Get to Know the Rich Console Printer

The Rich library provides a variety of console printers that allow you to style and format text in the terminal. You can use these printers to enhance the appearance of your Wordle game.

from rich.console import Console
console = Console()
console.print("Hello, World!", style="bold")

Keep Track of Previous Guesses and Color Them

To provide a visual representation of previous guesses, you can color the letters in the guessed word based on their correctness. For example, you can use green for correctly placed letters and red for wrongly placed letters.

from rich.color import Color
guess = "apricot"
secret_word = "apple"
colors = []
for letter in guess:
if letter in secret_word:
colors.append(Color.green)
else:
colors.append(Color.red)
console.print(guess, style=colors)

Wrap Up the Game in Style

To enhance the overall appearance of the game, you can use the Rich library to format and style the user interface. You can add banners, headers, and other formatting elements to make the game visually appealing.

console.rule("[bold]Welcome to Wordle[/bold]")
console.print("[green]Correctly placed[/green]")
console.print("[red]Wrongly placed[/red]")

Step 5: Add Validation and User Feedback

In this step, you will add validation and user feedback to your Wordle game. You will make sure that the word list is not empty, decide which words to accept, and validate the words that the user guesses.

Make Sure the Word List Isn’t Empty

Before starting a game, you can check if the word list is empty and handle this situation gracefully.

if not word_list:
console.print("No words found in the word list.")
return

Think About Which Words to Accept

To make the game more challenging, you can exclude certain types of words from being included in the word list. For example, you can choose to exclude proper nouns or words with repeating letters.

Validate the Words That the User Guesses

To ensure that the user guesses valid words, you can validate the guesses against certain criteria. For example, you can check the length of the word and verify that it is composed of valid letters.

def validate_guess(word):
if len(word) != 5:
console.print("The word should be 5 letters long.")
return False
if not word.isalpha():
console.print("Only alphabetic characters are allowed.")
return False
return True

Step 6: Clean Up the Game and Your Code

In this final step, you will clean up your Wordle game and your code. You will use constants to name your concepts, add an overview of used letters, and ensure that the game exits cleanly.

Use Constants to Name Your Concepts

To make your code more readable and maintainable, you can use constants to name concepts such as the maximum number of attempts.

MAX_ATTEMPTS = 6

Add an Overview of Used Letters

To help the player keep track of the letters they have already used, you can add an overview that displays the used letters.

used_letters = set()
def play_game():
# Game logic here
console.print(f"Used letters: {' '.join(sorted(used_letters))}")

Exit the Game Cleanly

To ensure that the game exits cleanly when the player chooses to quit, you can add an exit message and perform any necessary cleanup operations.

def exit_game():
console.print("Thanks for playing Wordle!")
cleanup_operations()
atexit.register(exit_game)

Conclusion

In this tutorial, you learned how to build a Wordle clone for the terminal using Python and the Rich library. You implemented the core game logic, organized your code into functions, styled your game with Rich, added validation and user feedback, and cleaned up your code. By following the step-by-step instructions and executing the sample codes, you now have a working Wordle clone that you can play in the terminal.

Next Steps

Now that you have built a Wordle clone, you can continue to enhance the game by adding more features and improving the user experience. You can consider implementing a scoring system, adding different difficulty levels, or incorporating a timer. The possibilities are endless, and you can continue to explore and improve your game-building skills with Python.