Creating a Leaderboard for Your Word Prediction Game
Introduction: The Power of a Leaderboard
Welcome back! In the last lesson, you learned how to make your word prediction game smarter by scoring guesses based on how close their meaning is to the correct answer. Now, let’s take your game to the next level by adding a leaderboard.
A leaderboard is a simple but powerful feature. It lets players see how their scores compare to others, which makes the game more exciting and competitive. In this lesson, you’ll learn how to store player scores and display the top results for each day. By the end, you’ll have the foundation for a daily leaderboard that updates as people play.
Quick Recall: What Is a Model in Flask?
Before we dive in, let’s quickly remind ourselves what a model is in Flask. In web development, a model is a way to represent and store data in your application. In Flask, we often use a library called SQLAlchemy to help us manage this data.
A model is like a blueprint for a table in a database. For example, if you want to keep track of high scores, you need a model that describes what information you want to save for each score — such as the player’s name, their score, and the date.
You might remember seeing something like this before:
Here, ExampleModel is a model with two fields: id and name. Each time you add a new entry, it creates a new row in the database.
Building the HighScore Model
Now, let’s build a model for our leaderboard. We want to store each player’s name, their score, and the date they played. Let’s start step by step.
First, we need to import the right tools and set up our database connection:
Next, let’s define our HighScore model:
Let’s break down what each part does:
id: This is a unique number for each score entry. It helps us keep track of each row.name: This stores the player’s name. It’s a string and cannot be empty.score: This is the player’s score. It must be a number and cannot be empty.date: This records the date the score was achieved. By default, it uses today’s date.
To make it easy to display scores, let’s add a method to turn a score into a dictionary:
This method helps us convert a score entry into a format that’s easy to use in our app or send to the frontend.
