the_goth_cardgame_collection/models/db_stats_repo.py

227 lines
9.0 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# models/db_stats_repo.py
from __future__ import annotations
import resources.code_res.sql_queries as sql
class DbStatsRepo:
"""
Kapselt spielgebundene Progression, Level-XP-Historie, Bot-Konfigurationen
sowie Varianten- & Goldbeutel-Statistiken.
"""
@staticmethod
def get_game_progress(db, profile_id: int, game_folder: str) -> dict:
from models.progression import Progression
db.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
row = db.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"]:
db.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder))
return info
@staticmethod
def get_profile_overall_progress(db, profile_id: int) -> dict:
"""Berechnet das übergreifende Profil-Gesamtlevel aus der Summe aller Spiel-XP."""
from models.progression import Progression
total_pts = int(db.fetch_val(sql.SELECT_PROFILE_TOTAL_POINTS, (profile_id,), default=0) or 0)
stats_all = DbStatsRepo.query_stats(db, "profile", profile_id)
info = Progression.get_level_info(total_pts, ever_deity=False)
info["games_played"] = stats_all["played"]
info["games_won"] = stats_all["won"]
info["win_pct"] = stats_all["win_pct"]
return info
@staticmethod
def get_recorded_game_level_avg_xp(
db, profile_id: int, game_folder: str, level_num: int
) -> int:
row = db.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"])
@staticmethod
def record_game_xp_with_history(
db, profile_id: int, game_folder: str, current_level: int, xp_gained: int
) -> None:
from models.progression import Progression
if xp_gained <= 0:
return
db.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
db.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder))
if current_level >= Progression.get_creator_spirit_v_level():
db.conn().execute(
sql.UPSERT_GAME_LEVEL_XP_HISTORY,
(profile_id, game_folder, int(current_level), int(xp_gained)),
)
@classmethod
def add_game_points(cls, db, profile_id: int, game_folder: str, points: int) -> None:
if points <= 0:
return
cur_prog = cls.get_game_progress(db, profile_id, game_folder)
with db.conn():
cls.record_game_xp_with_history(db, profile_id, game_folder, cur_prog["level"], int(points))
cls.get_game_progress(db, profile_id, game_folder)
@classmethod
def adjust_game_points(
cls, db, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0
) -> dict:
cur = cls.get_game_progress(db, profile_id, game_folder)
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
db.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
return cls.get_game_progress(db, profile_id, game_folder)
# --- Bot Configs ---
@staticmethod
def load_bot_configs(db, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]:
rows = db.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder))
return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows}
@staticmethod
def save_bot_configs(
db, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]
) -> None:
data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()]
db.execute_many(sql.UPSERT_BOT_CONFIG, data)
# --- Spielergebnisse & Varianten-Statistiken ---
@staticmethod
def upsert_stat(db, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float) -> None:
q = sql.STATS_SQL[scope]
cur = db.fetch_one(q["select_one"], (owner_id, variant_id))
dur = max(0.0, duration_sec)
if not cur:
db.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)
db.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,
db,
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,
) -> tuple[int, int]:
var_info = db.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(db, profile_id, game_folder)
old_lvl = prog_before["level"]
with db.conn():
if points_gained > 0:
cls.record_game_xp_with_history(db, profile_id, game_folder, old_lvl, int(points_gained))
cls.upsert_stat(db, "profile", profile_id, variant_id, won, duration_sec)
if bj_account_id is not None:
cls.upsert_stat(db, "bj_account", bj_account_id, variant_id, won, duration_sec)
if pk_account_id is not None:
cls.upsert_stat(db, "pk_account", pk_account_id, variant_id, won, duration_sec)
new_lvl = cls.get_game_progress(db, profile_id, game_folder)["level"]
return old_lvl, new_lvl
@staticmethod
def get_variants_for_filter(db, folder_path: str | None = None) -> list[dict]:
from resources.code_res.i18n import t
rows = (
db.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,))
if folder_path else db.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,
db,
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 = db.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 = row["current_streak"], row["longest_streak"]
best_t, total_t = row["best_time_sec"], row["total_time_sec"]
else:
row = (
db.fetch_one(q["aggregate_folder"], (owner_id, folder_path))
if folder_path is not None
else db.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 = row["c_streak"], row["l_streak"]
best_t, total_t = 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),
}
@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": "--:--",
}