DEV Community

Santhoshi Mary A
Santhoshi Mary A

Posted on

Number Guessing Game

Step 1: Sample Leaderboard Database Structure

We create a leaderboard table with:

id
player_name
difficulty
attempts
import sqlite3

conn = sqlite3.connect("leaderboard.db")
cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS leaderboard (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_name TEXT,
difficulty TEXT,
attempts INTEGER
)
""")

conn.commit()

Explanation:

sqlite3.connect() creates or connects to the database.
CREATE TABLE IF NOT EXISTS ensures table is created only once.
Step 2: Insert Sample Data
cursor.execute("INSERT INTO leaderboard (player_name, difficulty, attempts) VALUES (?, ?, ?)",
("Santhoshi", "Easy", 3))

cursor.execute("INSERT INTO leaderboard (player_name, difficulty, attempts) VALUES (?, ?, ?)",
("Arun", "Medium", 5))

conn.commit()

Explanation:

? placeholders prevent SQL injection.
Data is committed using commit().
Step 3: Show Leaderboard Option
def show_leaderboard():
cursor.execute("SELECT player_name, difficulty, attempts FROM leaderboard")
records = cursor.fetchall()

print("\n--- Leaderboard ---")
for row in records:
    print(f"Name: {row[0]}, Difficulty: {row[1]}, Attempts: {row[2]}")
Enter fullscreen mode Exit fullscreen mode

Explanation:

SELECT fetches all leaderboard data.
fetchall() returns all rows.
Loop prints formatted output.
Step 4: Sorting Leaderboard

We allow sorting by:

Difficulty
Attempts
Ascending or Descending
def show_sorted_leaderboard(sort_by="attempts", order="ASC"):
query = f"SELECT player_name, difficulty, attempts FROM leaderboard ORDER BY {sort_by} {order}"
cursor.execute(query)
records = cursor.fetchall()

print(f"\n--- Leaderboard Sorted by {sort_by} ({order}) ---")
for row in records:
    print(f"Name: {row[0]}, Difficulty: {row[1]}, Attempts: {row[2]}")
Enter fullscreen mode Exit fullscreen mode

Explanation:

ORDER BY sorts results.
ASC → Ascending order
DESC → Descending order
sort_by can be "difficulty" or "attempts"
Step 5: Menu Option in Game
while True:
print("\n1. Play Game")
print("2. View Leaderboard")
print("3. View Sorted Leaderboard")
print("4. Exit")

choice = input("Enter choice: ")

if choice == "2":
    show_leaderboard()

elif choice == "3":
    sort_field = input("Sort by (difficulty/attempts): ")
    sort_order = input("Order (ASC/DESC): ")
    show_sorted_leaderboard(sort_field, sort_order)

elif choice == "4":
    break
Enter fullscreen mode Exit fullscreen mode

Explanation:

Menu allows user to choose.
Sorting field and order are dynamic.
Calls appropriate function.

Top comments (0)