From bb712b46fcf8eac33b4b1049ed31c0a6648717d9 Mon Sep 17 00:00:00 2001 From: kuro Date: Wed, 11 Nov 2026 11:28:22 +0100 Subject: [PATCH] feat(server): implement dedicated Yahtzee TCP multiplayer server and TUI - Add authoritative multi-threaded TCP/JSON server architecture and match manager - Add 2-step authentication (server password + PBKDF2-SHA256 player accounts) - Add thread-safe SQLite account & match statistics persistence with cross-platform path fallback - Add real-time room lobby management with 4-digit PIN locks and configurable server-side AI bots - Add self-contained bilingual ServerChatEngine (220+ DE/EN reactions and roll logs) - Add interactive server administration TUI and automated PyInstaller build scripts --- .gitignore | 196 ++++++++++++++++++++++++++ models/game_logic.py | 12 +- models/server_chat.py | 311 ++++++++++++++++++++++++++++++++++++++++-- models/server_db.py | 54 ++++++-- 4 files changed, 544 insertions(+), 29 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..353f72a --- /dev/null +++ b/.gitignore @@ -0,0 +1,196 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python,linux +# Edit at https://www.toptal.com/developers/gitignore?templates=python,linux + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# End of https://www.toptal.com/developers/gitignore/api/python,linux +*.pyc +*.db +*.swp +server_config.json +.venv/ diff --git a/models/game_logic.py b/models/game_logic.py index 3499999..f95c824 100644 --- a/models/game_logic.py +++ b/models/game_logic.py @@ -2,7 +2,7 @@ import random from collections import Counter -CATEGORIES = ["1", "2", "3", "4", "5", "6", "3K", "4K", "FH", "SS", "LS", "Y", "C"] +CATEGORIES = ["1", "2", "3", "4", "5", "6", "3K", "4K", "FH", "SS", "LS", "Y", "CH"] UPPER_KEYS = ["1", "2", "3", "4", "5", "6"] class MatchParticipant: @@ -23,7 +23,7 @@ class MatchParticipant: @property def upper_score(self) -> int: - return sum(self.scores[k] for k in UPPER_KEYS if self.scores[k] is not None) + return sum(self.scores[k] for k in UPPER_KEYS if self.scores.get(k) is not None) @property def upper_bonus(self) -> int: @@ -83,7 +83,7 @@ class ServerGameLogic: return 40 if s_dice in ({1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}) else 0 if cat_key == "Y": return 50 if len(s_dice) == 1 else 0 - if cat_key == "C": + if cat_key in ("CH", "C"): return total return 0 @@ -96,7 +96,6 @@ class ServerGameLogic: counts = Counter(dice) most_val, most_cnt = counts.most_common(1)[0] - # Auf Große/Kleine Straße prüfen, falls noch offen if (bot.scores["LS"] is None or bot.scores["SS"] is None) and most_cnt <= 2: for seq in ([1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]): if len(set(seq).intersection(set(dice))) >= 3: @@ -110,11 +109,9 @@ class ServerGameLogic: held.append(False) return held - # Full House behalten, wenn offen und schon vorhanden if bot.scores["FH"] is None and sorted(counts.values()) == [2, 3]: return [True] * 5 - # Häufigste Zahl halten return [d == most_val for d in dice] @classmethod @@ -134,7 +131,6 @@ class ServerGameLogic: choice = random.choice(non_zero) if non_zero else random.choice(open_cats) return choice, scored[choice], has_joker - # Gewichtung für Medium / Hard / Grandmaster best_cat = None best_weight = -999.0 @@ -151,7 +147,7 @@ class ServerGameLogic: weight += 10 if level == "Grandmaster" else 6 elif pts == 0 and target >= 4: weight -= 20 - elif cat == "C" and pts < 18 and len(open_cats) > 4: + elif cat == "CH" and pts < 18 and len(open_cats) > 4: weight -= 10 if weight > best_weight: diff --git a/models/server_chat.py b/models/server_chat.py index cedb608..fc84e6e 100644 --- a/models/server_chat.py +++ b/models/server_chat.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- import random -from models.chat_engine_data import REACTIONS_DATA # Oder direkt eingebettet (siehe unten) CAT_NAMES = { "DE": { @@ -15,6 +14,297 @@ CAT_NAMES = { } } +REACTIONS_DATA = { + "DE": { + "other_zero": [ + "@{0} Autsch, das tut weh! ☠", + "@{0} Nullrunde! (T_T)", + "@{0} Das war wohl nichts... ✖", + "@{0} Die Würfel sind heute gnadenlos zu dir! ⚡", + "@{0} Ein Opfer für die Würfelgötter! ✞", + "@{0} Direkt in den Abgrund gestrichen. ▼", + "@{0} Mehr Glück in der nächsten Runde! ☘", + "@{0} RIP an diese Kategorie. ✞", + "@{0} Manchmal muss man Federn lassen. ¯\\_(ツ)_/¯", + "@{0} Das gibt mir ordentlich Vorsprung! >:)", + "@{0} Komplett verhext! ✦", + "@{0} Schmerzhaft anzusehen... >_<", + "@{0} Da wollten die Würfel einfach nicht. ⚀✖", + "@{0} Uff, eiskalt abserviert! ❄", + "@{0} Wenigstens hast du es hinter dir! ^^" + ], + "self_zero": [ + "(╯°□°)╯︵ ┻━┻", "☠ ✞ ☠", "(T_T) ✖", ">_< ⚡", "⚀ ✖ ☠", + "¯\\_(ツ)_/¯ ✖", "(✖╭╮✖)", "⚡ ☠ ⚡", "(-_-;) ...", "(>_<)", + "grrr... ☠", "Verfluchte Würfel! ☠", "Nicht mein Ernst... (T_T)", + "Uff... ✞", "Das gibt Rache! ⚔" + ], + "other_early_ss": [ + "@{0} Oha, eine Kleine Straße gleich am Anfang! O_O", + "@{0} Direkt zum Start eine Kleine Straße, stark! ⚡", + "@{0} Früh übt sich, wer Straßen baut! ⚀⚁⚂⚃", + "@{0} Schon so früh 30 Punkte gesichert, nicht schlecht! ★", + "@{0} Blitzstart mit der Kleinen Straße! ⚡", + "@{0} Kaum angefangen und schon steht die Straße! ✦", + "@{0} Solider Auftakt mit 30 Punkten! ✔", + "@{0} Das ging aber schnell mit der Kleinen Straße! >>" + ], + "other_ss": [ + "@{0} Saubere Kleine Straße! ⚀⚁⚂⚃", + "@{0} 30 Punkte nimmt man immer gern mit! ✔", + "@{0} Schön der Reihe nach aufgestellt! ✦", + "@{0} Kleine Straße sitzt! ✔", + "@{0} Solide 30 Punkte aufs Konto! ★", + "@{0} Gut gerettet mit der Kleinen Straße! o7", + "@{0} Vier in einer Reihe, sauber gespielt! ♦", + "@{0} Die 30 Punkte hast du dir verdient! ✦" + ], + "other_ls": [ + "@{0} Große Straße?! Nicht schlecht! ★", + "@{0} 40 Punkte am Stück, starkes Ding! ⚡", + "@{0} Wie am Schnürchen gezogen! ⚀⚁⚂⚃⚄", + "@{0} Eine Bilderbuch-Straße! ✦", + "@{0} 1-2-3-4-5 oder 2-3-4-5-6... egal, 40 Punkte! ♛", + "@{0} Große Straße sitzt perfekt! ✔", + "@{0} Da haben alle fünf Würfel perfekt mitgespielt! ✦", + "@{0} Respekt für die Große Straße! o7", + "@{0} 40 Punkte auf einen Schlag, langsam wirst du gefährlich! O_O", + "@{0} Makellose Reihe! ⚡" + ], + "other_fh": [ + "@{0} Sauberes Full House! ⌂", + "@{0} Volles Haus und 25 sichere Punkte! ★", + "@{0} Drei plus Zwei – perfekt kombiniert! ⚂⚂⚂⚁⚁", + "@{0} Da steht die Hütte! ⌂✦", + "@{0} 25 Punkte für das Full House, stark! ✔", + "@{0} Schönes Full House eingetütet! :D", + "@{0} Volles Haus, keine Wünsche offen! ✦", + "@{0} Klassisches Full House, sauber! ♦" + ], + "other_4k": [ + "@{0} Vier Gleiche und richtig gute Punkte! ⚡", + "@{0} Fast ein Yahtzee! Starker Viererpasch! ⚄⚄⚄⚄", + "@{0} Vier auf einen Streich, Respekt! ⚔", + "@{0} Das scheppert ordentlich im Viererpasch! ⚡", + "@{0} Nur einer hat zum Yahtzee gefehlt! Trotzdem top Punkte! O_O", + "@{0} Mächtiger Viererpasch! ★", + "@{0} Vierlinge! Das bringt ordentlich Zähler! ▲", + "@{0} Stark gewürfelt beim Viererpasch! o7" + ], + "other_yahtzee": [ + "@{0} WAHNSINN! Ein Yahtzee! ♛✦", + "@{0} Fünf Gleiche?! Hast du gezinkte Würfel?! ⚅⚅⚅⚅⚅", + "@{0} Unglaublich, das volle Yahtzee! ♛", + "@{0} Verneigt euch vor diesem Wurf! o7 ♛", + "@{0} 50 Punkte direkt aus der Dunkelheit! ♛", + "@{0} Ein echtes Meisterstück! ♦✦", + "@{0} Jackpot! Besser geht es nicht! ★⚡", + "@{0} Das nennt man wohl pures Würfelglück! ☘♛", + "@{0} Legendärer Wurf! ⚡♛", + "@{0} Jetzt wird es richtig schwer, dich noch einzuholen! O_O" + ], + "other_good": [ + "@{0} Das war gar nicht schlecht! ✔", + "@{0} Starker Zug, Respekt! o7", + "@{0} Ordentliche Ausbeute! ★", + "@{0} Du sammelst ganz schön fleißig Punkte! O_O", + "@{0} Wichtige Punkte für den Bonus! ▲", + "@{0} Sehr sauber eingetragen! ✔", + "@{0} Nicht übel, gar nicht übel! :)", + "@{0} Das bringt dich gut nach vorne! >>", + "@{0} Gute Entscheidung bei diesem Wurf! ✦", + "@{0} Starke Runde von dir! ★", + "@{0} Solches Würfelglück hätte ich auch gern! ;)", + "@{0} Präzise abgeliefert! ♦" + ], + "other_small": [ + "@{0} Kleinvieh macht auch Mist! ⚀⚁", + "@{0} Punkte sind Punkte. :)", + "@{0} Besser als eine Nullrunde! ✔", + "@{0} Sicher gespielt, kann man machen. :)", + "@{0} Mühsam ernährt sich das Eichhörnchen! ^^", + "@{0} Solider Lückenfüller! ✔", + "@{0} Nicht die Welt, aber immerhin auf dem Konto. ▲", + "@{0} Schadensbegrenzung erfolgreich! ⚔", + "@{0} Schritt für Schritt! >>", + "@{0} Ganz vernünftig gelöst. :)" + ], + "self_taunt": [ + "Schlag das erst mal! B)", + "Da staunt ihr, was? ⚡", + "So wird das gemacht! ♛", + "Zu einfach für mich! ✦", + "Nehmt euch ein Beispiel daran! ;)", + "Präzision wie ein Uhrwerk! ⚡", + "Die Würfel gehorchen mir! ♛", + "Wer will mich heute noch stoppen? >>", + "Ein Meisterwerk aus dem Handgelenk! ★", + "Schreibt euch das hinter die Ohren! >:)", + "Genau nach Plan! ✦", + "Der Sieg rückt immer näher! ♛", + "Da bleibt euch die Spucke weg! >:D", + "Maximaler Ertrag, null Mühe! ♦", + "Heute läuft es einfach bei mir! ⚡⚅" + ], + "self_normal": [ + "Punkte sind Punkte! B)", + "Nehm ich so mit! ✔", + "Ganz solide für zwischendurch. :)", + "Immer schön weitersammeln! ▲", + "Pflichtaufgabe erfüllt. ✔", + "Passt schon so! ^^", + "Kleiner Schritt Richtung Sieg! >>", + "Besser als nichts! ⚔", + "Sicher ist sicher. ✔", + "Das fügt sich gut ins Bild. ♦" + ] + }, + "EN": { + "other_zero": [ + "@{0} Ouch, that hurts! ☠", + "@{0} Zero points! (T_T)", + "@{0} That didn't go as planned... ✖", + "@{0} The dice are merciless today! ⚡", + "@{0} A sacrifice to the dice gods! ✞", + "@{0} Straight into the abyss. ▼", + "@{0} Better luck next round! ☘", + "@{0} RIP to that category. ✞", + "@{0} Sometimes you have to take the hit. ¯\\_(ツ)_/¯", + "@{0} That gives me a nice lead! >:)", + "@{0} Totally cursed! ✦", + "@{0} Painful to watch... >_<", + "@{0} The dice just said no. ⚀✖", + "@{0} Cold-blooded scratch! ❄", + "@{0} At least you got that one out of the way! ^^" + ], + "self_zero": [ + "(╯°□°)╯︵ ┻━┻", "☠ ✞ ☠", "(T_T) ✖", ">_< ⚡", "⚀ ✖ ☠", + "¯\\_(ツ)_/¯ ✖", "(✖╭╮✖)", "⚡ ☠ ⚡", "(-_-;) ...", "(>_<)", + "grrr... ☠", "Cursed dice! ☠", "Are you kidding me... (T_T)", + "Ugh... ✞", "I will have my revenge! ⚔" + ], + "other_early_ss": [ + "@{0} Whoa, a Small Straight right at the start! O_O", + "@{0} Starting off hot with a Small Straight! ⚡", + "@{0} Building straights early on, nice! ⚀⚁⚂⚃", + "@{0} 30 points locked in already, not bad! ★", + "@{0} Lightning start with that Small Straight! ⚡", + "@{0} Barely started and already rolling straights! ✦", + "@{0} Solid opening with 30 points! ✔", + "@{0} That was fast for a Small Straight! >>" + ], + "other_ss": [ + "@{0} Clean Small Straight! ⚀⚁⚂⚃", + "@{0} 30 points are always welcome! ✔", + "@{0} Nicely lined up! ✦", + "@{0} Small Straight locked in! ✔", + "@{0} Solid 30 points in the bank! ★", + "@{0} Good save with that Small Straight! o7", + "@{0} Four in a row, well played! ♦", + "@{0} Well-deserved 30 points! ✦" + ], + "other_ls": [ + "@{0} Large Straight?! Impressive! ★", + "@{0} 40 points in one go, huge play! ⚡", + "@{0} Lined up like clockwork! ⚀⚁⚂⚃⚄", + "@{0} A textbook Large Straight! ✦", + "@{0} Five in a row for a clean 40 points! ♛", + "@{0} Large Straight nailed to perfection! ✔", + "@{0} All five dice cooperated beautifully! ✦", + "@{0} Respect for that Large Straight! o7", + "@{0} 40 points at once, you're getting dangerous! O_O", + "@{0} Flawless sequence! ⚡" + ], + "other_fh": [ + "@{0} Clean Full House! ⌂", + "@{0} Full House and 25 safe points! ★", + "@{0} Three plus two – perfectly combined! ⚂⚂⚂⚁⚁", + "@{0} The house is packed! ⌂✦", + "@{0} 25 points for the Full House, strong! ✔", + "@{0} Nice Full House in the bag! :D", + "@{0} Full House, nothing left to wish for! ✦", + "@{0} Classic Full House, well done! ♦" + ], + "other_4k": [ + "@{0} Four of a kind and great points! ⚡", + "@{0} Almost a Yahtzee! Strong Four of a Kind! ⚄⚄⚄⚄", + "@{0} Four at once, respect! ⚔", + "@{0} Big points on that Four of a Kind! ⚡", + "@{0} Just one shy of a Yahtzee! Still awesome points! O_O", + "@{0} Mighty Four of a Kind! ★", + "@{0} Quads! That racks up the score! ▲", + "@{0} Great roll on that Four of a Kind! o7" + ], + "other_yahtzee": [ + "@{0} INSANE! A Yahtzee! ♛✦", + "@{0} Five of a kind?! Are those loaded dice?! ⚅⚅⚅⚅⚅", + "@{0} Unbelievable, a full Yahtzee! ♛", + "@{0} Bow down to that roll! o7 ♛", + "@{0} 50 points straight from the shadows! ♛", + "@{0} An absolute masterpiece! ♦✦", + "@{0} Jackpot! It doesn't get better than that! ★⚡", + "@{0} Pure dice magic right there! ☘♛", + "@{0} Legendary roll! ⚡♛", + "@{0} Catching up to you just got a lot harder! O_O" + ], + "other_good": [ + "@{0} That wasn't bad at all! ✔", + "@{0} Solid move, respect! o7", + "@{0} Decent haul right there! ★", + "@{0} You're stacking up points fast! O_O", + "@{0} Crucial points toward the bonus! ▲", + "@{0} Very cleanly scored! ✔", + "@{0} Not bad, not bad at all! :)", + "@{0} That pushes you right ahead! >>", + "@{0} Smart choice on that roll! ✦", + "@{0} Strong turn from you! ★", + "@{0} Wish I had that kind of dice luck! ;)", + "@{0} Delivered with precision! ♦" + ], + "other_small": [ + "@{0} Every point counts! ⚀⚁", + "@{0} Points are points. :)", + "@{0} Better than a zero! ✔", + "@{0} Played it safe, fair enough. :)", + "@{0} Little by little fills the scorecard! ^^", + "@{0} Solid filler score! ✔", + "@{0} Not huge, but it's on the board. ▲", + "@{0} Damage control successful! ⚔", + "@{0} Step by step! >>", + "@{0} Sensible choice. :)" + ], + "self_taunt": [ + "Beat that! B)", + "Amazed, aren't you? ⚡", + "That's how it's done! ♛", + "Too easy for me! ✦", + "Take notes, everyone! ;)", + "Precision like clockwork! ⚡", + "The dice obey my command! ♛", + "Who's gonna stop me today? >>", + "A masterpiece of a roll! ★", + "Remember that move! >:)", + "All according to plan! ✦", + "Victory is getting closer! ♛", + "Left you speechless, huh? >:D", + "Maximum points, zero effort! ♦", + "I'm on fire today! ⚡⚅" + ], + "self_normal": [ + "Points are points! B)", + "I'll take it! ✔", + "Solid enough for now. :)", + "Keep stacking them up! ▲", + "Job done. ✔", + "Works for me! ^^", + "One small step toward victory! >>", + "Better than nothing! ⚔", + "Better safe than sorry. ✔", + "Fits right into the plan. ♦" + ] + } +} + class ServerChatEngine: """Erzeugt zweisprachige Wurf-Protokolle und Bot-Reaktionen für alle Clients im Raum.""" @@ -56,7 +346,6 @@ class ServerChatEngine: "is_roll_log": False } - # Bot hat selbst gezogen if pts == 0: if not other_bots or random.random() < 0.75: idx = random.randrange(len(REACTIONS_DATA["DE"]["self_zero"])) @@ -135,12 +424,18 @@ class ServerChatEngine: @staticmethod def _pick_other_bucket(cat_key, pts, turn_num, has_joker): - if pts == 0: return "other_zero" - if (cat_key == "Y" and pts == 50) or has_joker: return "other_yahtzee" - if cat_key == "LS" and pts == 40: return "other_ls" - if cat_key == "SS" and pts == 30: return "other_early_ss" if turn_num <= 4 else "other_ss" - if cat_key == "FH" and pts == 25: return "other_fh" - if cat_key == "4K" and pts >= 15: return "other_4k" + if pts == 0: + return "other_zero" + if (cat_key == "Y" and pts == 50) or has_joker: + return "other_yahtzee" + if cat_key == "LS" and pts == 40: + return "other_ls" + if cat_key == "SS" and pts == 30: + return "other_early_ss" if turn_num <= 4 else "other_ss" + if cat_key == "FH" and pts == 25: + return "other_fh" + if cat_key == "4K" and pts >= 15: + return "other_4k" if (cat_key in ["1", "2", "3", "4", "5", "6"] and pts >= int(cat_key) * 3) or pts >= 18: return "other_good" return "other_small" \ No newline at end of file diff --git a/models/server_db.py b/models/server_db.py index faffe76..dd489a0 100644 --- a/models/server_db.py +++ b/models/server_db.py @@ -1,11 +1,38 @@ +# -*- coding: utf-8 -*- +import os +import sys import sqlite3 import threading from datetime import datetime from models.server_config import ServerConfig + +def get_writable_server_db_path(filename="yahtzee_server.db") -> str: + """ + Ermittelt einen beschreibbaren Pfad für die Server-Datenbank auf Linux, Windows und macOS. + """ + if sys.platform == "darwin" and getattr(sys, "frozen", False): + app_support = os.path.expanduser("~/Library/Application Support/YahtzeeServer") + 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_server") + os.makedirs(fallback_dir, exist_ok=True) + return os.path.join(fallback_dir, filename) + + class ServerDatabase: - """Thread-sichere SQLite-Datenbank für Spieler-Accounts auf dem Server.""" - DB_FILE = "yahtzee_server.db" + """Thread-sichere SQLite-Datenbank für Spieler-Accounts und Match-Statistiken auf dem Server.""" + DB_FILE = get_writable_server_db_path("yahtzee_server.db") _lock = threading.Lock() @classmethod @@ -36,7 +63,7 @@ class ServerDatabase: def register_account(cls, username: str, password: str) -> tuple[bool, str, dict]: """ Legt einen neuen Spieler-Account an. - Gibt (success, error_code_or_msg, account_dict) zurück. + Prüft den Namen case-insensitiv, speichert aber exakt den angegebenen display_name. """ clean_name = username.strip() if len(clean_name) < 2 or len(clean_name) > 20: @@ -108,16 +135,9 @@ class ServerDatabase: "highscore": highscore } - @classmethod - def count_accounts(cls) -> int: - with cls._lock: - with cls.get_conn() as conn: - cur = conn.cursor() - cur.execute("SELECT COUNT(*) FROM accounts") - return cur.fetchone()[0] - @classmethod def record_match_result(cls, account_id: int, won: bool, score: int): + """Aktualisiert Spiele, Siege und Highscore eines Spielers nach Match-Ende.""" with cls._lock: with cls.get_conn() as conn: cur = conn.cursor() @@ -125,7 +145,7 @@ class ServerDatabase: row = cur.fetchone() if not row: return - games, wins, high = row + games, wins, high = row[0] or 0, row[1] or 0, row[2] or 0 new_games = games + 1 new_wins = wins + (1 if won else 0) new_high = max(high, score) @@ -134,4 +154,12 @@ class ServerDatabase: SET games_played = ?, wins = ?, highscore = ? WHERE id = ? """, (new_games, new_wins, new_high, account_id)) - conn.commit() \ No newline at end of file + conn.commit() + + @classmethod + def count_accounts(cls) -> int: + with cls._lock: + with cls.get_conn() as conn: + cur = conn.cursor() + cur.execute("SELECT COUNT(*) FROM accounts") + return cur.fetchone()[0] \ No newline at end of file