2026-11-14 04:25:51 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
# models/database.py
|
2026-11-22 03:26:44 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-11-16 18:51:29 +00:00
|
|
|
import os
|
2026-11-14 04:25:51 +00:00
|
|
|
import sqlite3
|
2026-11-16 18:51:29 +00:00
|
|
|
import sys
|
2026-11-14 04:25:51 +00:00
|
|
|
from pathlib import Path
|
2026-11-22 03:26:44 +00:00
|
|
|
|
2026-11-14 04:25:51 +00:00
|
|
|
import resources.code_res.sql_queries as sql
|
2026-11-22 03:26:44 +00:00
|
|
|
from models.db_locator import DbLocator
|
2026-11-14 04:25:51 +00:00
|
|
|
from resources.code_res.game_constants import (
|
2026-11-22 03:26:44 +00:00
|
|
|
BJ_DEFAULT_BET,
|
|
|
|
|
BJ_STARTING_GOLD,
|
|
|
|
|
DEVILS_DEAL_GOLD_REWARD,
|
|
|
|
|
GOLD_MAX_ACCOUNTS,
|
|
|
|
|
INTERNAL_DB_REL_PATH,
|
|
|
|
|
PK_STARTING_GOLD,
|
|
|
|
|
USER_DB_FILENAME,
|
|
|
|
|
XP_TO_GOLD_AMOUNT,
|
2026-11-14 04:25:51 +00:00
|
|
|
)
|
|
|
|
|
|
2026-11-16 18:51:29 +00:00
|
|
|
|
|
|
|
|
def _resolve_bundle_root() -> Path:
|
|
|
|
|
"""Pfad zu den gebündelten Read-Only-Ressourcen (PyInstaller _MEIPASS oder Projekt-Root)."""
|
|
|
|
|
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
|
|
|
|
return Path(sys._MEIPASS)
|
|
|
|
|
return Path(__file__).resolve().parent.parent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _resolve_user_data_dir() -> Path:
|
2026-11-22 03:26:44 +00:00
|
|
|
"""Fallback-Speicherort neben der ausführbaren Datei bzw. im Benutzerverzeichnis."""
|
2026-11-16 18:51:29 +00:00
|
|
|
if getattr(sys, "frozen", False):
|
|
|
|
|
exe_dir = Path(sys.executable).resolve().parent
|
|
|
|
|
if ".app/Contents/MacOS" not in str(exe_dir).replace("\\", "/") and os.access(exe_dir, os.W_OK):
|
|
|
|
|
return exe_dir
|
|
|
|
|
fallback_dir = Path.home() / ".local" / "share" / "TheGothCardgameCollection"
|
|
|
|
|
fallback_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
return fallback_dir
|
|
|
|
|
return Path(__file__).resolve().parent.parent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
BUNDLE_ROOT = _resolve_bundle_root()
|
|
|
|
|
USER_DATA_DIR = _resolve_user_data_dir()
|
|
|
|
|
|
|
|
|
|
INTERNAL_DB_PATH = BUNDLE_ROOT / INTERNAL_DB_REL_PATH
|
2026-11-22 03:26:44 +00:00
|
|
|
USER_DB_PATH = DbLocator.resolve_initial_db_path(USER_DATA_DIR)
|
2026-11-14 04:25:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class Database:
|
|
|
|
|
_connection: sqlite3.Connection | None = None
|
2026-11-22 03:26:44 +00:00
|
|
|
_active_user_db_path: Path = USER_DB_PATH
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_user_db_path(cls) -> Path:
|
|
|
|
|
return cls._active_user_db_path
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_user_db_dir(cls) -> Path:
|
|
|
|
|
return cls._active_user_db_path.parent
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _set_active_path_vars(cls, new_path: Path) -> None:
|
|
|
|
|
global USER_DB_PATH, USER_DATA_DIR
|
|
|
|
|
resolved = new_path.expanduser().resolve()
|
|
|
|
|
cls._active_user_db_path = resolved
|
|
|
|
|
USER_DB_PATH = resolved
|
|
|
|
|
USER_DATA_DIR = resolved.parent
|
2026-11-14 04:25:51 +00:00
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def conn(cls) -> sqlite3.Connection:
|
|
|
|
|
if cls._connection is None:
|
|
|
|
|
if not INTERNAL_DB_PATH.is_file():
|
|
|
|
|
raise FileNotFoundError(
|
|
|
|
|
f"Interne Stammdaten-DB fehlt: {INTERNAL_DB_PATH}. "
|
|
|
|
|
"Bitte zuerst das Seed-SQL mit deinem Query-Executor ausführen!"
|
|
|
|
|
)
|
2026-11-22 03:26:44 +00:00
|
|
|
cls._active_user_db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
c = sqlite3.connect(str(cls._active_user_db_path))
|
2026-11-14 04:25:51 +00:00
|
|
|
c.row_factory = sqlite3.Row
|
|
|
|
|
c.execute(sql.PRAGMA_FOREIGN_KEYS)
|
2026-11-16 18:51:29 +00:00
|
|
|
internal_uri = f"{INTERNAL_DB_PATH.resolve().as_uri()}?mode=ro"
|
|
|
|
|
try:
|
|
|
|
|
c.execute(sql.ATTACH_INTERNAL_DB, (internal_uri,))
|
|
|
|
|
except sqlite3.OperationalError:
|
|
|
|
|
c.execute(sql.ATTACH_INTERNAL_DB, (str(INTERNAL_DB_PATH),))
|
2026-11-14 04:25:51 +00:00
|
|
|
cls._connection = c
|
|
|
|
|
return cls._connection
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def close(cls):
|
|
|
|
|
if cls._connection is not None:
|
2026-11-22 03:26:44 +00:00
|
|
|
try:
|
|
|
|
|
cls._connection.close()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
2026-11-14 04:25:51 +00:00
|
|
|
cls._connection = None
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def execute(cls, query: str, params: tuple = ()) -> sqlite3.Cursor:
|
|
|
|
|
cur = cls.conn().execute(query, params)
|
|
|
|
|
cls.conn().commit()
|
|
|
|
|
return cur
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def execute_many(cls, query: str, seq_of_params) -> sqlite3.Cursor:
|
|
|
|
|
cur = cls.conn().executemany(query, seq_of_params)
|
|
|
|
|
cls.conn().commit()
|
|
|
|
|
return cur
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def fetch_one(cls, query: str, params: tuple = ()) -> dict | None:
|
|
|
|
|
row = cls.conn().execute(query, params).fetchone()
|
|
|
|
|
return dict(row) if row else None
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def fetch_all(cls, query: str, params: tuple = ()) -> list[dict]:
|
|
|
|
|
return [dict(r) for r in cls.conn().execute(query, params).fetchall()]
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def fetch_val(cls, query: str, params: tuple = (), default=None):
|
|
|
|
|
row = cls.conn().execute(query, params).fetchone()
|
|
|
|
|
return row[0] if row is not None else default
|
|
|
|
|
|
2026-11-22 03:26:44 +00:00
|
|
|
@classmethod
|
|
|
|
|
def _persist_self_location_in_db(cls, previous_path: Path | None = None) -> None:
|
|
|
|
|
"""Speichert den aktuellen kanonischen Dateipfad direkt in der DB selbst + im OS-Locator."""
|
|
|
|
|
cur_p = cls._active_user_db_path.resolve()
|
|
|
|
|
cls.save_setting("user_db_path", str(cur_p))
|
|
|
|
|
cls.save_setting("user_db_dir", str(cur_p.parent))
|
|
|
|
|
if previous_path is not None:
|
|
|
|
|
cls.save_setting("user_db_previous_path", str(previous_path.resolve()))
|
|
|
|
|
DbLocator.remember_db_path(cur_p)
|
|
|
|
|
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def init_db(cls):
|
|
|
|
|
cls.conn().executescript(sql.USER_SCHEMA_DDL)
|
|
|
|
|
bj_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_BJ_ACCOUNTS)]
|
|
|
|
|
if "devils_deal_active" not in bj_cols:
|
|
|
|
|
cls.conn().execute(sql.MIGRATE_ADD_DEVILS_ACTIVE)
|
|
|
|
|
cls.conn().commit()
|
2026-11-22 03:26:44 +00:00
|
|
|
cls._persist_self_location_in_db()
|
2026-11-14 04:25:51 +00:00
|
|
|
|
2026-11-22 03:26:44 +00:00
|
|
|
# ------------------------------------------------------------------
|
|
|
|
|
# NUTZERDATEN-PFAD WÄHLEN (ERST-START), LADEN & ATOMAR UMZIEHEN
|
|
|
|
|
# ------------------------------------------------------------------
|
|
|
|
|
@staticmethod
|
|
|
|
|
def validate_sqlite_file(candidate_file: Path) -> bool:
|
|
|
|
|
if not candidate_file.is_file():
|
|
|
|
|
return False
|
|
|
|
|
try:
|
|
|
|
|
with sqlite3.connect(f"{candidate_file.resolve().as_uri()}?mode=ro", uri=True) as test_c:
|
|
|
|
|
res = test_c.execute("PRAGMA integrity_check;").fetchone()
|
|
|
|
|
if not res or str(res[0]).lower() != "ok":
|
|
|
|
|
return False
|
|
|
|
|
tables = {
|
|
|
|
|
r[0]
|
|
|
|
|
for r in test_c.execute(
|
|
|
|
|
"SELECT name FROM sqlite_master WHERE type='table';"
|
|
|
|
|
).fetchall()
|
|
|
|
|
}
|
|
|
|
|
# Entweder frisch/leer oder gültige Goth-Cardgame-Nutzerdatenbank
|
|
|
|
|
return (not tables) or ("profiles" in tables and "settings" in tables)
|
|
|
|
|
except Exception:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def relocate_for_first_user(cls, target_dir_or_file: Path) -> Path:
|
|
|
|
|
"""
|
|
|
|
|
Wird beim Anlegen des allerersten lokalen Profils genutzt, falls der Nutzer
|
|
|
|
|
einen eigenen Zielordner gewählt hat. Entfernt eine leere Platzhalter-DB am alten Ort.
|
|
|
|
|
"""
|
|
|
|
|
target = target_dir_or_file.expanduser().resolve()
|
|
|
|
|
if target.is_dir() or target.suffix.lower() != ".db":
|
|
|
|
|
target = target / USER_DB_FILENAME
|
|
|
|
|
|
|
|
|
|
old_path = cls._active_user_db_path.resolve()
|
|
|
|
|
if target == old_path:
|
|
|
|
|
cls._persist_self_location_in_db()
|
|
|
|
|
return target
|
|
|
|
|
|
|
|
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
old_was_empty = (len(cls.get_profiles()) == 0)
|
|
|
|
|
cls.close()
|
|
|
|
|
|
|
|
|
|
cls._set_active_path_vars(target)
|
|
|
|
|
cls.init_db()
|
|
|
|
|
|
|
|
|
|
if old_was_empty and old_path.is_file() and old_path != target:
|
|
|
|
|
for suffix in ("", "-wal", "-shm"):
|
|
|
|
|
try:
|
|
|
|
|
Path(f"{old_path}{suffix}").unlink(missing_ok=True)
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
return target
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def switch_user_database(cls, existing_db_file: Path) -> tuple[bool, str]:
|
|
|
|
|
"""Lädt eine bestehende user_data.db von beliebigem Pfad und merkt sie in DB & Locator."""
|
|
|
|
|
cand = existing_db_file.expanduser().resolve()
|
|
|
|
|
if not cls.validate_sqlite_file(cand):
|
|
|
|
|
return False, "invalid_file"
|
|
|
|
|
|
|
|
|
|
prev_path = cls._active_user_db_path.resolve()
|
|
|
|
|
if cand == prev_path and cls._connection is not None:
|
|
|
|
|
cls._persist_self_location_in_db()
|
|
|
|
|
return True, str(cand)
|
|
|
|
|
|
|
|
|
|
cls.close()
|
|
|
|
|
try:
|
|
|
|
|
cls._set_active_path_vars(cand)
|
|
|
|
|
cls.init_db()
|
|
|
|
|
cls._persist_self_location_in_db(previous_path=prev_path)
|
|
|
|
|
return True, str(cand)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
cls.close()
|
|
|
|
|
cls._set_active_path_vars(prev_path)
|
|
|
|
|
cls.init_db()
|
|
|
|
|
return False, str(exc)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def move_user_database(cls, destination_dir: Path) -> tuple[bool, str]:
|
|
|
|
|
"""
|
|
|
|
|
Zieht die aktive user_data.db per konsistentem SQLite-Online-Backup in einen neuen
|
|
|
|
|
Ordner um, speichert den neuen Pfad in der DB + im Locator und räumt die alte Datei auf.
|
|
|
|
|
"""
|
|
|
|
|
dst_dir = destination_dir.expanduser().resolve()
|
|
|
|
|
dst_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
dst_file = (dst_dir / cls._active_user_db_path.name).resolve()
|
|
|
|
|
old_file = cls._active_user_db_path.resolve()
|
|
|
|
|
|
|
|
|
|
if dst_file == old_file:
|
|
|
|
|
cls._persist_self_location_in_db()
|
|
|
|
|
return True, str(dst_file)
|
|
|
|
|
|
|
|
|
|
tmp_file = dst_dir / f".{dst_file.name}.moving_tmp"
|
|
|
|
|
try:
|
|
|
|
|
tmp_file.unlink(missing_ok=True)
|
|
|
|
|
# Konsistentes Backup der laufenden Haupt-DB (inkl. ungeschriebener WAL-Seiten)
|
|
|
|
|
src_conn = cls.conn()
|
|
|
|
|
src_conn.commit()
|
|
|
|
|
with sqlite3.connect(str(tmp_file)) as backup_conn:
|
|
|
|
|
src_conn.backup(backup_conn, name="main")
|
|
|
|
|
|
|
|
|
|
if not cls.validate_sqlite_file(tmp_file):
|
|
|
|
|
tmp_file.unlink(missing_ok=True)
|
|
|
|
|
return False, "Backup verification failed"
|
|
|
|
|
|
|
|
|
|
cls.close()
|
|
|
|
|
if dst_file.is_file():
|
|
|
|
|
dst_file.unlink()
|
|
|
|
|
tmp_file.replace(dst_file)
|
|
|
|
|
|
|
|
|
|
cls._set_active_path_vars(dst_file)
|
|
|
|
|
cls.init_db()
|
|
|
|
|
cls._persist_self_location_in_db(previous_path=old_file)
|
|
|
|
|
|
|
|
|
|
# Alte DB-Dateien erst löschen, nachdem die neue DB aktiv & verifiziert ist
|
|
|
|
|
for suffix in ("", "-wal", "-shm"):
|
|
|
|
|
try:
|
|
|
|
|
Path(f"{old_file}{suffix}").unlink(missing_ok=True)
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
return True, str(dst_file)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
try:
|
|
|
|
|
tmp_file.unlink(missing_ok=True)
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
if cls._connection is None:
|
|
|
|
|
cls._set_active_path_vars(old_file)
|
|
|
|
|
cls.init_db()
|
|
|
|
|
return False, str(exc)
|
|
|
|
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
|
|
|
# ÜBERSETZUNGEN, PRESTIGE & SETTINGS
|
|
|
|
|
# ------------------------------------------------------------------
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def load_all_translations(cls) -> dict[str, dict[str, str]]:
|
|
|
|
|
out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}}
|
|
|
|
|
for r in cls.fetch_all(sql.SELECT_ALL_I18N):
|
|
|
|
|
out.setdefault(r["lang"], {})[r["key"]] = r["val"]
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def load_prestige_ranks(cls) -> list[dict]:
|
|
|
|
|
return cls.fetch_all(sql.SELECT_PRESTIGE_RANKS)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def load_setting(cls, key: str, default: str = "") -> str:
|
|
|
|
|
return cls.fetch_val(sql.SELECT_SETTING, (key,), default=default)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def save_setting(cls, key: str, value: str):
|
|
|
|
|
cls.execute(sql.UPSERT_SETTING, (key, str(value)))
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
# --- Profile ---
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_profiles(cls) -> list[str]:
|
|
|
|
|
return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)]
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_or_create_profile(cls, name: str) -> dict:
|
|
|
|
|
cls.execute(sql.INSERT_PROFILE_IGNORE, (name,))
|
|
|
|
|
return cls.fetch_one(sql.SELECT_PROFILE_BY_NAME, (name,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_profile_by_id(cls, profile_id: int) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,))
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
# --- Spielgebundene Progression ---
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
|
|
|
|
|
from models.progression import Progression
|
|
|
|
|
cls.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
|
|
|
|
|
row = cls.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder))
|
|
|
|
|
info = Progression.get_level_info(
|
|
|
|
|
row["points"],
|
|
|
|
|
profile_id=profile_id,
|
|
|
|
|
game_folder=game_folder,
|
|
|
|
|
ever_deity=bool(row["ever_reached_deity"]),
|
|
|
|
|
)
|
|
|
|
|
if info["ever_reached_deity"] and not row["ever_reached_deity"]:
|
|
|
|
|
cls.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder))
|
|
|
|
|
return info
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int:
|
|
|
|
|
row = cls.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num)))
|
|
|
|
|
if not row or row["games_count"] <= 0:
|
|
|
|
|
return 0
|
|
|
|
|
return int(row["total_xp_earned"] // row["games_count"])
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _record_game_xp_with_history(cls, profile_id: int, game_folder: str, current_level: int, xp_gained: int):
|
|
|
|
|
from models.progression import Progression
|
|
|
|
|
if xp_gained <= 0:
|
|
|
|
|
return
|
|
|
|
|
cls.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
|
|
|
|
|
cls.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder))
|
|
|
|
|
if current_level >= Progression.get_creator_spirit_v_level():
|
|
|
|
|
cls.conn().execute(
|
|
|
|
|
sql.UPSERT_GAME_LEVEL_XP_HISTORY,
|
|
|
|
|
(profile_id, game_folder, int(current_level), int(xp_gained))
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def add_game_points(cls, profile_id: int, game_folder: str, points: int):
|
|
|
|
|
if points <= 0:
|
|
|
|
|
return
|
|
|
|
|
cur_prog = cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
with cls.conn():
|
|
|
|
|
cls._record_game_xp_with_history(profile_id, game_folder, cur_prog["level"], int(points))
|
|
|
|
|
cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
|
|
|
|
|
cur = cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
|
|
|
|
|
cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
|
|
|
|
|
return cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
# --- Spielgebundener THE DEVIL'S DEAL (Blackjack & Poker jeweils autark!) ---
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
|
|
|
|
|
from models.progression import Progression
|
|
|
|
|
min_lvl = Progression.get_devils_deal_min_level()
|
|
|
|
|
eligible = []
|
|
|
|
|
for row in cls.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)):
|
|
|
|
|
info = Progression.get_level_info(row["points"])
|
|
|
|
|
if info["level"] >= min_lvl:
|
|
|
|
|
eligible.append({
|
|
|
|
|
"id": row["id"],
|
|
|
|
|
"name": row["name"],
|
|
|
|
|
"level": info["level"],
|
|
|
|
|
"title": info["title"],
|
|
|
|
|
})
|
|
|
|
|
return eligible
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def execute_devils_deal(
|
2026-11-14 21:47:38 +00:00
|
|
|
cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int
|
2026-11-14 04:25:51 +00:00
|
|
|
) -> tuple[bool, str]:
|
|
|
|
|
from resources.code_res.i18n import t
|
|
|
|
|
candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)}
|
|
|
|
|
victim = candidates.get(sacrifice_profile_id)
|
|
|
|
|
if not victim:
|
|
|
|
|
return False, ""
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
if game_folder == "poker":
|
|
|
|
|
with cls.conn():
|
|
|
|
|
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
|
|
|
|
|
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
|
|
|
|
|
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1, account_id))
|
|
|
|
|
acc = cls.get_poker_account(account_id)
|
|
|
|
|
else:
|
|
|
|
|
with cls.conn():
|
|
|
|
|
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
|
|
|
|
|
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
|
|
|
|
|
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, account_id))
|
|
|
|
|
acc = cls.get_blackjack_account(account_id)
|
2026-11-14 04:25:51 +00:00
|
|
|
|
|
|
|
|
return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"])
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_active_devils_bj_account(cls, profile_id: int) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
|
|
|
|
|
cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id))
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_PK_ACCOUNT, (profile_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
|
|
|
|
|
cls.execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1 if active else 0, pk_account_id))
|
|
|
|
|
|
2026-11-14 04:25:51 +00:00
|
|
|
# --- Savegames ---
|
|
|
|
|
@classmethod
|
|
|
|
|
def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str):
|
|
|
|
|
cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def load_game_state(cls, profile_id: int, game_folder: str) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_SAVEGAME, (profile_id, game_folder))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def delete_game_state(cls, profile_id: int, game_folder: str):
|
|
|
|
|
cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder))
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
# --- Blackjack Gold-Konten ---
|
2026-11-14 04:25:51 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
|
|
|
|
|
return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_blackjack_account(cls, bj_account_id: int) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict:
|
|
|
|
|
from resources.code_res.i18n import t
|
|
|
|
|
clean_name = account_name.strip()
|
|
|
|
|
if not clean_name:
|
|
|
|
|
raise ValueError(t("bj_err_empty_name"))
|
|
|
|
|
if len(cls.get_blackjack_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
|
|
|
|
|
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
|
|
|
|
|
cls.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET))
|
|
|
|
|
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
|
|
|
|
|
if last_bet is not None:
|
|
|
|
|
cls.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id))
|
|
|
|
|
else:
|
|
|
|
|
cls.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id))
|
|
|
|
|
return cls.get_blackjack_account(bj_account_id)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def save_blackjack_last_bet(cls, bj_account_id: int, bet: int):
|
|
|
|
|
cls.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def delete_blackjack_account(cls, bj_account_id: int):
|
|
|
|
|
cls.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
|
2026-11-14 21:47:38 +00:00
|
|
|
return cls._exchange_game_xp_for_gold(profile_id, "blackjack", bj_account_id)
|
|
|
|
|
|
|
|
|
|
# --- Poker Gold-Konten (autarke Bankroll + eigener XP-Tausch!) ---
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
|
|
|
|
|
return cls.fetch_all(sql.SELECT_PK_ACCOUNTS_BY_PROFILE, (profile_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_poker_account(cls, pk_account_id: int) -> dict | None:
|
|
|
|
|
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_ID, (pk_account_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
|
|
|
|
|
from resources.code_res.i18n import t
|
|
|
|
|
clean_name = account_name.strip()
|
|
|
|
|
if not clean_name:
|
|
|
|
|
raise ValueError(t("bj_err_empty_name"))
|
|
|
|
|
if len(cls.get_poker_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
|
|
|
|
|
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
|
|
|
|
|
cls.execute(sql.INSERT_PK_ACCOUNT, (profile_id, clean_name, PK_STARTING_GOLD))
|
|
|
|
|
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_NAME, (profile_id, clean_name))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
|
|
|
|
|
cls.execute(sql.UPDATE_PK_GOLD_ONLY, (int(gold_delta), pk_account_id))
|
|
|
|
|
return cls.get_poker_account(pk_account_id)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def delete_poker_account(cls, pk_account_id: int):
|
|
|
|
|
cls.execute(sql.DELETE_PK_ACCOUNT, (pk_account_id,))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
|
|
|
|
|
return cls._exchange_game_xp_for_gold(profile_id, "poker", pk_account_id)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _exchange_game_xp_for_gold(cls, profile_id: int, game_folder: str, account_id: int) -> tuple[bool, str]:
|
2026-11-14 04:25:51 +00:00
|
|
|
from models.progression import Progression
|
|
|
|
|
from resources.code_res.i18n import t
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
prog = cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
if prog.get("at_divine_floor"):
|
2026-11-14 04:25:51 +00:00
|
|
|
return False, t("bj_err_floor_reached")
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
cost = prog["xp_exchange_cost"]
|
|
|
|
|
is_divine = prog["is_divine_punishment"]
|
2026-11-14 04:25:51 +00:00
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
if not is_divine and prog["total_points"] < cost:
|
|
|
|
|
return False, t("bj_err_not_enough_xp", prog["total_points"], cost)
|
2026-11-14 04:25:51 +00:00
|
|
|
|
|
|
|
|
if is_divine:
|
|
|
|
|
floor_xp = Progression.get_creator_spirit_v_floor_xp()
|
2026-11-14 21:47:38 +00:00
|
|
|
new_points = max(floor_xp, prog["total_points"] - cost)
|
|
|
|
|
actual_deducted = prog["total_points"] - new_points
|
2026-11-14 04:25:51 +00:00
|
|
|
if actual_deducted <= 0:
|
|
|
|
|
return False, t("bj_err_floor_reached")
|
|
|
|
|
else:
|
2026-11-14 21:47:38 +00:00
|
|
|
new_points = max(0, prog["total_points"] - cost)
|
2026-11-14 04:25:51 +00:00
|
|
|
actual_deducted = cost
|
|
|
|
|
|
|
|
|
|
with cls.conn():
|
2026-11-14 21:47:38 +00:00
|
|
|
cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, game_folder))
|
|
|
|
|
if game_folder == "poker":
|
|
|
|
|
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
|
|
|
|
|
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (0, account_id))
|
|
|
|
|
acc = cls.get_poker_account(account_id)
|
|
|
|
|
else:
|
|
|
|
|
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
|
|
|
|
|
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, account_id))
|
|
|
|
|
acc = cls.get_blackjack_account(account_id)
|
2026-11-14 04:25:51 +00:00
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
updated_prog = cls.get_game_progress(profile_id, game_folder)
|
2026-11-14 04:25:51 +00:00
|
|
|
if is_divine:
|
|
|
|
|
return True, t(
|
|
|
|
|
"bj_exchange_divine_success",
|
|
|
|
|
XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"]
|
|
|
|
|
)
|
|
|
|
|
return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted)
|
|
|
|
|
|
|
|
|
|
# --- Bot Configs & Statistiken ---
|
|
|
|
|
@classmethod
|
|
|
|
|
def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]:
|
|
|
|
|
rows = cls.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder))
|
|
|
|
|
return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows}
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]):
|
|
|
|
|
data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()]
|
|
|
|
|
cls.execute_many(sql.UPSERT_BOT_CONFIG, data)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _upsert_stat(cls, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float):
|
|
|
|
|
q = sql.STATS_SQL[scope]
|
|
|
|
|
cur = cls.fetch_one(q["select_one"], (owner_id, variant_id))
|
|
|
|
|
dur = max(0.0, duration_sec)
|
|
|
|
|
|
|
|
|
|
if not cur:
|
|
|
|
|
cls.conn().execute(q["insert"], (
|
|
|
|
|
owner_id, variant_id,
|
|
|
|
|
1 if won else 0, 0 if won else 1,
|
|
|
|
|
1 if won else 0, 1 if won else 0,
|
|
|
|
|
dur if won else None, dur,
|
|
|
|
|
))
|
|
|
|
|
else:
|
|
|
|
|
c_streak = (cur["current_streak"] + 1) if won else 0
|
|
|
|
|
best_t = cur["best_time_sec"]
|
|
|
|
|
if won:
|
|
|
|
|
best_t = dur if best_t is None else min(best_t, dur)
|
|
|
|
|
cls.conn().execute(q["update"], (
|
|
|
|
|
cur["games_played"] + 1,
|
|
|
|
|
cur["games_won"] + (1 if won else 0),
|
|
|
|
|
cur["games_lost"] + (0 if won else 1),
|
|
|
|
|
c_streak,
|
|
|
|
|
max(cur["longest_streak"], c_streak),
|
|
|
|
|
best_t,
|
|
|
|
|
cur["total_time_sec"] + dur,
|
|
|
|
|
owner_id, variant_id,
|
|
|
|
|
))
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def record_game_result(
|
|
|
|
|
cls,
|
|
|
|
|
profile_id: int,
|
|
|
|
|
variant_key: str,
|
|
|
|
|
won: bool,
|
|
|
|
|
duration_sec: float,
|
|
|
|
|
points_gained: int = 0,
|
2026-11-14 21:47:38 +00:00
|
|
|
bj_account_id: int | None = None,
|
|
|
|
|
pk_account_id: int | None = None,
|
2026-11-14 04:25:51 +00:00
|
|
|
) -> tuple[int, int]:
|
|
|
|
|
var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,))
|
|
|
|
|
if not var_info:
|
|
|
|
|
raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}")
|
|
|
|
|
|
|
|
|
|
variant_id = var_info["id"]
|
|
|
|
|
game_folder = var_info["folder_path"]
|
|
|
|
|
|
|
|
|
|
prog_before = cls.get_game_progress(profile_id, game_folder)
|
|
|
|
|
old_lvl = prog_before["level"]
|
|
|
|
|
|
|
|
|
|
with cls.conn():
|
|
|
|
|
if points_gained > 0:
|
|
|
|
|
cls._record_game_xp_with_history(profile_id, game_folder, old_lvl, int(points_gained))
|
|
|
|
|
cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec)
|
|
|
|
|
if bj_account_id is not None:
|
|
|
|
|
cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec)
|
2026-11-14 21:47:38 +00:00
|
|
|
if pk_account_id is not None:
|
|
|
|
|
cls._upsert_stat("pk_account", pk_account_id, variant_id, won, duration_sec)
|
2026-11-14 04:25:51 +00:00
|
|
|
|
|
|
|
|
new_lvl = cls.get_game_progress(profile_id, game_folder)["level"]
|
|
|
|
|
return old_lvl, new_lvl
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]:
|
|
|
|
|
from resources.code_res.i18n import t
|
|
|
|
|
rows = (
|
|
|
|
|
cls.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,))
|
|
|
|
|
if folder_path else cls.fetch_all(sql.SELECT_ALL_VARIANTS)
|
|
|
|
|
)
|
|
|
|
|
for d in rows:
|
|
|
|
|
d["translated_name"] = t(f"variant_{d['variant_key']}")
|
|
|
|
|
return rows
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _query_stats(cls, scope: str, owner_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
|
|
|
|
|
q = sql.STATS_SQL[scope]
|
|
|
|
|
if variant_id is not None:
|
|
|
|
|
row = cls.fetch_one(q["select_one"], (owner_id, variant_id))
|
|
|
|
|
if not row or row["games_played"] == 0:
|
|
|
|
|
return cls._empty_stats()
|
|
|
|
|
played, won, lost = row["games_played"], row["games_won"], row["games_lost"]
|
|
|
|
|
c_streak, l_streak, best_t, total_t = row["current_streak"], row["longest_streak"], row["best_time_sec"], row["total_time_sec"]
|
|
|
|
|
else:
|
|
|
|
|
row = (
|
|
|
|
|
cls.fetch_one(q["aggregate_folder"], (owner_id, folder_path))
|
|
|
|
|
if folder_path is not None
|
|
|
|
|
else cls.fetch_one(q["aggregate_all"], (owner_id,))
|
|
|
|
|
)
|
|
|
|
|
if not row or row["played"] == 0:
|
|
|
|
|
return cls._empty_stats()
|
|
|
|
|
played, won, lost = row["played"], row["won"], row["lost"]
|
|
|
|
|
c_streak, l_streak, best_t, total_t = row["c_streak"], row["l_streak"], row["best_time"], row["total_time"]
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"played": played,
|
|
|
|
|
"won": won,
|
|
|
|
|
"lost": lost,
|
|
|
|
|
"win_pct": f"{(won / played * 100.0):.1f} %",
|
|
|
|
|
"current_streak": c_streak,
|
|
|
|
|
"longest_streak": l_streak,
|
|
|
|
|
"best_time": cls.format_seconds(best_t),
|
|
|
|
|
"avg_time": cls.format_seconds(total_t / played),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
|
|
|
|
|
return cls._query_stats("profile", profile_id, variant_id=variant_id, folder_path=folder_path)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict:
|
|
|
|
|
return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
|
|
|
|
|
|
2026-11-14 21:47:38 +00:00
|
|
|
@classmethod
|
|
|
|
|
def get_pk_account_stats_overview(cls, pk_account_id: int, variant_id: int | None = None) -> dict:
|
|
|
|
|
return cls._query_stats("pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
|
|
|
|
|
|
2026-11-14 04:25:51 +00:00
|
|
|
@staticmethod
|
|
|
|
|
def format_seconds(sec: float | None) -> str:
|
|
|
|
|
if sec is None:
|
|
|
|
|
return "--:--"
|
|
|
|
|
mins, secs = divmod(int(round(sec)), 60)
|
|
|
|
|
if mins >= 60:
|
|
|
|
|
hrs, mins = divmod(mins, 60)
|
|
|
|
|
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
|
|
|
|
|
return f"{mins:02d}:{secs:02d}"
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _empty_stats() -> dict:
|
|
|
|
|
return {
|
|
|
|
|
"played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %",
|
|
|
|
|
"current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--",
|
|
|
|
|
}
|