yahtzee-py/models/database.py

241 lines
8.2 KiB
Python

# -*- coding: utf-8 -*-
import os
import sys
import json
import sqlite3
def get_writable_db_path(filename="yahtzee_data.db") -> str:
"""
Ermittelt einen beschreibbaren Pfad für die SQLite-Datenbank:
- macOS (.app Bundle): ~/Library/Application Support/Yahtzee/
- Linux / Windows: Direkt neben der ausführbaren Datei bzw. im Projektordner
- Fallback (falls Ordner schreibgeschützt): ~/.yahtzee/
"""
if sys.platform == "darwin" and getattr(sys, "frozen", False):
app_support = os.path.expanduser("~/Library/Application Support/Yahtzee")
os.makedirs(app_support, exist_ok=True)
return os.path.join(app_support, filename)
if getattr(sys, "frozen", False):
base_dir = os.path.dirname(sys.executable)
else:
base_dir = os.path.abspath(".")
candidate = os.path.join(base_dir, filename)
if os.access(base_dir, os.W_OK):
return candidate
fallback_dir = os.path.expanduser("~/.yahtzee")
os.makedirs(fallback_dir, exist_ok=True)
return os.path.join(fallback_dir, filename)
class Database:
DB_NAME = get_writable_db_path("yahtzee_data.db")
@classmethod
def get_conn(cls):
return sqlite3.connect(cls.DB_NAME)
@classmethod
def init_db(cls):
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
password TEXT,
lang TEXT DEFAULT 'DE',
games_played INTEGER DEFAULT 0,
wins_vs_bots INTEGER DEFAULT 0,
losses_vs_bots INTEGER DEFAULT 0,
highscore INTEGER DEFAULT 0,
bot_configs TEXT DEFAULT '{}'
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS saves (
profile_id INTEGER PRIMARY KEY,
game_state TEXT NOT NULL,
FOREIGN KEY(profile_id) REFERENCES profiles(id)
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Sicherheits-Migration falls ältere Datenbank ohne bot_configs existiert
try:
c.execute("ALTER TABLE profiles ADD COLUMN bot_configs TEXT DEFAULT '{}'")
except sqlite3.OperationalError:
pass
conn.commit()
@classmethod
def save_setting(cls, key: str, value: str):
with cls.get_conn() as conn:
conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
(str(key), str(value))
)
conn.commit()
@classmethod
def load_setting(cls, key: str, default: str = None) -> str:
try:
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("SELECT value FROM settings WHERE key = ?", (str(key),))
row = c.fetchone()
return row[0] if row else default
except Exception:
return default
@classmethod
def get_all_profile_names(cls) -> list[str]:
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("SELECT name FROM profiles ORDER BY name ASC")
return [row[0] for row in c.fetchall()]
@classmethod
def create_profile(cls, name: str, password: str = "", lang: str = "DE") -> bool:
try:
with cls.get_conn() as conn:
conn.execute(
"INSERT INTO profiles (name, password, lang) VALUES (?, ?, ?)",
(name.strip(), password, lang)
)
conn.commit()
return True
except sqlite3.IntegrityError:
return False
@classmethod
def login_local(cls, name: str):
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("""
SELECT id, name, lang, games_played, wins_vs_bots, losses_vs_bots, highscore
FROM profiles WHERE name = ?
""", (name,))
row = c.fetchone()
if not row:
return None, "NOT_FOUND"
profile = {
"id": row[0],
"name": row[1],
"lang": row[2] or "DE",
"games_played": row[3] or 0,
"wins_vs_bots": row[4] or 0,
"losses_vs_bots": row[5] or 0,
"highscore": row[6] or 0
}
return profile, "OK"
@classmethod
def update_language(cls, profile_id: int, new_lang: str):
with cls.get_conn() as conn:
conn.execute("UPDATE profiles SET lang = ? WHERE id = ?", (new_lang, profile_id))
conn.commit()
@classmethod
def get_stats(cls, profile_id: int) -> dict:
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("""
SELECT games_played, wins_vs_bots, losses_vs_bots, highscore
FROM profiles WHERE id = ?
""", (profile_id,))
row = c.fetchone()
if not row:
return None
return {
"games_played": row[0] or 0,
"wins_vs_bots": row[1] or 0,
"losses_vs_bots": row[2] or 0,
"highscore": row[3] or 0
}
@classmethod
def record_game(cls, profile: dict, is_vs_bot: bool, won: bool, score: int):
profile_id = profile["id"]
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("""
SELECT games_played, wins_vs_bots, losses_vs_bots, highscore
FROM profiles WHERE id = ?
""", (profile_id,))
row = c.fetchone()
if not row:
return
gp, wins, losses, high = row[0] or 0, row[1] or 0, row[2] or 0, row[3] or 0
gp += 1
if is_vs_bot:
if won:
wins += 1
else:
losses += 1
if score > high:
high = score
c.execute("""
UPDATE profiles
SET games_played = ?, wins_vs_bots = ?, losses_vs_bots = ?, highscore = ?
WHERE id = ?
""", (gp, wins, losses, high, profile_id))
conn.commit()
profile["games_played"] = gp
profile["wins_vs_bots"] = wins
profile["losses_vs_bots"] = losses
profile["highscore"] = high
@classmethod
def save_bot_configs(cls, profile_id: int, configs_dict: dict):
raw_json = json.dumps(configs_dict)
with cls.get_conn() as conn:
conn.execute("UPDATE profiles SET bot_configs = ? WHERE id = ?", (raw_json, profile_id))
conn.commit()
@classmethod
def load_bot_configs(cls, profile_id: int) -> dict:
try:
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("SELECT bot_configs FROM profiles WHERE id = ?", (profile_id,))
row = c.fetchone()
if row and row[0]:
raw = json.loads(row[0])
return {int(k): (v[0], int(v[1])) for k, v in raw.items()}
except Exception:
pass
return {}
@classmethod
def save_game(cls, profile_id: int, state_json: str):
with cls.get_conn() as conn:
conn.execute(
"INSERT OR REPLACE INTO saves (profile_id, game_state) VALUES (?, ?)",
(profile_id, state_json)
)
conn.commit()
@classmethod
def load_game(cls, profile_id: int):
with cls.get_conn() as conn:
c = conn.cursor()
c.execute("SELECT game_state FROM saves WHERE profile_id = ?", (profile_id,))
row = c.fetchone()
return row[0] if row else None
@classmethod
def delete_save(cls, profile_id: int):
with cls.get_conn() as conn:
conn.execute("DELETE FROM saves WHERE profile_id = ?", (profile_id,))
conn.commit()