Adding Leaderboard View and Sorting Feature
In this task, we improve the Number Guessing Game by adding a leaderboard feature. This allows users to view past scores and sort them based on difficulty and number of attempts.
Goal of This Enhancement
The main idea is to:
- Display leaderboard data from the database
- Allow sorting based on difficulty level
- Allow sorting based on number of attempts
This makes the game more interactive and competitive.
Step 1 Create Leaderboard Table
First, make sure you have a table to store player results.
```sql id="a1b2c3"
CREATE TABLE leaderboard (
id SERIAL PRIMARY KEY,
player_name VARCHAR(50),
difficulty VARCHAR(20),
attempts INT
);
This table stores player name, difficulty level, and number of attempts taken to guess correctly.
---
## Step 2 Insert Sample Data
```sql id="d4e5f6"
INSERT INTO leaderboard (player_name, difficulty, attempts)
VALUES
('Arul', 'Easy', 3),
('Meena', 'Medium', 5),
('John', 'Hard', 7);
Step 3 Add Menu Option in Game
In your program, add an option for users to view the leaderboard.
Example menu:
1 Play Game
2 View Leaderboard
3 Exit
When the user selects View Leaderboard, fetch data from the database.
Step 4 Fetch Leaderboard Data
```sql id="g7h8i9"
SELECT player_name, difficulty, attempts
FROM leaderboard;
This retrieves all records from the leaderboard.
---
## Step 5 Sorting by Difficulty
To sort by difficulty level:
```sql id="j1k2l3"
SELECT player_name, difficulty, attempts
FROM leaderboard
ORDER BY difficulty ASC;
You can also use DESC for reverse order.
Step 6 Sorting by Attempts
To sort based on number of attempts:
```sql id="m4n5o6"
SELECT player_name, difficulty, attempts
FROM leaderboard
ORDER BY attempts ASC;
This shows players who guessed the number in fewer attempts first.
---
## Step 7 Combine Sorting
You can sort by both difficulty and attempts together.
```sql id="p7q8r9"
SELECT player_name, difficulty, attempts
FROM leaderboard
ORDER BY difficulty ASC, attempts ASC;
This first groups by difficulty and then sorts by attempts.
Step 8 Dynamic Sorting Option
You can ask the user how they want to sort:
Sort Options
1 Difficulty Ascending
2 Difficulty Descending
3 Attempts Ascending
4 Attempts Descending
Based on user choice, change the query.
Example:
```sql id="s1t2u3"
SELECT player_name, difficulty, attempts
FROM leaderboard
ORDER BY attempts DESC;
---
## Conclusion
By adding a leaderboard feature, the Number Guessing Game becomes more engaging. Users can track their performance and compare with others.
Sorting options help users view results in a meaningful way, either by difficulty or by efficiency in guessing.
This is a simple but powerful improvement that brings real world functionality into your project.
Top comments (0)