the_goth_cardgame_collection/models/database.py

522 lines
22 KiB
Python
Raw Normal View History

2026-11-14 04:25:51 +00:00
# -*- coding: utf-8 -*-
# models/database.py
import os
2026-11-14 04:25:51 +00:00
import sqlite3
import sys
2026-11-14 04:25:51 +00:00
from pathlib import Path
import resources.code_res.sql_queries as sql
from resources.code_res.game_constants import (
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
)
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:
"""Persistenter Speicherort für user_data.db direkt neben der ausführbaren Datei."""
if getattr(sys, "frozen", False):
exe_dir = Path(sys.executable).resolve().parent
# Auf macOS (.app-Bundle) oder schreibgeschützten Pfaden wie /usr/local/bin ausweichen
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
USER_DB_PATH = USER_DATA_DIR / USER_DB_FILENAME
2026-11-14 04:25:51 +00:00
class Database:
_connection: sqlite3.Connection | None = None
@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!"
)
USER_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(str(USER_DB_PATH))
2026-11-14 04:25:51 +00:00
c.row_factory = sqlite3.Row
c.execute(sql.PRAGMA_FOREIGN_KEYS)
# Read-Only URI verhindert Schreib-Sperren in schreibgeschützten Bundle-Ordnern
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:
cls._connection.close()
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
@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()
@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)))
# --- 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,))
# --- 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)
# --- 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(
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, ""
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))
@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))
# --- 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]:
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]:
"""Gemeinsame Logik für streng spielgebundenen XP->Gold-Tausch inkl. Divine Punishment."""
2026-11-14 04:25:51 +00:00
from models.progression import Progression
from resources.code_res.i18n import t
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")
cost = prog["xp_exchange_cost"]
is_divine = prog["is_divine_punishment"]
2026-11-14 04:25:51 +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()
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:
new_points = max(0, prog["total_points"] - cost)
2026-11-14 04:25:51 +00:00
actual_deducted = cost
with cls.conn():
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
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,
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)
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")
@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": "--:--",
}