Skip to content

Commit e927cad

Browse files
Merge pull request steam-bell-92#1094 from knoxiboy/feat/issue-972-sqlite-support
feat: Add SQLite Support for Persistent High Scores in Games
2 parents d357f96 + e2177a0 commit e927cad

4 files changed

Lines changed: 96 additions & 0 deletions

File tree

games/Whack-a-Mole/Whack-a-Mole.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ def main():
1111
import os
1212
import sys
1313

14+
# Add root directory to sys.path to import utils package
15+
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
16+
from utils import save_score, get_top_scores
17+
1418
# Windows only for non-blocking input
1519
try:
1620
import msvcrt
@@ -206,6 +210,20 @@ def main():
206210
else:
207211
print("\n 🐭 The moles win this round...")
208212

213+
# Save and display high scores
214+
name = input("\n Enter your name for the high scores board: ").strip()
215+
if name:
216+
save_score("Whack-a-Mole", name, score)
217+
218+
print("\n🏆 ===== HIGH SCORES BOARD =====")
219+
top_scores = get_top_scores("Whack-a-Mole", 5)
220+
if top_scores:
221+
for idx, (p_name, p_score, p_time) in enumerate(top_scores):
222+
print(f" {idx+1}. {p_name:15s} : {p_score:4d} ({p_time})")
223+
else:
224+
print(" No high scores yet!")
225+
print("================================")
226+
209227
while True:
210228
replay = input("\n Play again? (y / n): ").strip().lower()
211229
if replay in ['y', 'yes', 'n', 'no']:

utilities/Typing-Speed-Tester/Typing-Speed-Tester.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22
import random
33
import urllib.request
44
import json
5+
import sys
6+
import os
7+
8+
# Add root directory to sys.path to import utils package
9+
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
10+
from utils import save_score, get_top_scores
511

612
# Local fallback sentences
713
fallback_sentences = [
@@ -102,6 +108,20 @@
102108
print("👍 Good Attempt!")
103109
else:
104110
print("💡 Keep Practicing!")
111+
112+
# Save and display high scores
113+
name = input("\n Enter your name for the high scores board: ").strip()
114+
if name:
115+
save_score("Typing-Speed-Tester", name, int(wpm))
116+
117+
print("\n🏆 ===== HIGH SCORES BOARD =====")
118+
top_scores = get_top_scores("Typing-Speed-Tester", 5)
119+
if top_scores:
120+
for idx, (p_name, p_score, p_time) in enumerate(top_scores):
121+
print(f" {idx+1}. {p_name:15s} : {p_score:4d} WPM ({p_time})")
122+
else:
123+
print(" No high scores yet!")
124+
print("================================")
105125

106126
again = input("\n🔄 Do you want to test again? (y/n): ").strip().lower()
107127
if again != 'y':

utils/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
# Central utilities package
2+
from utils.db_manager import save_score, get_top_scores

utils/db_manager.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import os
2+
import sqlite3
3+
from datetime import datetime
4+
5+
# Resolve database path to root directory
6+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7+
DB_PATH = os.path.join(BASE_DIR, "data.db")
8+
9+
def get_connection():
10+
"""Returns a connection to the SQLite database."""
11+
conn = sqlite3.connect(DB_PATH)
12+
return conn
13+
14+
def init_db():
15+
"""Initializes the database and creates high_scores table if it doesn't exist."""
16+
conn = get_connection()
17+
cursor = conn.cursor()
18+
cursor.execute("""
19+
CREATE TABLE IF NOT EXISTS high_scores (
20+
id INTEGER PRIMARY KEY AUTOINCREMENT,
21+
game_name TEXT NOT NULL,
22+
player_name TEXT NOT NULL,
23+
score INTEGER NOT NULL,
24+
timestamp TEXT NOT NULL
25+
)
26+
""")
27+
conn.commit()
28+
conn.close()
29+
30+
def save_score(game_name: str, player_name: str, score: int):
31+
"""Saves a player's score to the database."""
32+
init_db()
33+
conn = get_connection()
34+
cursor = conn.cursor()
35+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
36+
cursor.execute("""
37+
INSERT INTO high_scores (game_name, player_name, score, timestamp)
38+
VALUES (?, ?, ?, ?)
39+
""", (game_name, player_name.strip(), score, timestamp))
40+
conn.commit()
41+
conn.close()
42+
43+
def get_top_scores(game_name: str, limit: int = 5):
44+
"""Retrieves top scores for a specific game."""
45+
init_db()
46+
conn = get_connection()
47+
cursor = conn.cursor()
48+
cursor.execute("""
49+
SELECT player_name, score, timestamp
50+
FROM high_scores
51+
WHERE game_name = ?
52+
ORDER BY score DESC, timestamp ASC
53+
LIMIT ?
54+
""", (game_name, limit))
55+
results = cursor.fetchall()
56+
conn.close()
57+
return results

0 commit comments

Comments
 (0)