|
| 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