yahtzee-py/models/database.py

175 lines
7.1 KiB
Python
Raw Normal View History

2026-11-02 18:32:36 +00:00
import sqlite3
2026-11-02 21:43:42 +00:00
from models.security import SecurityManager
from models.save_manager import SaveManager, DB_FILE
2026-11-02 18:32:36 +00:00
class Database:
2026-11-02 21:43:42 +00:00
"""Verwaltet Profile, Statistiken und bündelt Datenbankzugriffe."""
2026-11-02 18:32:36 +00:00
@staticmethod
def init_db():
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS profiles
(id INTEGER PRIMARY KEY, name TEXT UNIQUE, pass_hash TEXT, language TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS stats
(profile_id INTEGER PRIMARY KEY,
vs_real_wins INT, vs_real_loss INT, vs_real_avg REAL, vs_real_high INT,
vs_bot_wins INT, vs_bot_loss INT, vs_bot_avg REAL, vs_bot_high INT,
signature TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS saved_game
(profile_id INTEGER PRIMARY KEY, game_data TEXT)''')
2026-11-02 21:43:42 +00:00
c.execute('''CREATE TABLE IF NOT EXISTS bot_configs
(profile_id INTEGER, bot_index INTEGER, name TEXT, level INTEGER,
PRIMARY KEY(profile_id, bot_index))''')
2026-11-02 18:32:36 +00:00
conn.commit()
@staticmethod
def login_local(name):
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT id, language, pass_hash FROM profiles WHERE name=?", (name,))
result = c.fetchone()
if result:
prof_id, lang, pass_hash = result
c.execute("SELECT * FROM stats WHERE profile_id=?", (prof_id,))
s = c.fetchone()
if s:
2026-11-02 21:43:42 +00:00
stats_dict = {
'vr_w': s[1], 'vr_l': s[2], 'vr_avg': s[3], 'vr_h': s[4],
'vb_w': s[5], 'vb_l': s[6], 'vb_avg': s[7], 'vb_h': s[8]
}
sig = SecurityManager.generate_signature(stats_dict, pass_hash)
2026-11-02 18:32:36 +00:00
if sig != s[9]:
return None, "CORRUPT"
return {'id': prof_id, 'name': name, 'lang': lang, 'pass_hash': pass_hash}, "OK"
return None, "INVALID"
@staticmethod
def get_all_profile_names():
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT name FROM profiles")
2026-11-02 21:43:42 +00:00
return [row[0] for row in c.fetchall()]
2026-11-02 18:32:36 +00:00
@staticmethod
def create_profile(name, password, lang):
Database.init_db()
2026-11-02 21:43:42 +00:00
pass_hash = SecurityManager.hash_password(password)
2026-11-02 18:32:36 +00:00
try:
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("INSERT INTO profiles (name, pass_hash, language) VALUES (?, ?, ?)", (name, pass_hash, lang))
prof_id = c.lastrowid
2026-11-02 21:43:42 +00:00
init_stats = {'vr_w': 0, 'vr_l': 0, 'vr_avg': 0.0, 'vr_h': 0, 'vb_w': 0, 'vb_l': 0, 'vb_avg': 0.0, 'vb_h': 0}
sig = SecurityManager.generate_signature(init_stats, pass_hash)
2026-11-02 18:32:36 +00:00
c.execute('''INSERT INTO stats VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(prof_id, 0, 0, 0.0, 0, 0, 0, 0.0, 0, sig))
conn.commit()
return True
except sqlite3.IntegrityError:
2026-11-02 21:43:42 +00:00
return False
2026-11-02 18:32:36 +00:00
@staticmethod
def login(name, password):
Database.init_db()
2026-11-02 21:43:42 +00:00
pass_hash = SecurityManager.hash_password(password)
2026-11-02 18:32:36 +00:00
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT id, language FROM profiles WHERE name=? AND pass_hash=?", (name, pass_hash))
result = c.fetchone()
if result:
c.execute("SELECT * FROM stats WHERE profile_id=?", (result[0],))
s = c.fetchone()
if s:
2026-11-02 21:43:42 +00:00
stats_dict = {
'vr_w': s[1], 'vr_l': s[2], 'vr_avg': s[3], 'vr_h': s[4],
'vb_w': s[5], 'vb_l': s[6], 'vb_avg': s[7], 'vb_h': s[8]
}
sig = SecurityManager.generate_signature(stats_dict, pass_hash)
2026-11-02 18:32:36 +00:00
if sig != s[9]:
2026-11-02 21:43:42 +00:00
return None, "CORRUPT"
2026-11-02 18:32:36 +00:00
return {'id': result[0], 'name': name, 'lang': result[1], 'pass_hash': pass_hash}, "OK"
return None, "INVALID"
@staticmethod
def get_stats(profile_id):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT * FROM stats WHERE profile_id=?", (profile_id,))
return c.fetchone()
@staticmethod
def record_game(profile, is_vs_bot, won, score):
s = Database.get_stats(profile['id'])
2026-11-02 21:43:42 +00:00
if not s:
return
2026-11-02 18:32:36 +00:00
vr_w, vr_l, vr_avg, vr_h = s[1], s[2], s[3], s[4]
vb_w, vb_l, vb_avg, vb_h = s[5], s[6], s[7], s[8]
if is_vs_bot:
total_games = vb_w + vb_l
vb_w += 1 if won else 0
vb_l += 0 if won else 1
vb_avg = ((vb_avg * total_games) + score) / (total_games + 1)
vb_h = max(vb_h, score)
else:
total_games = vr_w + vr_l
vr_w += 1 if won else 0
vr_l += 0 if won else 1
vr_avg = ((vr_avg * total_games) + score) / (total_games + 1)
vr_h = max(vr_h, score)
2026-11-02 21:43:42 +00:00
stats_dict = {
'vr_w': vr_w, 'vr_l': vr_l, 'vr_avg': vr_avg, 'vr_h': vr_h,
'vb_w': vb_w, 'vb_l': vb_l, 'vb_avg': vb_avg, 'vb_h': vb_h
}
sig = SecurityManager.generate_signature(stats_dict, profile['pass_hash'])
2026-11-02 18:32:36 +00:00
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute('''UPDATE stats SET
vs_real_wins=?, vs_real_loss=?, vs_real_avg=?, vs_real_high=?,
vs_bot_wins=?, vs_bot_loss=?, vs_bot_avg=?, vs_bot_high=?, signature=?
WHERE profile_id=?''',
(vr_w, vr_l, vr_avg, vr_h, vb_w, vb_l, vb_avg, vb_h, sig, profile['id']))
conn.commit()
2026-11-02 21:43:42 +00:00
# --- Weiterleitungen an SaveManager ---
2026-11-02 18:32:36 +00:00
@staticmethod
def save_game(profile_id, game_state_json):
2026-11-02 21:43:42 +00:00
SaveManager.save_game(profile_id, game_state_json)
2026-11-02 18:32:36 +00:00
@staticmethod
def load_game(profile_id):
2026-11-02 21:43:42 +00:00
return SaveManager.load_game(profile_id)
2026-11-02 18:32:36 +00:00
@staticmethod
def delete_save(profile_id):
2026-11-02 21:43:42 +00:00
SaveManager.delete_save(profile_id)
2026-11-02 18:32:36 +00:00
@staticmethod
def save_bot_configs(profile_id, bot_configs_dict):
2026-11-02 21:43:42 +00:00
SaveManager.save_bot_configs(profile_id, bot_configs_dict)
2026-11-02 18:32:36 +00:00
@staticmethod
def load_bot_configs(profile_id):
2026-11-02 21:43:42 +00:00
return SaveManager.load_bot_configs(profile_id)
@staticmethod
def update_language(profile_id, lang):
2026-11-02 18:32:36 +00:00
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
2026-11-02 21:43:42 +00:00
c.execute("UPDATE profiles SET language=? WHERE id=?", (lang, profile_id))
conn.commit()
@staticmethod
def save_setting(key, value):
SaveManager.save_setting(key, value)
@staticmethod
def load_setting(key, default=None):
return SaveManager.load_setting(key, default)