CentraleSupélec — Département informatique
Plateau de Moulon
3 rue Joliot-Curie
F-91192 Gif-sur-Yvette cedex
1CC1000 - Information Systems and Programming - Test-Driven Development

The goal of this lab is to discover and practise Test-Driven Development (TDD) by creating your own version of the famous Wordle word game in Python.

How to play Wordle

The goal of Wordle is to guess a hidden word in a limited number of attempts.

  1. The game chooses a hidden word of a specified length, usually five letters.
  2. The player has a limited number of guesses to find the word, usually six.
  3. Each guess must contain the correct number of letters.
  4. After each guess:
  • A letter is marked correct if it appears in the same position in the hidden word.
  • A letter is marked present if it appears in the hidden word, but in a different position.
  • A letter is marked absent if it does not appear in the hidden word.

5. The player wins if they guess the hidden word before using all their attempts.

6. If the player uses all their attempts without guessing the word, the game ends and the hidden word is revealed.

The dictionary contains a limited set of valid words. If the user enters a word that is not in the dictionary, the application informs them, but does not count that attempt. The user can therefore try another valid word without losing an attempt.

The game can use different symbols, colours or other visual indicators to display the result of each guess, depending on whether it is used in the terminal or in a web interface.

Project setup

  • Create a fork of this project in GitLab. You can create a fork using the GitLab interface.
  • Open a terminal on your computer (Windows users: use GitBash).
  • Clone the forked project into a folder on your computer.
  • Open the project in Visual Studio Code (VSC) using the command code . (if the command code . does not work, open the folder using the VSC interface).
  • Open a terminal in VSC (Windows users: select GitBash).
  • Create a virtual environment by entering the following command in the integrated VSC terminal.

Windows users: py -m venv .venv

Linux/macOS users: python3 -m venv .venv

  • Activate the virtual environment using the following command:

Windows users: source .venv/Scripts/activate

Linux/macOS users: source .venv/bin/activate

  • Update pip with the following command:

pip install --upgrade pip

Windows users. If the command fails, try: python -m pip install --upgrade pip

  • Install the dependencies with the following command:

pip install -r requirements.txt

Project structure

In addition to the Git-related files and the requirements.txt file you already know, the project is organized into the following folders:

  • assets: this folder contains resources used by the application, such as dictionaries used to choose secret words and configuration files that let you customize the program. It can also contain other static resources, such as logos or images.
  • src: this folder contains all the project's source code. You will complete the existing implementation and add new code files as needed. Some files are already provided and will be introduced throughout the exercise.
  • tests: this folder contains the tests your code must pass to be considered correct. Throughout the project, you will add and run tests to check that your implementation behaves as expected.

Model-View-Controller

As the Wordle application grows, it is important to organize the code so that it is easier to understand, test and modify. To do this, the project follows the Model-View-Controller (MVC) design pattern.

MVC separates an application into three main components:

  • Model: the model contains the application's data and core logic. In this project, it represents the state of the Wordle game and enforces its rules. For example, it can store the secret word, track the player's guesses, determine whether a guess is valid and generate the result associated with each guess. The model must not depend on how the game is presented to the user.
  • View: the view presents information to the user and collects their input. In this project, you will implement a web interface with Flask. The view should focus on displaying information rather than on game logic.
  • Controller: the controller acts as an intermediary between the model and the view. It receives the user's input through the view, asks the model to perform the appropriate operations and updates the view with the results. It therefore coordinates interactions between the user interface and the game logic.

This separation of responsibilities has several advantages. Since the game logic is independent of the user interface, the same model can be used with different views, such as a terminal application or a web application. The code is also easier to test because the core game logic can be tested independently of the interface.

In the src folder, you will find three subfolders corresponding to the three MVC components: model, view and controller. Each of these subfolders can also contain an exceptions folder with code that defines and handles errors specific to the corresponding MVC component.

We will begin the implementation with the model.

The model

Except for a very simple application, the model code should not be contained in a single file. To determine which files we need, let's think about the elements required to implement the rules of the game.

Question. What components are needed to implement the rules of the game?


SUGGESTED ANSWER

Here are the main elements to consider:

  • The state of the game: this includes the player's guesses, the number of attempts remaining, the secret word, the required length of guesses and whether the player has won or lost.
  • Guess validation and evaluation: for each guess, the program must determine whether each letter is in the correct position, appears in the secret word in another position, or does not appear in it at all.
  • The dictionary: the program must load a list of valid words from a file, check whether a given word is in the dictionary and randomly choose a secret word.

As established in the previous question, implementing Wordle requires several components. The game logic should therefore be distributed across several modules rather than grouped in a single file. We will use object-oriented programming to implement these modules.

The Wordle dictionary

The dictionaries used by the game are provided as text files in the assets folder.

The following features are needed:

  • Load a dictionary from a file. The words read from the file will be stored in memory in an appropriate data structure.
  • Add a word to the dictionary.
  • Check whether a word is in the dictionary. This operation may be performed many times during a game, so it must be efficient. Which of the Python data structures you have studied would be best for storing the words in memory and efficiently checking whether a given word is present?
  • Get the number of words in the dictionary.
  • Randomly choose a word of a given length from the dictionary.

Create a new branch

Since we are adding a new feature to the project, it is recommended that you create a dedicated branch. The following command creates a branch named dictionary and switches to it:

git switch -c dictionary

Activity. In the src/model directory, open the dictionary.py file. With your instructor, review the main object-oriented programming concepts that will be needed to complete this lab.

NB. If you exeucute python3 -m pytest tests/model/test_dictionary.py (Linux/MacOS) or python -m pytest tests/model/test_dictionary.py you'll get errors because we haven't implemented anything yet.

Test-Driven Development

Instead of immediately implementing the methods of the Dictionary class, we will first define their expected behaviour using tests. For each operation, we will write one or more tests describing the expected result. We will then implement the corresponding features so that all the tests pass.

In this project, we will use pytest to automatically test the different components of the application. pytest is a Python testing framework that discovers and runs test methods, then reports whether they pass or fail.

Activity. In the tests/model directory, open the test_dictionary.py file. With your instructor, discuss the main concepts related to Test-Driven Development and pytest.


SUGGESTED ANSWER

To illustrate how pytest works, consider a simple program that provides a function for calculating the area of a rectangle:

def rectangle_area(width, height):
    return width * height

We can create a test class to check that this function behaves as expected:

class TestRectangleArea:

    def test_area_of_rectangle(self):
        assert rectangle_area(5, 3) == 15

    def test_area_of_square(self):
        assert rectangle_area(4, 4) == 16

The TestRectangleArea class groups all tests related to the rectangle_area() function. Each method whose name begins with test_ represents an individual test.

When pytest runs the tests, it discovers the TestRectangleArea class and runs its two test methods.

The assert statement is at the heart of our tests. It lets us specify the expected result of an operation.

For example:

assert rectangle_area(5, 3) == 15

This assertion indicates that we expect rectangle_area(5, 3) to return the value 15. If it does, the assertion succeeds and the test passes. If the function returns another value, the assertion fails and pytest reports the test failure.

Assertions can also check whether a condition is true:

assert 10 > 5

or false:

assert not 10 < 5

They can compare values:

assert "hello".upper() == "HELLO"
assert len([1, 2, 3]) == 3

They can also check whether an element belongs to a collection:

assert "Python" in ["Python", "Java", "C++"]

In all these cases, the expression following assert must evaluate to True for the test to pass.


Exercise 1. In the TestDictionary class, complete the test_add_word_with_accents_empty_dict method to check that adding an accented word to an empty dictionary stores it without accents. For example, the word "élève" should be stored as "eleve".


SUGGESTED ANSWER

def test_add_word_with_accents_empty_dict(self):
        d = Dictionary()
	d.add_word("élément")
	assert len(d._words) == 1
	assert "element" in d._words


Using fixtures

In the previous exercise, we checked that a word could be added correctly to an empty dictionary. We must now check that the Dictionary class also behaves correctly when words are added to a dictionary that already contains entries.

We need two tests in particular:

  • one to check that a new word is correctly added to a non-empty dictionary;
  • another to check that a word already present is not added a second time.

Both tests require the same setup: a dictionary that has already been initialized and contains one or more words. Repeating this code in each test would make the tests unnecessarily redundant and harder to maintain.

Fortunately, pytest provides a mechanism called a fixture that lets us define reusable setup code. A fixture can create and initialize the objects or data needed by one or more tests, allowing each test to focus on the behaviour it needs to check.

Exercise 2. Complete the test_dict() method of the TestDictionary class.

This method must:

  1. Create a new Dictionary object.
  2. Add the following words to the dictionary: ["hello", "World", "wordlet", " SecRet ", "élément"].
  3. Return the initialized dictionary.

👉 The method is decorated with @pytest.fixture() to make it a pytest fixture.


SUGGESTED ANSWER

import pytest

@pytest.fixture()
def test_dict(self):
	d = Dictionary()
	for word in ["hello", "World", "wordlet", " SecRet ", "élément"]:
		d.add_word(word)
	return d

Exercise 3. Complete the test_add_word and test_add_word_duplicate methods in the TestDictionary class:

  • the first should check that a word not yet in the dictionary is correctly added;
  • the second should check that a word already in the dictionary is not added a second time.

Both test methods must receive test_dict as an argument. By specifying the fixture name as a parameter, pytest will automatically run test_dict() and pass the resulting dictionary to the test method.


SUGGESTED ANSWER

Note that here we access private instance attributes of the Dictionary class directly. This is not a problem in the context of tests.

def test_add_word(self, test_dict):
        before_add_len = len(test_dict._words)
        test_dict.add_word("custom")

        assert "custom" in test_dict._words
        assert len(test_dict._words) == before_add_len + 1

def test_add_word_duplicate(self, test_dict):
        before_add_len = len(test_dict._words)
        test_dict.add_word("SECRET ")

        assert len(test_dict._words) == before_add_len

All the other tests in the test_dictionary.py class are already implemented.

Create a commit

Since we have completed a task (writing the tests), it is time to create a new commit in our local repository.

We can now complete the implementation of the methods in the Dictionary class.

The Dictionary class

The Dictionary class provides several methods for adding a word to the dictionary, checking whether a word is present, finding out how many words it contains and selecting a word at random.

The class constructor is already implemented. It initializes the _words instance variable, which contains the dictionary words as a set (type set).

We will now implement these methods.

Add a word to the dictionary

We must ensure that all words are stored in the dictionary in a consistent format. We will therefore first implement helper methods that convert a word to lowercase and remove its accents. We can then use them in the add method.

About UNICODE normalization

When manipulating text in Python, two strings that look identical to a user may actually have different internal representations. For example, the character é can be represented by a single Unicode character (U+00E9) or by two characters: e (U+0065), followed by a combining acute accent (U+0301). Unicode normalization converts different representations of the same text into a consistent form. Two common normalization forms are NFC (Normalization Form C) and NFD (Normalization Form D). NFC generally combines characters and their diacritical marks into a single precomposed character when possible, while NFD decomposes characters into base characters and diacritical marks. For example, é is represented by a single character in NFC, whereas NFD represents it as e followed by a combining acute accent. Normalization therefore makes it possible to process visually identical strings consistently, even if they come from different Unicode representations.

In our Wordle implementation, we want all words stored in memory to have a consistent representation without accents. To do this, we can normalize words to NFD, remove combining characters and keep only the base characters.

In Python, we perform NFD normalization with the following instructions:

import unicodedata

word = "café"
normalized = unicodedata.normalize("NFD", word)

We can remove combining characters as follows:

normalized = ''.join(
    char for char in unicodedata.normalize("NFD", word)
    if not unicodedata.combining(char)
)

The resulting value is cafe.

Note that normalization and accent removal are related but distinct operations: NFD decomposes characters, while the additional filtering removes combining diacritical marks.

Exercise 4. Complete the _remove_accents() method of the Dictionary class. It must take a word as an argument and return the word without any accents.


SUGGESTED ANSWER

Note that this is a static method.

import unicodedata

@staticmethod
def _remove_accents(word: str)->str:
	return  ''.join(
		char for char in unicodedata.normalize("NFD", word)
		if not unicodedata.combining(char)
	)	

Exercise 5. Complete the _normalize_word() method of the Dictionary class. This method must take a word as input and return its normalized form by:

  • removing accents using the _remove_accents() method defined above;
  • removing spaces at the beginning and end;
  • converting all letters to lowercase.

SUGGESTED ANSWER

@staticmethod
def _normalize_word(word: str)->str:
	return Dictionary._remove_accents(word).strip().lower()

Exercise 6. Complete the add_word() method of the Dictionary class to add a new word to the dictionary. Before storing it, make sure to normalize it using the methods defined above.

Run the tests after implementing the method. Fix the code if any tests fail.


SUGGESTED ANSWER

Note that we have broken the task of adding a word to the dictionary into several functions; each function handles a specific aspect of the operation (accent removal, word normalization and addition).

def add_word(self, word: str)->None:
	self._words.add(Dictionary._normalize_word(word))

Activity. Run the tests for the add_word method using the command appropriate for your operating system:

(Windows) python -m pytest -k test_add_word

(macOS or Linux) python3 -m pytest -k test_add_word

This command runs only the tests whose names contain the string test_add_word.

Analyze the output to identify the tests that failed, understand the cause of the errors and determine what corrections are needed.

Load the dictionary from a file

The words in a dictionary are stored in a text file. We therefore need to read the contents of this file and add each word to an instance of the Dictionary class.

This is the purpose of the load_from_file() method of the Dictionary class.

Guidance: in Python, you can use the open() function to open a file and read its contents. The with statement ensures that the file is properly closed after use. Also remember to specify the file encoding using the encoding parameter. For example, encoding="utf-8" makes it possible to read accented characters correctly when the file is saved with this encoding.

with open("words.txt", "r", encoding="utf-8") as file:
    for line in file:
        word = line.strip()
        print(word)

Exercise 7. Implement the load_from_file method of the Dictionary class.

Test the method with the following command (this command runs only the test_load_from_file test).

(Windows) python -m pytest tests/model/test_dictionary.py::TestDictionary::test_load_from_file

(Linux/macOS) python3 -m pytest tests/model/test_dictionary.py::TestDictionary::test_load_from_file


SUGGESTED ANSWER


def load_from_file(self, file: Path)->None:
    with open(file, mode='r', encoding='utf-8') as f:
        for line in f:
            self.add_word(line)


Calculate the size of the dictionary

Exercise 8. Implement the size method of the Dictionary class, which returns the number of words stored in the dictionary.

Test the method with the following command (this command runs only the test_load_from_file test).

(Windows) python -m pytest tests/model/test_dictionary.py::TestDictionary::test_size

(Linux/macOS) python3 -m pytest tests/model/test_dictionary.py::TestDictionary::test_size


SUGGESTED ANSWER


def size(self)->int:
        return len(self._words)



Check whether a word is present

Exercise 9. Implement the has_word method of the Dictionary class, which returns True if the given word is present in the dictionary and False otherwise. The method must normalize the word before looking it up in the dictionary.

Test the method with the following command:

(Windows) python -m pytest -k test_is_in_dictionary

(Linux/macOS) python3 -m pytest -k test_is_in_dictionary

This command runs only the tests whose names contain the string test_is_in_dictionary.


SUGGESTED ANSWER


def has_word(self, word:str)->bool:
    return Dictionary._normalize_word(word) in self._words


Select a word from the dictionary

At the start of the game, a word is chosen at random from the dictionary.

To do this, you can use the choice function from the random module. Consult its documentation here.

Exercise 10. Implement the select_random_word method of the Dictionary class.

Test the method with the following command:

(Windows) python -m pytest -k test_select_random_word

(Linux/macOS) python3 -m pytest -k test_select_random_word

This command runs only the tests whose names contain the string test_select_random_word.


SUGGESTED ANSWER

import random

def select_random_word(self, word_len:int=5)->str:
    words_with_len = list([word for word in self._words if len(word) == word_len])
    return random.choice(words_with_len)



If all the tests have passed as you developed the code, you have now finished implementing the Dictionary class.

Activity. It is important to run all the tests for the TestDictionary class to check that implementing one method has not introduced a regression in another method.

To do this, run the following command:

(Windows) python -m pytest tests/model/test_dictionary.py::TestDictionary

(Linux/macOS) python3 -m pytest tests/model/test_dictionary.py::TestDictionary

If all the tests pass, your implementation of the Dictionary class is complete. Congratulations!

Commit

It is time to commit your work to the local Git repository.

Error handling

In the previous code, we added a method to the Dictionary class that randomly chooses a word of a given length. However, we neglected the case where the dictionary contains no words of that length. This is an error condition that we must handle carefully using exceptions.

Exceptions

When a program runs, some situations can prevent an operation from completing normally. For example, a program may try to open a file that does not exist, convert an invalid string to a number or access an element outside the bounds of a list. Python uses exceptions to signal and handle these situations.

An exception is an object that represents an error or unusual situation that occurs while a program is running. When an exception is raised, Python interrupts the normal flow of the program and looks for code that can handle it.

Built-in exceptions. Python provides many built-in exception types, such as ValueError, TypeError, FileNotFoundError and IndexError. We can explicitly raise an exception with the raise statement:

age = -1

if age < 0:
    raise ValueError("Age cannot be negative")

It is generally preferable to use a built-in exception when a Python exception type accurately describes the problem. For example, ValueError is appropriate when a function receives a value of the correct type, but that value is invalid.

Catching exceptions. Exceptions can be handled with a try/except statement:

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a valid number.")

If the user enters a value that cannot be converted to an integer, int() raises a ValueError exception. The except block catches the exception and lets the program respond appropriately instead of stopping unexpectedly.

It is important to catch only exceptions that you actually know how to handle. For example, using:

try:
    ...
except Exception:
    ...

indiscriminately can hide programming errors and make debugging considerably more difficult. As a general rule, it is better to catch a specific exception:

except ValueError:
    ...

Custom exceptions. Sometimes Python's built-in exceptions do not adequately describe an error specific to your application. In that case, we can define a custom exception by creating a class that inherits from Exception (inheritance will be explained later in the course).

For example:

class InvalidWordError(Exception):
    pass

We can then raise this exception when an invalid word is encountered:

if not word:
    raise InvalidWordError("The word cannot be empty.")

And handle it like a built-in exception:

try:
    process_word(word)
except InvalidWordError:
    print("The word is not valid.")

Custom exceptions are particularly useful when an application has error conditions specific to its domain. They let code that uses a class or function distinguish between different types of errors and respond to them appropriately.

Exceptions do not replace validation. Exceptions should signal situations that prevent an operation from completing normally. They should not be used unnecessarily during the ordinary flow of a program.

For example, if a function requires a word to be present in a dictionary and its absence makes the operation invalid, it may be appropriate to raise an exception. In contrast, if checking whether a word is present is a normal operation, a method such as:

dictionary.contains(word)

can simply return True or False.

The important distinction is between expected results and exceptional situations. A Boolean value is often appropriate when both outcomes are normal; an exception is more appropriate when an operation cannot proceed as requested.

In src/model/exceptions, you will find a file named NoWordOfLengthException.py. It defines a custom exception called NoWordOfLengthException. This class contains no additional code; it simply inherits from Python's built-in Exception class.

Exercise 11. Add a method to the TestDictionary class to check that the NoWordOfLengthException exception is correctly raised when attempting to randomly select a word of a length that is not present in the dictionary.

👉 To test that a function should raise an exception, you can use the pytest.raises() function, as in the following code:

with pytest.raises(ZeroDivisionError):
     res = 3/0


SUGGESTED ANSWER

from src.model.exceptions.NoWordOfLengthException import NoWordOfLengthException

def test_select_random_word_bad_length(self, test_dict):
	word_len=10
	with pytest.raises(NoWordOfLengthException):
		test_dict.select_random_word(word_len=word_len)

Exercise 12. Modify the implementation of the select_random_word method of the Dictionary class so that it raises the NoWordOfLengthException exception when the dictionary contains no words of the requested length.

Run the tests and check that they all pass.


SUGGESTED ANSWER

from src.model.exceptions.NoWordOfLengthException import NoWordOfLengthException

def select_random_word(self, word_len:int=5)->str:
	words_with_len = list([word for word in self._words if len(word) == word_len])
	if len(words_with_len) == 0:
		raise NoWordOfLengthException("No words in dictionary 
                        match the given length")
	return random.choice(words_with_len)


Merge the dictionary branch into the main branch

We have finished implementing the Dictionary class. It is time to merge our dictionary branch into the main branch.

1. Commit the latest changes on the dictionary branch.

2. Switch to the main branch using the following command:

git switch main

3. Merge the dictionary branch into main with the following command:

git merge dictionary

4. Delete the dictionary branch with the following command:

git branch -d dictionary

5. Push the latest commit to GitLab:

git push

👉 If you are working on this project with other developers sharing the same remote repository, your branch should be merged into main through a merge request, as we learned in the previous lab.

Implementing the game

To play a complete game of Wordle, the application must let the user:

  • Start a new game. Each game has its own configuration, including the required length of guesses, the maximum number of attempts to guess the secret word, the secret word and the dictionary from which it is chosen. Some parameters may have default values.
  • Submit a word. The game must accept the player's word, compare it with the secret word and provide a result for each letter.
  • Determine whether the game is over. The application must be able to determine whether the player guessed the secret word and won, or used the maximum number of attempts and lost.

In addition to these operations, the game must track its state throughout execution. This state includes the player's guesses and the evaluation result for each letter in each guess.

In the following sections, you will implement these features, beginning with the game state.

New branch

Create a branch named game-logic and use it to implement the features in the following sections.

Game state

We will now develop a representation of annotated player guesses. The exercises in this section will guide you through designing and implementing this representation, which will let us express the game's feedback on the letters that have been guessed.

We will work in the file src/model/annotated_guess.py.

This file already contains the LetterState enumeration, which represents the different possible states of a letter, as well as the definitions of the AnnotatedLetter and AnnotatedGuess classes.

Your goal is to implement these two classes by completing the exercises below.

Annotated letter

The AnnotatedLetter class represents a letter annotated with one of the states in the LetterState enumeration. Your goal is to implement all the methods in this class.

Exercise 13. Complete the implementation of the AnnotatedLetter class (file src/model/annotated_guess.py) by following the comments in each of its methods.


SUGGESTED ANSWER

class AnnotatedLetter:
    def __init__(self, letter: str, state: LetterState = LetterState.UNKNOWN):
        self._letter = letter
        self._state = state

    @property
    def letter(self):
        return self._letter

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, state: LetterState):
        self._state = state

    def __eq__(self, other_letter):
        return (
            self.letter == other_letter.letter and 
            self.state == other_letter.state
        )

Annotated guess

Now you will complete the code for the AnnotatedGuess class.

Exercise 14. Complete the implementation of the AnnotatedGuess class (file src/model/annotated_guess.py) by following the comments in each of its methods.


SUGGESTED ANSWER


from src.model.exceptions.AnnotationLengthException import AnnotationLengthException

class AnnotatedGuess:
    def __init__(self, guess: str):
        self.guess = guess.lower()


    def annotate_guess(self, secret: str):
        if len(secret) != len(self.guess):
            raise AnnotationLengthException(
                           "Guess and secret must have the same length")

        annotated_guess = [None]*len(self.guess)

        secret = secret.lower()
        letter_occurrences = {letter: secret.count(letter) for letter in secret}

        # Identify the correct letters.
        for pos, letter in enumerate(self.guess):
            if secret[pos] == letter:
                annotated_guess[pos] = AnnotatedLetter(letter, LetterState.CORRECT)
                letter_occurrences[letter] -= 1 

        # Annotate the other letters
        for pos, letter in enumerate(self.guess):
            if annotated_guess[pos] is not None:
                continue

            if letter in secret and letter_occurrences[letter] > 0:
                annotated_guess[pos] = AnnotatedLetter(letter, LetterState.PRESENT)
                letter_occurrences[letter] -= 1
            else:
                annotated_guess[pos] = AnnotatedLetter(letter, LetterState.ABSENT)

        return annotated_guess  

Activity. Test the classes you implemented with the following command:

Windows: python -m pytest tests/model/test_annotated_guess.py::TestAnnotatedGuess

Linux/macOS: python3 -m pytest tests/model/test_annotated_guess.py::TestAnnotatedGuess

Game logic

You will now implement the game logic in the src/model/game.py file.

Exercise 15. Complete the implementation of the Game class by following the comments in each of its methods.

After implementing each method, run the tests for the TestGame class using the command appropriate for your operating system:

Windows: python -m pytest tests/model/test_game.py::TestGame

Linux/macOS: python3 -m pytest tests/model/test_game.py::TestGame

Until the class implementation is complete, it is normal for some tests to pass and others to fail. However, each time you run the tests, check that the tests for the method you just implemented pass.

If you want to run only the tests associated with a method, you will notice that each test method in the tests/model/test_game.py file has a comment indicating which method of the Game class it tests.

Test names follow a naming convention: all tests associated with the same method share a common prefix. For example, tests that check the behaviour of the __init__ method start with test_init.

You can therefore use the -k option of pytest to run only tests whose names contain a given prefix:

Windows: python -m pytest -k test_prefix

Linux/macOS: python3 -m pytest -k test_prefix

Replace test_prefix with the prefix corresponding to the tests you want to run.


SUGGESTED ANSWER

from src.model.dictionary import Dictionary
from src.model.annotated_guess import LetterState, AnnotatedGuess
from src.model.exceptions.WrongSecretLengthException import WrongSecretLengthException
from src.model.exceptions.EmptyDictionaryException import EmptyDictionaryException
from src.model.exceptions.InvalidGuessException import InvalidGuessException
from src.model.exceptions.WrongGuessLengthException import WrongGuessLengthException
from src.model.exceptions.GameFinishedException import GameFinishedException

class Game:

    def __init__( 
        self,
        secret: str, 
        word_length: int, 
        nb_attempts: int, 
        dictionary: Dictionary
    ):
        secret = secret.strip().lower()

        if (len(secret) != word_length):
            raise WrongSecretLengthException(f"Secret length does not match {word_length}")

        if (dictionary.size() == 0):
            raise EmptyDictionaryException("Dictionary cannot be empty")

        self._secret = secret
        self._word_length = word_length
        self._nb_attempts = nb_attempts
        self._dictionary = dictionary

        # Keep the list of the submitted guesses.
        self._submitted_guesses = []

    def remaining_attempts(self):
        return self._nb_attempts - len(self._submitted_guesses)

    def get_guesses(self):
        return [guess for guess in self._submitted_guesses]

    def get_secret(self):
        return self._secret

    def is_won(self):

        # The game cannot be won if there are no guesses.
        if self.remaining_attempts() == self._nb_attempts:
            return False

        # Get the last guess and check if all letters are correct.
        last_guess = self._submitted_guesses[-1]
        return all([letter.state == LetterState.CORRECT for letter in last_guess])

    def is_finished(self):
        return self.is_won() or self.remaining_attempts() == 0

    def submit_guess(self, guess):
        guess = guess.strip().lower()
        if len(guess) != self._word_length:
            raise WrongGuessLengthException(f"Guess length does not match {self._word_length}")

        if not self._dictionary.has_word(guess):
            raise InvalidGuessException(f"Guess '{guess}' is not a valid word")

        if self.is_finished():
            raise GameFinishedException("Cannot submit guess on a finished game.")

        # Annotate the guess.
        annotated_guess = AnnotatedGuess(guess).annotate_guess(self._secret)
        self._submitted_guesses.append(annotated_guess)

Activity.

You can now run all the tests with the following command:

Windows: python -m pytest

Linux/macOS: python3 -m pytest

If all the tests pass, your implementation is correct. Congratulations!

Git

Remember to commit your work, merge the current branch into the main branch and push to the GitLab repository.

The view

You will now complete the application so that you can play Wordle from the terminal using a text-based interface.

The user interface, also called the view, has already been implemented, so you do not need to modify this code. You will find it in the src/view/console_view.py file, which contains the ConsoleView class.

This class provides the methods needed to interact with the player, including entering guesses and displaying the annotations associated with the letters.

The interface uses the Rich library, which enhances terminal output using, among other things, colours and text styles. These visual elements make it easy to distinguish the different states of letters, as in the original Wordle game.

Your goal is now to connect this interface to the game logic you have developed so that the application is fully functional.

The controller

To connect the interface to the game logic, you will now implement the controller, which coordinates the player's interactions with the progress of the game.

You will find the controller code in the src/controller/console_controller.py file. This file defines the ConsoleController class, whose __init__ constructor is already implemented.

The controller retrieves the game's configuration parameters, including the number of allowed attempts, the secret word length, the language and the dictionary to use.

Your goal is now to implement the run() method, which orchestrates a game. It must initialize a new game, start the user interface and then handle interactions with the player until the game ends. During this loop, the controller must retrieve the player's guesses, pass them to the game logic and use the view to display the annotated guesses.

New branch.

You are adding a new feature. Remember to work on a new Git branch.

Exercise 16. Implement the run method of the ConsoleController class by following the comments in the file.


SUGGESTED ANSWER

import configparser
from pathlib import Path

from src.model.dictionary import Dictionary
from src.model.game import Game
from src.model.exceptions.WrongGuessLengthException import WrongGuessLengthException
from src.model.exceptions.InvalidGuessException import InvalidGuessException

from src.view.console_view import ConsoleView

class ConsoleController:
	def __init__(self, config_file: Path):
		config = configparser.ConfigParser()
		config.read(config_file)

		self._word_length = config.getint("game", "word_length")
		self._max_attempts = config.getint("game", "max_attempts")
		self._dictionary = Dictionary()
		self._dictionary.load_from_file(config.get("game", "dictionary"))

	def run(self):
		secret = self._dictionary.select_random_word()

		# Instantiate a new game.
		game = Game(
			secret, 
			self._word_length,
			self._max_attempts,
			self._dictionary
		)

		# Initialize the interface.
		console = ConsoleView()

		while not game.is_finished():
			player_guess = console.ask_guess(self._word_length)

			try:
				game.submit_guess(player_guess)
				current_guesses = game.get_guesses()
				console.visualize_guesses(current_guesses)
			except WrongGuessLengthException:
				console.show_invalid_length_guess(self._word_length)
			except InvalidGuessException:
				console.show_invalid_guess(player_guess)

		if game.is_won():
			console.visualize_win(secret)
		else:
			console.visualize_loss(secret)



Running the application

Time to play!

The src/wordle_console_app.py file contains the code needed to launch the game. It creates an instance of the controller, passes it the configuration defined in the assets/wordle.ini file and then calls its run method to start the game.

To launch the game, run the command appropriate for your operating system:

Windows: py -m src.wordle_console_app

Linux/macOS: python3 -m src.wordle_console_app

Commit and merge.

If the game works as expected, you can finalize your work by creating a commit, merging your current branch into the main branch and then pushing the changes to GitLab.

Next steps

Being able to play Wordle from a terminal is nice, but it would be even better to have a more modern and enjoyable interface!

In the next session, you will learn how to develop a web interface to play Wordle like a pro. You will also be able to easily change the game configuration, including the secret word length and the language used.