In previous session, you developed the Wordle game and learned how to play it using a text-based interface integrated into the terminal.
The goal of this tutorial is to add a web interface to the Wordle project using the Flask library.
Environment setup
- Open in Visual Studio Code the Wordle project you worked on during the previous session.
- Open the Visual Studio Code integrated terminal (on Windows, select Git Bash).
- Activate your virtual environment.
- Check that you are on the
mainbranch (using thegit branchcommand) and that your Git repository has no uncommitted changes (using thegit statuscommand).
Introducing Flask
Flask is a lightweight Python web framework that lets you create web applications. It provides the functionality needed to receive requests from a browser, run Python code in response, and send a response back to the browser.
As you may have seen in your networking course, the browser and the web server communicate using the HTTP protocol. HTTP provides several methods, two of which are particularly important for this project:
- GET is generally used to request information from the server, for example to display a page.
- POST is generally used to send information to the server, for example to submit a user's guess.
Browser Flask application | | | GET / | |--------------------------------->| | | | HTML page | |<---------------------------------| | | | POST /guess | | guess = "example" | |--------------------------------->| | | | Updated page | |<---------------------------------|
Communication between a browser and a Flask application is a little more complex than it may seem. When a user interacts with a web page, for example by clicking a link or submitting a form, the browser sends an HTTP request to a web server. The server receives the request and determines how to handle it.
However, a traditional web server cannot directly run a Python web application. To solve this problem, the Python community created WSGI (Web Server Gateway Interface), a standard interface that defines communication between a web server and a Python web application. WSGI is specified in PEP 333.
The basic architecture is therefore as follows:
Browser
│ │ HTTP request ▼
Web server
│ │ WSGI ▼
Python web application
│ ▼
HTTP response
│ ▼
Browser
A WSGI server, such as Gunicorn or Waitress, runs the Python application and communicates with it through the WSGI interface. These servers can accept HTTP requests themselves, but in production they are often placed behind a separate web server. The web server can serve static files, handle HTTPS connections, and filter or forward incoming requests, while the WSGI server focuses on running the Python application. The web server placed in front of the application server is called a reverse proxy. A typical production architecture therefore looks like this:
Browser
│ │ HTTP/HTTPS ▼
Web server / Reverse proxy
│ │ WSGI ▼
WSGI server
│ ▼
Flask application
First Flask application
To get familiar with Flask and its terminology, let's start with a simple example. We will create a small Flask application to explore some of the concepts introduced above.
In the src directory, create a subdirectory named playground, then add a file named flask_sample_app.py to it. We will build our sample application in this file step by step.
Initializing the application
A Flask application is represented by a Python object created from the Flask class. Add the following code to flask_sample_app.py:
from flask import Flask app = Flask(__name__)
The app object represents our web application. It receives HTTP requests and determines how to handle them.
The argument passed to the Flask constructor is the name of the application's module or package. In most cases, __name__ is the right choice. __name__ is a special Python variable that contains the name of the module in which the code is defined. In our example, its value is src.playground.flask_sample_app.
Flask uses this information to determine the location of the application and its associated resources, such as templates and static files, which we will introduce later.
Routes and views
When a user interacts with a web application, they request specific URLs (Uniform Resource Locators), such as http://example.com/wordle. The application must determine what to do when a given URL is requested.
Flask introduces the concept of a route for this purpose. A route maps a URL to a Python function that should run when that URL is requested. This function is called a view.
For example, the following code defines a route for /, which conventionally represents the home page of a web application:
@app.route("/")
def home():
return "Hello, world!"
Here, / is the route and home() is the view function associated with it. When a browser requests /, Flask calls home() and sends it the returned value.
👉 Add this code to flask_sample_app.py.
Running the application
We can now start the application from the terminal with the following command:
flask --app src.playground.flask_sample_app run --debug
The command should display some text in the terminal and then appear to stop responding. This is normal: Flask has started the development server and is now waiting for incoming requests.
Among the messages displayed in the terminal, you should see something like:
Running on http://127.0.0.1:5000
Open this address in a web browser. You should see:
Hello, world!
Is port 5000 already in use?
If you see:
Address already in use Port 5000 is in use by another program.
this means that another application is already using port 5000. You can stop that application or ask Flask to use a different port. For example:
flask --app src.playground.flask_sample_app run --debug --port 5001
You can then access the application at http://127.0.0.1:5001.
What happens when you run a Flask application?
When you launch the application with the flask command, Flask starts its built-in development server, which provides a WSGI interface to the application. This server is convenient for development and testing, but it is not intended for production. It does not provide the performance, robustness, or security needed to handle real production traffic. Flask therefore displays a warning reminding you not to use the development server in production.
The --debug option enables debug mode. It provides two features that are particularly useful during development.
First, if an error occurs while processing a request, Flask displays a detailed traceback in the browser. This makes it easier to determine where and why the error occurred.
Second, Flask automatically reloads the application when you modify the source code. You can therefore modify the code, save the file, and immediately test your changes without manually stopping and restarting the server.
You may also notice a message in the terminal containing a debugger PIN, for example:
Debugger PIN: 123-456-789
This PIN is for Flask's interactive debugger. In addition to displaying the error traceback, the debugger can provide an interactive environment in the browser where the developer can inspect the application's state and, after authentication, run Python expressions.
This feature is very powerful and could be dangerous if anyone able to connect to the application had access to it. The PIN therefore provides an additional layer of protection for the interactive debugger.
For this reason, debug mode should only be used during development and testing. In particular, a Flask application with the interactive debugger enabled must never be exposed to untrusted users or deployed in production.
👉 Add the following code to flask_sample_app.py:
@app.route("/about")
def about():
return "About page"
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}!"
@app.route("/status")
def status():
return "<h1>Everything is working!</h1>"
As you can see in the second route, a route can also contain dynamic parts. In the third route, the view returns HTML code, which is used to create a web page.
👉 Try the application to check that all the routes work correctly.
Templates
In a real web application, we generally do not want to write complete HTML pages directly inside Python functions. That would mix the application's presentation with its Python code, making the application harder to organize and maintain.
To solve this problem, Flask supports templates. A template is generally an HTML file that defines the structure of a web page and contains placeholders for information that the Python application will provide dynamically.
Flask uses the Jinja template engine to process templates. Consider the following template, for example:
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
The {{ name }} expression is a Jinja placeholder. When the template is rendered, Flask replaces it with the value associated with the name variable.
By default, Flask looks for templates in a folder named templates. This folder is usually located relative to the module or package in which the Flask application is defined. You can also customize its location with the template_folder argument when creating the Flask application.
👉 Create a folder named templates in src/playground, then create a file named hello.html containing the template above. Next, modify your Flask application so that the /hello/<name> route renders this template:
from flask import render_template
@app.route("/hello/<name>")
def hello(name):
return render_template("hello.html", name=name)
The call to render_template() performs two operations:
- It loads the
hello.htmltemplate file from the templates folder. - It passes the value of the
namevariable to the template.
For example, if the user visits /hello/Alice, Flask calls hello("Alice"). The function then renders hello.html, passing Alice as the value of name. Jinja replaces {{ name }} with this value, and the browser receives the resulting HTML:
<h1>Hello, Alice!</h1>
Thus, the Python code remains responsible for processing the request and preparing the data, while the template defines how that data is presented in the browser.
Wordle web interface
For our Wordle game, we want to create a web interface that provides the main elements needed to play and configure a game:
- The game board. It consists of a grid of cells. The number of columns corresponds to the number of letters in a valid guess, while the number of rows corresponds to the maximum number of attempts. Each cell represents a letter entered by the player.
- A virtual keyboard. It is displayed below the board and provides an overview of the letters used during the game. As guesses are submitted, the keys can be colored to indicate the state of each letter.
- The game settings. The interface must allow the user to start a new game and change settings such as the language, the required length of guesses, and the maximum number of attempts.
All code related to the web interface will be in the src/view/web directory. This directory already contains two important subdirectories:
templates: this directory contains the HTML templates that define the structure and content of the web pages. Since HTML is not part of the SIP curriculum, the templates are provided and you will not need to modify them.static: this directory contains static files, that is, files sent to the browser without being generated dynamically by the application. It includes thestyle.cssfile, which contains the style rules for the web interface. Like the HTML templates, the CSS file is provided with the project because CSS is not part of the SIP curriculum.
CSS
The style.css file uses Cascading Style Sheets (CSS), a language commonly used on the web to control the appearance and layout of HTML elements. CSS makes it possible to separate a page's content and structure, defined in HTML, from its presentation: colors, fonts, spacing, and positioning.
Game configuration
The game configuration is stored in the wordle.toml file in the assets directory.
We use the TOML format, which allows configuration data to be represented in a more structured way than the traditional INI format. TOML supports, among other things, nested tables, arrays, and explicit data types, which are useful when the configuration becomes more complex.
For example, the configuration can organize settings for each language hierarchically:
[languages.en] label = "English" flag = "🇬🇧" dictionary = "assets/dictionaries/wordle_en.txt" [languages.fr] label = "Français" flag = "🇫🇷" dictionary = "assets/dictionaries/wordle_fr.txt"
Here, en and fr are nested sections within the languages section. An INI parser, by contrast, would generally interpret [languages.en] and [languages.fr] as two distinct section names, rather than as nested sections.
Application factory
As we have seen, a Flask application is an instance of the Flask class. Routes, views, configuration settings, and other application components are registered with this instance.
In our first example, we put all of this code in a single file. This approach is suitable for a small example, but quickly becomes difficult to manage as the application grows. In a larger project, we therefore want to distribute the code across several modules.
This raises an important question: where should we create the Flask application object?
One possibility would be to create a global Flask object that the different application modules could import. However, the Flask documentation discourages this approach in large applications because it can lead to problems with imports, testing, and managing multiple application instances.
Flask instead recommends using an application factory. An application factory is simply a function that creates and configures a new Flask application. All the instructions needed to initialize it, such as loading the configuration and registering routes and other components, can be placed in this function.
The application factory is generally defined in a file named __init__.py. In our project, this file will be located at src/view/web/__init__.py.
Now remember to work on a new Git branch.
Exercise 1. Create a file named __init__.py in the src/view/web directory and add the following code to it:
from pathlib import Path
import tomllib
from flask import Flask
from src.view.web.wordle_state import initialize_game
def create_app():
app = Flask(__name__)
with open("assets/wordle.toml", "rb") as f:
config = tomllib.load(f)
app.config.from_mapping(
GAME=config["game"],
SETTINGS=config["settings"],
LANGUAGES=config["languages"]
)
return app
The create_app() function is our application factory. When we start the application with the flask command, Flask will find and call this function to create the application.
The function performs the following steps:
- Creates a Flask application by instantiating the
Flaskclass. - Loads the configuration from
assets/wordle.tomlusing Python'stomllibmodule, which is part of the standard library. - Registers the configuration with the Flask application using
app.config.from_mapping(). - Returns the configured application.
The configuration is stored in app.config, Flask's configuration object. We store the three main sections of our TOML file under the GAME, SETTINGS, and LANGUAGES keys.
Notice that these keys are written in uppercase, following Flask's convention for application configuration keys:
app.config["GAME"] app.config["SETTINGS"] app.config["LANGUAGES"]
The values associated with these keys correspond to the sections loaded from the TOML file.
At this point, the factory only creates the application and loads its configuration. As we develop the web interface, we will add the other initialization steps, such as registering routes.
Initializing the game
If we run the application at this point, Flask will start correctly, but every URL request will return a 404 Not Found response. This is because we have not yet defined any routes or view functions.
Before defining the routes, however, we need to implement functions that manage the Wordle game state for the web application. We will put them in a new Python module named wordle_state.py, located in src/view/web/.
Exercise 2. Create the wordle_state.py file in the src/view/web/ directory and define a function called initialize_game().
This function must take two arguments:
game_settings: a dictionary containing the settings from the[game]section ofwordle.toml;language_settings: a dictionary containing the settings from the[languages]section ofwordle.toml.
The function must use these settings to create and initialize a new game, then return an instance of the Game class (defined in src/model/game.py).
SOLUTION ELEMENTS
from src.model.dictionary import Dictionary from src.model.game import Game def initialize_game(game_settings: dict, language_settings: dict) -> Game: """ Initialize a new game from settings, mirroring console startup logic. """ language = game_settings["language_code"] word_length = game_settings["word_length"] max_attempts = game_settings["max_attempts"] dictionary = Dictionary() dictionary.load_from_file(language_settings[language]["dictionary"]) secret = dictionary.select_random_word(word_length) return Game(secret, word_length, max_attempts, dictionary)
👉 In __init__.py, add the following line inside the create_app() function, before return app:
app.extensions["wordle"] = initialize_game(
config["game"],
config["languages"],
)
Why store the game instance in app.extensions?
Flask's app.extensions dictionary is intended for storing extensions and application-specific objects that need to remain accessible throughout the application.
In our case, we want to create the Game instance once, when the Flask application is initialized, and then make it accessible to the different parts of the application that need it.
By storing it in app.extensions["wordle"], we will be able to retrieve this same Game instance from the Flask application later, instead of creating a new game for every request.
This approach is particularly useful here because the Game object represents the state of the Wordle game. If we created a new instance for every request, information such as the guesses already submitted by the user would be lost.
The wordle key is the name our application uses to access this shared game instance.
Board view
We will now create the board view.
Exercise 3. Add a build_board_view() function to wordle_state.py.
It takes two arguments:
game: an instance of theGameclass, that is, the object returned byinitialize_game();game_settings: a dictionary containing the settings defined in the[game]section ofwordle.toml.
The function must return the board view as a list of lists of dictionaries.
More specifically:
- Each row of the board represents a user guess and takes the form of a list of dictionaries.
- Each dictionary represents a cell and contains two keys:
- "letter": the letter entered by the user;
- "state": the state of the letter, which must be "correct", "present", or "absent".
Some rows, or even all of them, may still be empty if the user has not used all their attempts. In these rows, each cell must contain:
{"letter": "", "state": "unknown"}
This way, every row of the returned board has the same number of cells, whether or not it contains a guess.
SOLUTION ELEMENTS
def build_board_view(game: Game, game_settings: dict) -> list[list[dict]]:
"""
Build a board view model with letter and state for each cell.
"""
word_length = game_settings["word_length"]
max_attempts = game_settings["max_attempts"]
board_rows: list[list[dict]] = []
for annotated_guess in game.get_guesses():
row = []
for annotated_letter in annotated_guess:
row.append(
{
"letter": annotated_letter.letter.upper(),
"state": annotated_letter.state.name.lower(),
}
)
board_rows.append(row)
for _ in range(max_attempts - len(board_rows)):
row = [{"letter": "", "state": "unknown"} for _ in range(word_length)]
board_rows.append(row)
return board_rows
Keyboard state
We will now implement a function that manages the state of the virtual keyboard.
Exercise 4. Implement the build_keyboard_state() function in wordle_state.py.
It builds the state of the game's virtual keyboard from the guesses submitted by the user.
The function takes one argument:
game: an instance of theGameclass. You can use this object's methods to retrieve the guesses submitted by the user.
The function must return a dictionary mapping each letter of the alphabet to its current state:
{
"A": "unknown",
"B": "absent",
...
"Z": "unknown",
}
The returned dictionary must contain all the letters from A to Z, with the initial state "unknown". Use the guesses submitted by the user to determine the state of each letter. Each guess contains letters and their corresponding state. The possible states of a letter are:
- "unknown": the letter does not appear in any submitted guess;
- "absent": the letter was guessed, but does not appear in the target word;
- "present": the letter appears in the target word, but is not in the correct position;
- "correct": the letter is in the correct position.
A letter may appear in several guesses with different states. In this case, keep the state with the highest priority. The states are ranked from lowest to highest priority as follows:
unknown < absent < present < correct
For example, if A is "absent" in one guess and "present" in another, its final state must be "present". If it is "correct" in at least one guess, its final state must be "correct".
The keyboard uses uppercase letters, so be sure to convert letters extracted from the guesses to uppercase before updating the dictionary. After processing all submitted guesses, the function must return the completed dictionary.
SOLUTION ELEMENTS
def build_keyboard_state(game: Game) -> dict[str, str]:
"""
Build virtual keyboard color states from submitted guesses.
Priority order is: correct > present > absent > unknown.
"""
state_priority = {
"unknown": 0,
"absent": 1,
"present": 2,
"correct": 3,
}
keyboard_states = {chr(code): "unknown"
for code in range(ord("A"), ord("Z") + 1)}
for annotated_guess in game.get_guesses():
for annotated_letter in annotated_guess:
letter = annotated_letter.letter.upper()
state = annotated_letter.state.name.lower()
if letter in keyboard_states and
state_priority[state] > state_priority[keyboard_states[letter]]:
keyboard_states[letter] = state
return keyboard_states
Game status
We will now implement a function that tracks the state of the game.
Exercise 5. Implement the build_status() function in wordle_state.py.
It builds a dictionary describing the current state of the game from the state of the Game object.
The function takes one argument:
game: an instance of theGameclass.
The function must return a dictionary containing two keys:
- "type": indicates the type of state;
- "message": contains the message to display to the user.
The game can be in one of the following three states:
- The player has won. In this case, return:
{"type": "win", "message": "Great job! You guessed the word."} - The game is over without a win. If the player has used all their attempts without guessing the word, return a state with type "loss". The message must include the secret word in uppercase.
- The game is still in progress. If the player has neither won nor run out of attempts, return:
{"type": "info", "message": ""}
Important. Check the game states in the correct order. In particular, a won game must be reported as a win, even if the winning guess also means that the game is over.
SOLUTION ELEMENTS
def build_status(game: Game) -> dict:
if game.is_won():
return {"type": "win", "message": "Great job! You guessed the word."}
if game.is_finished():
return {"type": "loss",
"message": f"No attempts left.
The word was {game.get_secret().upper()}. Start a new game."}
return {"type": "info", "message": ""}
Routes and views
We will now define the routes and implement the corresponding views to display the game, submit guesses, start a new game, and change the settings.
Instead of defining all the routes and views in a single file, we group related functionality using a Flask concept called a blueprint. In this project, we can define two separate blueprints:
game, which contains all routes and views related to the game itself;settings, which contains all routes and views related to the game configuration.
Exercise 6. Create a game.py file in the src/view/web directory and write the following code in it:
from flask import Blueprint
bp = Blueprint('game', __name__)
This code creates a new blueprint named game.
Once the blueprint is defined, we can associate routes with it. Let's start with the index page route, /.
We will then gradually build the corresponding view to render the index page and display the game interface.
Exercise 7. Define an index() view in the game.py file and associate it with the / route. Since this route belongs to the blueprint, use the bp.get("/") decorator.
The index() function must:
- Retrieve the game settings from
current_app.config["GAME"]. To accesscurrent_app, import it fromflask. Remember that we used an application factory to create and initialize the Flask application. Outside this factory, the current application is therefore available throughcurrent_app. Store the game settings in a variable namedgame_settings. - Retrieve the current
Gameinstance. In the application factory, we stored an instance of theGameclass inapp.extensions["wordle"]. Theindex()function must therefore retrieve it fromcurrent_app.extensions["wordle"]. Store the game instance in a variable namedgame.
SOLUTION ELEMENTS
Here is the current code for the game.py file.
from flask import Blueprint, current_app
bp = Blueprint('game', __name__)
@bp.get("/")
def index() -> str:
game_settings = current_app.config["GAME"]
game = current_app.extensions["wordle"]
To display the game interface, the index() function must build the board view and the keyboard state. The index.html template needs these components. Let's define them.
Exercise 8. Add the following instructions to the index() function:
- Get the board view using the
build_board_view()function defined inwordle_state.py. Store it in a variable namedboard_view. - Get the keyboard state using the
build_keyboard_state()function defined inwordle_state.py. Store it in a variable namedkeyboard_states. - Get the current game status using the
build_status()function defined inwordle_state.py. Store it in a variable namedstatus. - Determine the index of the active row (the board row where the user should enter their next guess). If the game is in progress, the active row is the number of guesses already submitted; if the game is over, there is no active row and you must use -1. Store this index in a variable named
active_row.
SOLUTION ELEMENTS
Here is the current code for the game.py file.
from flask import Blueprint, current_app
from src.view.web.wordle_state import (
initialize_game,
build_board_view,
build_keyboard_state,
build_status
)
bp = Blueprint('game', __name__)
@bp.get("/")
def index() -> str:
game_settings = current_app.config["GAME"]
game = current_app.extensions["wordle"]
board_view = build_board_view(game, game_settings)
keyboard_states = build_keyboard_state(game)
status = build_status(game)
active_row = len(game.get_guesses()) if not game.is_finished() else -1
It is now time to render the index.html template. This template needs several arguments, some of which correspond to the values retrieved in the previous two exercises.
Exercise 9. Add the following instruction to the index() function:
return render_template(
"index.html",
game_settings=game_settings,
general_settings=current_app.config["SETTINGS"],
language_settings=current_app.config["LANGUAGES"],
board_rows=board_view,
keyboard_states=keyboard_states,
active_row=active_row,
error_message=request.args.get("error", ""),
status=status,
)
Notes:
- You must import
render_templateandrequestfromflask. - We pass the general and language settings to the template.
- We also pass an
error_messageto the template. This message comes from the optionalerrorquery parameter, which can be supplied in a request to the/page, for example/?error=Invalid+word. We will use this mechanism later to display error messages to the user during the game.
SOLUTION ELEMENTS
Here is the current code for the game.py file.
from flask import Blueprint, current_app, request, render_template
from src.view.web.wordle_state import (
initialize_game,
build_board_view,
build_keyboard_state,
build_status
)
bp = Blueprint('game', __name__)
@bp.get("/")
def index() -> str:
game_settings = current_app.config["GAME"]
game = current_app.extensions["wordle"]
board_view = build_board_view(game, game_settings)
keyboard_states = build_keyboard_state(game)
status = build_status(game)
active_row = len(game.get_guesses()) if not game.is_finished() else -1
return render_template(
"index.html",
game_settings=game_settings,
general_settings=current_app.config["SETTINGS"],
language_settings=current_app.config["LANGUAGES"],
board_rows=board_view,
keyboard_states=keyboard_states,
active_row=active_row,
error_message=request.args.get("error", ""),
status=status,
)
The blueprint must now be registered with the Flask application. Otherwise, its associated routes will not be available to the application.
Exercise 10. Add the following instructions to the create_app() function in the __init__.py file, just before the return app statement:
from . import game app.register_blueprint(game.bp)
It is now time to test the application.
👉 Enter the following command:
flask --app src.view.web run --debug
If you enter the URL http://127.0.0.1:5000/ in your browser, you should see the game board and the virtual keyboard. You should also be able to enter a guess on the first row. However, you will not be able to submit it yet, because we have not implemented the route that handles it.
👉 Now try entering the URL http://127.0.0.1:5000/?error=test. The message "test" should appear in red in the interface. This illustrates the purpose of the error_message argument added to the render_template() call.
Let's now implement the view associated with the /guess route. It will allow the user to submit a guess and receive its result.
Exercise 11. Add a submit_guess() function to game.py. It will retrieve the entered guess and submit it to the current Game instance using the method implemented while developing the game model.
- Decorate the function with
@bp.post("/guess"). We use thePOSTmethod because the user is sending data to the server. - Retrieve the submitted guess with:
request.form.get("guess", "").strip().lower(). Inindex.html, you will find an HTML form element namedguessthat lets the user enter a guess. The instruction above retrieves the value sent by this element. The call tostrip()removes leading and trailing spaces, whilelower()converts the guess to lowercase. - The function must end with:
return redirect(url_for("game.index")). Bothredirectandurl_formust be imported fromflask. This instruction redirects the user to the index page associated with the/route. Note that we usegame.indexrather than simplyindex, because theindexview belongs to thegameblueprint.- We also use
url_forinstead of writing the/URL directly. This way, if we later change the route associated withindex(), we will not need to change the redirect code. redirectasks the browser to send a new request to the index page. Theindex()view then renders the current game state, including the guess that was just submitted.
- We also use
- Be sure to catch any exceptions that may be raised when submitting the guess to the
Gameinstance. For example, if the user submits a word that is not in the dictionary, an appropriate error message should be displayed. You can redirect to the index page and pass the error message as a query parameter using the following instruction:
return redirect(url_for("game.index", error="The word is not in the dictionary"))
The error parameter will then be available to the index() view and can be passed to the index.html template to be displayed to the user.
SOLUTION ELEMENTS
from flask import Blueprint, current_app, request, render_template, redirect, url_for
from src.model.exceptions.GameFinishedException import GameFinishedException
from src.model.exceptions.InvalidGuessException import InvalidGuessException
from src.model.exceptions.WrongGuessLengthException import WrongGuessLengthException
from src.view.web.wordle_state import (
initialize_game,
build_board_view,
build_keyboard_state,
build_status
)
bp = Blueprint('game', __name__)
@bp.get("/")
def index() -> str:
game_settings = current_app.config["GAME"]
game = current_app.extensions["wordle"]
board_view = build_board_view(game, game_settings)
keyboard_states = build_keyboard_state(game)
status = build_status(game)
active_row = len(game.get_guesses()) if not game.is_finished() else -1
return render_template(
"index.html",
game_settings=game_settings,
general_settings=current_app.config["SETTINGS"],
language_settings=current_app.config["LANGUAGES"],
board_rows=board_view,
keyboard_states=keyboard_states,
active_row=active_row,
error_message=request.args.get("error", ""),
status=status,
)
@bp.post("/guess")
def submit_guess() -> str:
game = current_app.extensions["wordle"]
guess = request.form.get("guess", "").strip().lower()
try:
game.submit_guess(guess)
except WrongGuessLengthException:
return redirect(url_for("game.index", error="Wrong guess length."))
except InvalidGuessException:
return redirect(url_for("game.index",
error=f"'{guess}' is not a valid word."))
except GameFinishedException:
return redirect(url_for("game.index",
error="Game is finished. Change settings to start a new game."))
return redirect(url_for("game.index"))
👉 In the index.html template, uncomment lines 86 to 88 by removing {# on line 86 and #} on line 88. Run the application and play!
Does everything work as expected? You should notice, however, that it is not possible to start a new game. Let's add this feature!
Exercise 12. Add a new new_game() view to game.py and associate it with the /new-game route. This view must initialize a new game.
Uncomment lines 52 to 54 of the index.html template. A button allowing the user to start a new game will appear.
Run the application and test this feature. Check that clicking the button starts a new game.
SOLUTION ELEMENTS
Here is the complete code for the game.py file.
from flask import Blueprint, current_app, request, render_template, redirect, url_for
from src.model.exceptions.GameFinishedException import GameFinishedException
from src.model.exceptions.InvalidGuessException import InvalidGuessException
from src.model.exceptions.WrongGuessLengthException import WrongGuessLengthException
from src.view.web.wordle_state import (
initialize_game,
build_board_view,
build_keyboard_state,
build_status
)
bp = Blueprint('game', __name__)
@bp.get("/")
def index() -> str:
game_settings = current_app.config["GAME"]
game = current_app.extensions["wordle"]
board_view = build_board_view(game, game_settings)
keyboard_states = build_keyboard_state(game)
status = build_status(game)
active_row = len(game.get_guesses()) if not game.is_finished() else -1
return render_template(
"index.html",
game_settings=game_settings,
general_settings=current_app.config["SETTINGS"],
language_settings=current_app.config["LANGUAGES"],
board_rows=board_view,
keyboard_states=keyboard_states,
active_row=active_row,
error_message=request.args.get("error", ""),
status=status,
)
@bp.post("/guess")
def submit_guess() -> str:
game = current_app.extensions["wordle"]
guess = request.form.get("guess", "").strip().lower()
try:
game.submit_guess(guess)
except WrongGuessLengthException:
return redirect(url_for("game.index", error="Wrong guess length."))
except InvalidGuessException:
return redirect(url_for("game.index",
error=f"'{guess}' is not a valid word."))
except GameFinishedException:
return redirect(url_for("game.index",
error="Game is finished. Change settings to start a new game."))
return redirect(url_for("game.index"))
@bp.post("/new-game")
def new_game() -> str:
settings = current_app.config["GAME"]
current_app.extensions["wordle"] =
initialize_game(settings, current_app.config["LANGUAGES"])
return redirect(url_for("game.index"))
Game settings
The only remaining feature is to let users change the game settings: the language, the number of attempts, and the length of guesses.
In the index.html template, the code that displays the controls for changing these settings is on lines 13 to 50.
👉 Uncomment this code to enable the settings interface.
There are three types of settings:
- "language", whose value is the code for the currently selected language;
- "word_length", whose value is the length of guesses;
- "max_attempts", whose value is the maximum number of attempts allowed.
Exercise 13. Add a settings.py file to the src/view/web directory.
In this file:
- Define a new blueprint named
settings. Remember to register it with the application by adding the corresponding code to the__init__.pyfile. - Add an
update_setting()view associated with the/settingsroute. This function must:
- Retrieve the name of the setting to change with
request.form.get("setting"); - Retrieve the value of the setting with
request.form.get("value"); - Change the corresponding setting in
current_app.config["GAME"]; - Initialize a new game with these settings, then redirect to the index page.
SOLUTION ELEMENTS
Here is the code for settings.py.
from flask import Blueprint, current_app, redirect, url_for, request
from src.view.web.wordle_state import initialize_game
bp = Blueprint('settings', __name__)
@bp.post("/settings")
def update_setting() -> str:
settings = current_app.config["GAME"]
setting_name = request.form.get("setting")
value = request.form.get("value")
if setting_name == "language":
settings["language_code"] = value
if setting_name == "word_length":
settings["word_length"] = int(value)
if setting_name == "max_attempts":
settings["max_attempts"] = int(value)
current_app.extensions["wordle"] =
initialize_game(settings, current_app.config["LANGUAGES"])
return redirect(url_for("game.index"))
Don't forget to register the blueprint in __init__.py:
from .import settings app.register_blueprint(settings.bp)
👉 Use the application and check that you can change the settings correctly.
It is time to merge your branch into main and push your changes to GitLab.
Conclusion
This brings us to the end of this tutorial. Throughout the project, you have gradually built a complete application by applying several important principles and techniques of software development.
Here are some key concepts to remember:
- Test-driven development (TDD). You learned how tests can guide development by defining the expected behavior of code before or alongside its implementation.
- Model-View-Controller (MVC) pattern. You learned to separate an application's responsibilities by distinguishing the model, which manages data and logic, from views and controllers, which handle user interaction and presentation.
- Modular software design. You learned the importance of organizing an application into separate modules and components, each with a clear responsibility. This makes the code easier to understand, test, maintain, and evolve.
- Exception handling. You learned to identify error situations and use exceptions to handle them correctly, rather than mixing error handling with the normal flow of the application.
You also learned how to:
- write automated tests with
pytest, including tests that check the expected behavior of code and the correct handling of exceptional situations; - create a user interface in the terminal that lets you interact with the game directly from the command line;
- create a web interface with
Flask, using routes, views, templates, forms, redirects, and blueprints; - organize a Flask application using an application factory and modular blueprints;
- use Git to track your changes and develop the project incrementally.
Next steps
If you have time left, you can try adding the ability to play Dordle.

