DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Number Guessing Game with Leaderboard

Introduction:

  • As part of my learning in Python and problem-solving, I built a Number Guessing Game and extended it with a Leaderboard system.
  • This project started as a simple guessing game but later evolved into a small system that tracks and sorts player performance.

🎮 How the Game Works:
The idea is simple:

  • The program generates a random number
  • The player tries to guess it
  • After each guess:
  • If the guess is too low → show hint
  • If too high → show hint
  • The game continues until the correct number is guessed
  • The number of attempts is recorded CODE:
import random

def play_game():
    number = random.randint(1, 100)
    attempts = 0

    while True:
        guess = int(input("Enter your guess: "))
        attempts += 1

        if guess < number:
            print("Too low!")
        elif guess > number:
            print("Too high!")
        else:
            print(f"Correct! You guessed it in {attempts} attempts.")
            return attempts
Enter fullscreen mode Exit fullscreen mode

⚙️ Adding Difficulty Levels:

To make the game more interesting, I introduced difficulty levels:

  • Easy → 1 to 50
  • Medium → 1 to 100
  • Hard → 1 to 200 This changes how challenging the game feels.

🏆 Leaderboard System:

Instead of stopping at just gameplay, I added a Leaderboard to store results.
Each record contains:

  • Player name
  • Difficulty level
  • Number of attempts
leaderboard = [
    {"name": "Ashiq", "difficulty": "Easy", "attempts": 3},
    {"name": "John", "difficulty": "Hard", "attempts": 7}
]
Enter fullscreen mode Exit fullscreen mode

🔄 Sorting the Leaderboard:

To analyze performance, I implemented sorting based on:
Attempts (fewer attempts = better)
Difficulty level

def sort_leaderboard(data, key, reverse=False):
    return sorted(data, key=lambda x: x[key], reverse=reverse)
Enter fullscreen mode Exit fullscreen mode

🔍 How the System Works:

This project combines two main parts:

  1. Game Logic Handles:
  2. Random number generation
  3. User input
  4. Hint system
  5. Attempt tracking

  6. Data Handling
    Handles:

  7. Storing player results

  8. Sorting leaderboard

  9. Displaying rankings

⏱️ Complexity:

  1. Game loop → depends on user attempts
  2. Sorting → O(n log n)

⚠️ Challenges Faced:

  1. Handling invalid user input
  2. Designing a clean leaderboard structure
  3. Implementing flexible sorting options

Top comments (0)