diff --git a/build_all.sh b/build_all.sh new file mode 100755 index 0000000..f61577e --- /dev/null +++ b/build_all.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -e + +APP_NAME="Yahtzee" +MAIN_FILE="main.py" +RES_DIR="ressources" + +echo "====================================================" +echo " 🦇 Starte Multi-Plattform Build für $APP_NAME" +echo "====================================================" + +# ---------------------------------------------------- +# TEIL 1: LINUX EXECUTABLE BAUEN +# ---------------------------------------------------- +echo "" +echo "---> [1/2] Baue Linux Executable..." + +# Prüfen, ob eine virtuelle Umgebung (.venv / venv) existiert, sonst System-pip nutzen +if [ -d ".venv" ]; then + LINUX_PY=".venv/bin/python3" +elif [ -d "venv" ]; then + LINUX_PY="venv/bin/python3" +else + LINUX_PY="python3" +fi + +# Sicherstellen, dass PyInstaller und Pillow unter Linux installiert sind +$LINUX_PY -m pip install --upgrade pillow pyinstaller --break-system-packages 2>/dev/null || $LINUX_PY -m pip install --upgrade pillow pyinstaller + +# WICHTIG: Unter Linux wird bei --add-data ein Doppelpunkt (:) als Trennzeichen genutzt! +$LINUX_PY -m PyInstaller \ + --noconsole \ + --onefile \ + --clean \ + --distpath "dist/linux" \ + --workpath "build/linux" \ + --add-data "${RES_DIR}:${RES_DIR}" \ + --name "${APP_NAME}_Linux" \ + "$MAIN_FILE" + +chmod +x "dist/linux/${APP_NAME}_Linux" +echo "✔ Linux-Build fertig: dist/linux/${APP_NAME}_Linux" + + +# ---------------------------------------------------- +# TEIL 2: WINDOWS .EXE BAUEN (VIA WINE) +# ---------------------------------------------------- +echo "" +echo "---> [2/2] Baue Windows .exe (via Wine)..." + +if ! command -v wine &> /dev/null; then + echo "❌ Fehler: 'wine' ist unter Linux noch nicht installiert!" + echo "Bitte führe erst 'sudo apt update && sudo apt install wine' aus." + exit 1 +fi + +# Suche nach einer vorhandenen python.exe innerhalb von Wine +WINE_PY=$(find ~/.wine/drive_c -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true) + +# Falls Windows-Python noch nicht in Wine installiert ist -> automatisch installieren +if [ -z "$WINE_PY" ]; then + echo "⚙️ Windows-Python wurde in Wine noch nicht gefunden. Installiere Python 3.11.9 automatisch..." + INSTALLER="python-3.11.9-amd64.exe" + if [ ! -f "$INSTALLER" ]; then + wget -O "$INSTALLER" https://www.python.org/ftp/python/3.11.9/python-3.11.9-amd64.exe + fi + wine "$INSTALLER" /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 + wineserver -w + rm -f "$INSTALLER" + WINE_PY=$(find ~/.wine/drive_c -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true) +fi + +if [ -z "$WINE_PY" ]; then + echo "❌ Konnte python.exe in Wine nicht finden!" + exit 1 +fi + +echo "✔ Nutze Wine-Python: $WINE_PY" + +# Pillow und PyInstaller in Wine-Python installieren +wine "$WINE_PY" -m pip install --upgrade pip pillow pyinstaller + +# WICHTIG: Unter Windows/Wine wird bei --add-data ein Semikolon (;) genutzt! +wine "$WINE_PY" -m PyInstaller \ + --noconsole \ + --onefile \ + --clean \ + --distpath "dist/windows" \ + --workpath "build/windows" \ + --add-data "${RES_DIR};${RES_DIR}" \ + --name "${APP_NAME}" \ + "$MAIN_FILE" + +# Aufräumen der temporären .spec Dateien +rm -f "${APP_NAME}.spec" "${APP_NAME}_Linux.spec" + +echo "" +echo "====================================================" +echo " ✅ BUILD ERFOLGREICH ABGESCHLOSSEN!" +echo " 🐧 Linux-Version: dist/linux/${APP_NAME}_Linux" +echo " 🪟 Windows-Version: dist/windows/${APP_NAME}.exe" +echo "====================================================" diff --git a/controllers/__pycache__/gui_ctrl.cpython-313.pyc b/controllers/__pycache__/gui_ctrl.cpython-313.pyc index 56d8f82..090a7bd 100644 Binary files a/controllers/__pycache__/gui_ctrl.cpython-313.pyc and b/controllers/__pycache__/gui_ctrl.cpython-313.pyc differ diff --git a/controllers/gui_ctrl.py b/controllers/gui_ctrl.py index 6b939f5..bfc1835 100644 --- a/controllers/gui_ctrl.py +++ b/controllers/gui_ctrl.py @@ -1,4 +1,5 @@ import json +import random from models.game import GameModel from models.player import Player from models.database import Database @@ -6,6 +7,7 @@ from models.constants import CATEGORIES import models.i18n as i18n from models.i18n import t from views.gui_view import YahtzeeView +from models.chat_engine import ChatEngine class GuiController: def __init__(self): @@ -70,7 +72,14 @@ class GuiController: self.model.players[idx + 1].name = name self.current_player_idx = 0 + self.view.clear_chat_history() self.view.init_game_ui() + + bots = [p for p in self.model.players if p.is_bot] + if bots: + welcome_txt = "Mach dich bereit! ⚔ ⚅" if i18n.CURRENT_LANG == "DE" else "Get ready! ⚔ ⚅" + self.view.add_chat_message(bots[0].name, welcome_txt, is_self_taunt=True) + self.start_turn() def discard_and_return_menu(self): @@ -106,16 +115,30 @@ class GuiController: self.show_main_menu() def end_game(self): + self.view.hide_centered_overlay() Database.delete_save(self.active_profile['id']) players_sorted = sorted(self.model.players, key=lambda p: p.total_score, reverse=True) - won = (players_sorted[0] == self.model.players[0]) - human_score = self.model.players[0].total_score + human_player = self.model.players[0] + winner_player = players_sorted[0] + won = (winner_player == human_player) + human_score = human_player.total_score has_bots = any(p.is_bot for p in self.model.players) Database.record_game(self.active_profile, is_vs_bot=has_bots, won=won, score=human_score) + # Am Spielende bis zu 8 Nachrichten erlauben! + self.view.set_chat_endgame_mode(True) + scoreboard_display = [(p.display_name, p.total_score) for p in players_sorted] - self.view.show_game_over_dialog(scoreboard_display, on_close=self.show_main_menu) + self.view.show_game_over_dialog(scoreboard_display, human_won=won, on_close=self.show_main_menu) + + end_msgs = ChatEngine.generate_endgame_reactions(human_player, self.model.players, winner_player) + for idx, (sender, txt, is_taunt) in enumerate(end_msgs): + delay = 350 + idx * 550 + self.view.after( + delay, + lambda s=sender, m=txt, t_flag=is_taunt: self.view.add_chat_message(s, m, is_self_taunt=t_flag) + ) def toggle_die(self, idx): if getattr(self, 'input_locked', False): @@ -143,6 +166,9 @@ class GuiController: self.view.show_centered_overlay(t("bot_thinking", player.display_name)) self.view.after(2000, lambda: self.execute_bot_logic(player)) else: + self.view.hide_centered_overlay() + # Bots sind fertig -> Chat-Banner nach 3.5 Sekunden automatisch ausblenden! + self.view.schedule_chat_hide(3500) self.view.enable_input() self.model.held = [False] * 5 self.model.rolls_left = 3 @@ -154,8 +180,54 @@ class GuiController: player = self.model.players[self.current_player_idx] if player.is_bot or self.model.rolls_left <= 0: return - self.model.held = self.view.get_held_dice() - self.view.trigger_roll_animation(is_bot=False, callback=self.on_human_roll_done) + + held = self.view.get_held_dice() + self.model.held = held + + warn_header, warn_msg = self._check_roll_warnings(player, self.model.dice, held) + if warn_header: + self.view.ask_roll_warning_confirm( + warn_header, warn_msg, + on_confirm=lambda: self.view.trigger_roll_animation(is_bot=False, callback=self.on_human_roll_done) + ) + else: + self.view.trigger_roll_animation(is_bot=False, callback=self.on_human_roll_done) + + def _check_roll_warnings(self, player, dice, held): + if all(held): + return None, None + + is_yz = len(set(dice)) == 1 + has_joker = is_yz and player.scores["Y"] == 50 + + fh_open = player.scores["FH"] is None and self.model.calculate_score("FH", dice, has_joker) == 25 + ls_open = player.scores["LS"] is None and self.model.calculate_score("LS", dice, has_joker) == 40 + ss_open = player.scores["SS"] is None and self.model.calculate_score("SS", dice, has_joker) == 30 + + if self.model.calculate_score("SS", dice, has_joker) == 30 and player.scores["LS"] is None and not ls_open: + for seq in ([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]): + if set(seq).issubset(set(dice)): + held_values = [dice[i] for i in range(5) if held[i]] + if not all(v in held_values for v in seq): + seq_str = "-".join(str(x) for x in seq) + return t("roll_warn_ls_header"), t("roll_warn_ls_msg", t("cat_SS"), seq_str) + + ready_combos = [] + if ls_open: + ready_combos.append(f"{t('cat_LS')} (40)") + if fh_open: + ready_combos.append(f"{t('cat_FH')} (25)") + if ss_open: + kept_vals = set(dice[i] for i in range(5) if held[i]) + keeps_ss = any(s.issubset(kept_vals) for s in [{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}]) + if not keeps_ss: + ready_combos.append(f"{t('cat_SS')} (30)") + + if ready_combos: + combo_str = " / ".join(ready_combos) + return t("roll_warn_combo_header"), t("roll_warn_combo_msg", combo_str) + + return None, None def on_human_roll_done(self): self.model.roll_unheld() @@ -163,12 +235,16 @@ class GuiController: self.view.update_scoreboard() player = self.model.players[self.current_player_idx] - is_yz = len(set(self.model.dice)) == 1 + dice = self.model.dice + is_yz = len(set(dice)) == 1 + + # Nur beim ersten Yahtzee wird sofort automatisch eingetragen und gratuliert if is_yz and player.scores["Y"] is None: self.input_locked = True self.view.disable_input() player.scores["Y"] = 50 self.view.update_scoreboard() + self._trigger_chat_reaction(player, "Y", 50, has_joker=False) self.view.show_achievement_banner("yahtzee", on_close=self.next_player) def score_category(self, cat_key): @@ -200,6 +276,20 @@ class GuiController: else: self._apply_score(player, cat_key, pts, has_joker) + def _trigger_chat_reaction(self, actor, cat_key, pts, has_joker=False): + """Erzeugt erst NACH dem Eintragen einer Kategorie eine passende Chat-Nachricht.""" + res = ChatEngine.generate_reaction( + actor=actor, + all_players=self.model.players, + cat_key=cat_key, + pts=pts, + turn_num=self.model.turn, + has_joker=has_joker + ) + if res: + sender, text, is_self_taunt = res + self.view.add_chat_message(sender, text, is_self_taunt=is_self_taunt) + def _apply_score(self, player, cat_key, pts, has_joker): upper_keys = ["1", "2", "3", "4", "5", "6"] prev_upper = sum(player.scores[k] for k in upper_keys if player.scores[k] is not None) @@ -209,10 +299,26 @@ class GuiController: player.scores[cat_key] = pts new_upper = sum(player.scores[k] for k in upper_keys if player.scores[k] is not None) + unlocked_upper_bonus = (prev_upper < 63 and new_upper >= 63) self.view.update_scoreboard() + self._trigger_chat_reaction(player, cat_key, pts, has_joker=has_joker) - if prev_upper < 63 and new_upper >= 63: + if has_joker: + self.input_locked = True + self.view.disable_input() + if unlocked_upper_bonus: + self.view.show_achievement_banner( + "additional_yahtzee", + on_close=lambda: self.view.show_achievement_banner("bonus", on_close=self.next_player) + ) + else: + self.view.show_achievement_banner("additional_yahtzee", on_close=self.next_player) + elif cat_key == "Y" and pts == 50: + self.input_locked = True + self.view.disable_input() + self.view.show_achievement_banner("yahtzee", on_close=self.next_player) + elif unlocked_upper_bonus: self.input_locked = True self.view.disable_input() self.view.show_achievement_banner("bonus", on_close=self.next_player) @@ -226,13 +332,21 @@ class GuiController: self.view.update_scoreboard() cat_name = t(next(name for k, name in CATEGORIES if k == cat_key)) - msg = t("bot_scored_msg", player.display_name, pts, cat_name) + # 1. Wurf-Ergebnis mit echten Würfelsymbolen im Chatprotokoll speichern & durchscrollen + dice_faces = {1: "⚀", 2: "⚁", 3: "⚂", 4: "⚃", 5: "⚄", 6: "⚅"} + dice_str = "[" + " ".join(dice_faces.get(d, str(d)) for d in sorted(self.model.dice)) + "]" + roll_log_msg = t("bot_roll_log", dice_str, pts, cat_name) + self.view.add_chat_message(player.name, roll_log_msg, is_roll_log=True) + + # 2. Emotionale Reaktion / Stichelei des Bots (läuft durch die Queue 750ms später sanft hinterher!) + self._trigger_chat_reaction(player, cat_key, pts) + + msg = t("bot_scored_msg", player.display_name, pts, cat_name) self.view.show_centered_overlay(msg) - self.view.after(2000, self.end_bot_turn) + self.view.after(2200, self.end_bot_turn) def end_bot_turn(self): - self.view.hide_centered_overlay() self.next_player() def next_player(self): diff --git a/models/__pycache__/i18n.cpython-313.pyc b/models/__pycache__/i18n.cpython-313.pyc index 00ce721..ba56706 100644 Binary files a/models/__pycache__/i18n.cpython-313.pyc and b/models/__pycache__/i18n.cpython-313.pyc differ diff --git a/models/chat_engine.py b/models/chat_engine.py new file mode 100644 index 0000000..e1fb87b --- /dev/null +++ b/models/chat_engine.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +import random +import models.i18n as i18n + +class ChatEngine: + """Verwaltet über 220 kontextsensitive Chat-Reaktionen (DE/EN) ohne >U+FFFF Tkinter-Bugs.""" + + REACTIONS = { + "DE": { + # --- Wenn JEMAND ANDERES 0 Punkte streicht (mit @{0}) --- + "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! ^^" + ], + # --- Wenn der Bot SELBST 0 Punkte streicht (OHNE @, nur Symbole/Emotes) --- + "self_zero": [ + "(╯°□°)╯︵ ┻━┻", "☠ ✞ ☠", "(T_T) ✖", ">_< ⚡", "⚀ ✖ ☠", + "¯\\_(ツ)_/¯ ✖", "(✖╭╮✖)", "⚡ ☠ ⚡", "(-_-;) ...", "(>_<)", + "grrr... ☠", "Verfluchte Würfel! ☠", "Nicht mein Ernst... (T_T)", + "Uff... ✞", "Das gibt Rache! ⚔" + ], + # --- Kleine Straße in Runde 1-4 (mit @{0}) --- + "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! >>" + ], + # --- Kleine Straße allgemein (mit @{0}) --- + "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! ✦" + ], + # --- Große Straße (mit @{0}) --- + "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! ⚡" + ], + # --- Full House (mit @{0}) --- + "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! ♦" + ], + # --- Viererpasch (mit @{0}) --- + "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" + ], + # --- Yahtzee / +100 Bonus Yahtzee (mit @{0}) --- + "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" + ], + # --- Gute Punkte allgemein / Oberer Teil >= 3 Gleiche (mit @{0}) --- + "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! ♦" + ], + # --- Kleine / normale Punkte (mit @{0}) --- + "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. :)" + ], + # --- Bot feiert SICH SELBST bei starken Würfen (OHNE @) --- + "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! ⚡⚅" + ], + # --- Bot trägt für SICH SELBST normale Punkte ein (OHNE @) --- + "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. ♦" + ], + + # --- Spielende: Mensch hat gewonnen --- + "end_human_won": [ + "@{0} Gut gemacht, verdienter Sieg! ♛✦", + "@{0} Stark gespielt, Glückwunsch zum Sieg! o7", + "@{0} Heute warst du nicht zu schlagen. GG! ★", + "@{0} Respekt, sauber abgeliefert! ⚔♛", + "@{0} Nächstes Mal holen wir uns den Sieg zurück! >:)" + ], + # --- Spielende: Mensch hat verloren (Aufmunterung) --- + "end_human_lost": [ + "@{0} Gut gespielt! Viel Glück fürs nächste Mal! ☘", + "@{0} Kopf hoch, beim nächsten Mal fallen die Würfel für dich! ⚀⚅", + "@{0} Stark gekämpft, nächstes Mal klappt es! o7", + "@{0} Knappes Ding! Viel Erfolg in der nächsten Runde! ★", + "@{0} GG! Beim nächsten Ritual drehst du den Spieß um! ✦" + ], + # --- Spielende: Sieger-Bot feiert sich selbst (ohne @) --- + "end_bot_winner": [ + "Dieser Sieg gehört mir! GG an alle! ♛✦", + "Niemand schlägt den Meister der Würfel! B) ♛", + "Ein würdiges Spiel! Danke für die Runde! ⚔★", + "Die Krone bleibt heute bei mir! ♛" + ] + }, + + "EN": { + # --- Someone else scores 0 (with @{0}) --- + "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! ^^" + ], + # --- Bot scores 0 itself (NO @) --- + "self_zero": [ + "(╯°□°)╯︵ ┻━┻", "☠ ✞ ☠", "(T_T) ✖", ">_< ⚡", "⚀ ✖ ☠", + "¯\\_(ツ)_/¯ ✖", "(✖╭╮✖)", "⚡ ☠ ⚡", "(-_-;) ...", "(>_<)", + "grrr... ☠", "Cursed dice! ☠", "Are you kidding me... (T_T)", + "Ugh... ✞", "I will have my revenge! ⚔" + ], + # --- Early Small Straight (with @{0}) --- + "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! >>" + ], + # --- Small Straight general (with @{0}) --- + "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! ✦" + ], + # --- Large Straight (with @{0}) --- + "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! ⚡" + ], + # --- Full House (with @{0}) --- + "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! ♦" + ], + # --- Four of a Kind (with @{0}) --- + "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" + ], + # --- Yahtzee (with @{0}) --- + "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" + ], + # --- Good points general (with @{0}) --- + "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! ♦" + ], + # --- Small / normal points (with @{0}) --- + "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. :)" + ], + # --- Bot taunts for ITSELF on strong rolls (NO @) --- + "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! ⚡⚅" + ], + # --- Bot scores normal points for ITSELF (NO @) --- + "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. ♦" + ], + # --- Game Over: Human won --- + "end_human_won": [ + "@{0} Well done, well-deserved victory! ♛✦", + "@{0} Great game, congrats on the win! o7", + "@{0} You were unbeatable today. GG! ★", + "@{0} Respect, cleanly played! ⚔♛", + "@{0} Next time we'll take the crown back! >:)" + ], + # --- Game Over: Human lost --- + "end_human_lost": [ + "@{0} Well played! Better luck next time! ☘", + "@{0} Heads up, the dice will roll your way next game! ⚀⚅", + "@{0} Good fight, you'll get 'em next time! o7", + "@{0} Close game! Best of luck in the next match! ★", + "@{0} GG! Next ritual is yours! ✦" + ], + # --- Game Over: Winning bot celebrates (no @) --- + "end_bot_winner": [ + "Victory is mine! GG everyone! ♛✦", + "Nobody beats the master of dice! B) ♛", + "A worthy match! Thanks for playing! ⚔★", + "The crown stays with me today! ♛" + ] + } + } + + @staticmethod + def sanitize_for_tk(text): + """Entfernt oder ersetzt Zeichen über U+FFFF, die in Linux-Tkinter Darstellungsfehler verursachen.""" + return "".join(ch if ord(ch) <= 0xFFFF else "✦" for ch in str(text)) + + @classmethod + def generate_reaction(cls, actor, all_players, cat_key, pts, turn_num, has_joker=False): + bots = [p for p in all_players if p.is_bot] + if not bots: + return None + + lang = i18n.CURRENT_LANG if i18n.CURRENT_LANG in cls.REACTIONS else "DE" + pool = cls.REACTIONS[lang] + target_name = actor.name + + if not actor.is_bot: + sender = random.choice(bots).name + bucket = cls._pick_other_bucket(cat_key, pts, turn_num, has_joker) + template = random.choice(pool[bucket]) + return sender, cls.sanitize_for_tk(template.format(target_name)), False + + other_bots = [b for b in bots if b != actor] + + if pts == 0: + if not other_bots or random.random() < 0.75: + return actor.name, cls.sanitize_for_tk(random.choice(pool["self_zero"])), False + else: + commenter = random.choice(other_bots).name + return commenter, cls.sanitize_for_tk(random.choice(pool["other_zero"]).format(target_name)), False + + is_big_play = ( + has_joker + or (cat_key in ["FH", "SS", "LS", "Y"] and pts > 0) + or (cat_key in ["1", "2", "3", "4", "5", "6"] and pts >= int(cat_key) * 3) + or pts >= 20 + ) + + if is_big_play: + if not other_bots or random.random() < 0.70: + return actor.name, cls.sanitize_for_tk(random.choice(pool["self_taunt"])), True + else: + commenter = random.choice(other_bots).name + bucket = cls._pick_other_bucket(cat_key, pts, turn_num, has_joker) + return commenter, cls.sanitize_for_tk(random.choice(pool[bucket]).format(target_name)), False + else: + if not other_bots or random.random() < 0.65: + return actor.name, cls.sanitize_for_tk(random.choice(pool["self_normal"])), False + else: + commenter = random.choice(other_bots).name + return commenter, cls.sanitize_for_tk(random.choice(pool["other_small"]).format(target_name)), False + + @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 (cat_key in ["1", "2", "3", "4", "5", "6"] and pts >= int(cat_key) * 3) or pts >= 18: + return "other_good" + return "other_small" + + @classmethod + def generate_endgame_reactions(cls, human_player, all_players, winner_player): + """Erzeugt am Spielende für jeden Bot eine Abschluss-Nachricht (Gratulation oder Viel Glück).""" + bots = [p for p in all_players if p.is_bot] + if not bots: + return [] + + lang = i18n.CURRENT_LANG if i18n.CURRENT_LANG in cls.REACTIONS else "DE" + pool = cls.REACTIONS[lang] + human_won = (winner_player == human_player) + messages = [] + + for bot in bots: + if human_won: + txt = random.choice(pool["end_human_won"]).format(human_player.name) + messages.append((bot.name, cls.sanitize_for_tk(txt), False)) + else: + if bot == winner_player: + txt = random.choice(pool["end_bot_winner"]) + messages.append((bot.name, cls.sanitize_for_tk(txt), True)) + else: + txt = random.choice(pool["end_human_lost"]).format(human_player.name) + messages.append((bot.name, cls.sanitize_for_tk(txt), False)) + return messages \ No newline at end of file diff --git a/models/i18n.py b/models/i18n.py index 2351aca..cb1b165 100644 --- a/models/i18n.py +++ b/models/i18n.py @@ -61,6 +61,8 @@ TEXTS = { "err_profile_corrupt": "Profil manipuliert oder nicht gefunden!", "err_name_exists": "Dieser Name existiert bereits.", "game_over_title": "Spiel beendet", + "game_over_win_sub": "GEWONNEN!!!", + "game_over_lose_sub": "Leider verloren....", "game_over_msg": "SPIEL BEENDET!\n\nRANGLISTE:\n", "points_word": "Punkte", "turn_label": "Runde {0}/13", @@ -107,7 +109,21 @@ TEXTS = { "btn_no_rolls": "[ Keine Würfe ]", "btn_score": "[ Eintragen ]", "upper_sec": "OBERER TEIL", - "lower_sec": "UNTERER TEIL" + "lower_sec": "UNTERER TEIL", + + # --- Würfel-Assistent (Vor dem Weiterwürfeln) --- + "roll_warn_title": "Wurf-Hinweis", + "roll_warn_combo_header": "Starke Kombination liegt bereit!", + "roll_warn_combo_msg": "Du hast bereits {0}!\nWenn du diese Würfel jetzt neu würfelst, geht die Kombination vielleicht verloren.\n\nMöchtest du trotzdem weiterwürfeln?", + "roll_warn_ls_header": "Große Straße noch möglich!", + "roll_warn_ls_msg": "Du hast schon eine Kleine Straße ({0}) auf dem Tisch und die Große Straße ist noch offen!\nDu hältst aktuell aber nicht alle 4 Straßen-Würfel ({1}).\n\nTrotzdem so würfeln?", + "roll_anyway_btn": "Trotzdem würfeln", + "hold_and_stay_btn": "Abbrechen & prüfen", + + "btn_chat_log": "Protokoll", + "chat_log_title": "Spiel- & Chatprotokoll", + "chat_log_empty": "Noch keine Einträge im Protokoll.", + "bot_roll_log": "würfelt {0} -> {1} Pkt. bei '{2}'" }, "EN": { @@ -170,6 +186,8 @@ TEXTS = { "err_profile_corrupt": "Profile tampered with or not found!", "err_name_exists": "This name already exists.", "game_over_title": "Game Over", + "game_over_win_sub": "YOU WON!!!", + "game_over_lose_sub": "Unfortunately lost....", "game_over_msg": "GAME OVER!\n\nLEADERBOARD:\n", "points_word": "Points", "turn_label": "Round {0}/13", @@ -216,7 +234,21 @@ TEXTS = { "btn_no_rolls": "[ No Rolls ]", "btn_score": "[ Score ]", "upper_sec": "UPPER SECTION", - "lower_sec": "LOWER SECTION" + "lower_sec": "LOWER SECTION", + + # --- Roll Assistant (Before rerolling) --- + "roll_warn_title": "Roll Hint", + "roll_warn_combo_header": "Strong Combination Ready!", + "roll_warn_combo_msg": "You already rolled {0}!\nIf you reroll these dice now, you might lose it.\n\nRoll anyway?", + "roll_warn_ls_header": "Large Straight Possible!", + "roll_warn_ls_msg": "You have a Small Straight ({0}) on the board and Large Straight is still open!\nHowever, you didn't hold all 4 sequence dice ({1}).\n\nRoll like this anyway?", + "roll_anyway_btn": "Roll Anyway", + "hold_and_stay_btn": "Cancel & Check", + + "btn_chat_log": "Chat Log", + "chat_log_title": "Game & Roll Log", + "chat_log_empty": "No entries in the log yet.", + "bot_roll_log": "rolled {0} -> {1} pts in '{2}'" } } diff --git a/python-3.11.9-amd64.exe b/python-3.11.9-amd64.exe new file mode 100644 index 0000000..798159c Binary files /dev/null and b/python-3.11.9-amd64.exe differ diff --git a/python-3.11.9-amd64.exe.1 b/python-3.11.9-amd64.exe.1 new file mode 100644 index 0000000..798159c Binary files /dev/null and b/python-3.11.9-amd64.exe.1 differ diff --git a/ressources/additional_yahtzee_achieved.png b/ressources/additional_yahtzee_achieved.png new file mode 100644 index 0000000..884f966 Binary files /dev/null and b/ressources/additional_yahtzee_achieved.png differ diff --git a/ressources/bonus_achived.png b/ressources/bonus_achieved.png similarity index 100% rename from ressources/bonus_achived.png rename to ressources/bonus_achieved.png diff --git a/ressources/chat_window.png b/ressources/chat_window.png new file mode 100644 index 0000000..50c46ff Binary files /dev/null and b/ressources/chat_window.png differ diff --git a/ressources/lose.gif b/ressources/lose.gif new file mode 100644 index 0000000..f55ba9f Binary files /dev/null and b/ressources/lose.gif differ diff --git a/ressources/win.gif b/ressources/win.gif new file mode 100644 index 0000000..592a543 Binary files /dev/null and b/ressources/win.gif differ diff --git a/ressources/yahtzee_achived.png b/ressources/yahtzee_achieved.png similarity index 100% rename from ressources/yahtzee_achived.png rename to ressources/yahtzee_achieved.png diff --git a/views/__pycache__/asset_manager.cpython-313.pyc b/views/__pycache__/asset_manager.cpython-313.pyc index 9fbd284..cebfd8f 100644 Binary files a/views/__pycache__/asset_manager.cpython-313.pyc and b/views/__pycache__/asset_manager.cpython-313.pyc differ diff --git a/views/__pycache__/board_view.cpython-313.pyc b/views/__pycache__/board_view.cpython-313.pyc index 26deae9..e84ae79 100644 Binary files a/views/__pycache__/board_view.cpython-313.pyc and b/views/__pycache__/board_view.cpython-313.pyc differ diff --git a/views/__pycache__/dialogs.cpython-313.pyc b/views/__pycache__/dialogs.cpython-313.pyc index 09f10b1..c88dabe 100644 Binary files a/views/__pycache__/dialogs.cpython-313.pyc and b/views/__pycache__/dialogs.cpython-313.pyc differ diff --git a/views/__pycache__/gui_view.cpython-313.pyc b/views/__pycache__/gui_view.cpython-313.pyc index 61155d7..cc4ca15 100644 Binary files a/views/__pycache__/gui_view.cpython-313.pyc and b/views/__pycache__/gui_view.cpython-313.pyc differ diff --git a/views/__pycache__/theme.cpython-313.pyc b/views/__pycache__/theme.cpython-313.pyc index 311e3a9..6625ed5 100644 Binary files a/views/__pycache__/theme.cpython-313.pyc and b/views/__pycache__/theme.cpython-313.pyc differ diff --git a/views/asset_manager.py b/views/asset_manager.py index bd7e1a4..a6a17b4 100644 --- a/views/asset_manager.py +++ b/views/asset_manager.py @@ -14,6 +14,7 @@ class AssetManager: self.raw_bg = None self.raw_title = None self.raw_logo = None + self.raw_chat_bg = None self.raw_btn_orange = None self.raw_btn_orange_active = None @@ -28,18 +29,21 @@ class AssetManager: self.bonus_achieved_img = None self.yahtzee_achieved_img = None + self.additional_yahtzee_img = None self.raw_dice = {} self.raw_anim_frames = [] - self.anim_cache_large = [] + self.anim_cache_large = [] + self.win_frames = [] + self.lose_frames = [] if not HAS_PIL: return def get_full_path(rel_path): - try: + if hasattr(sys, "_MEIPASS"): base_path = sys._MEIPASS - except Exception: + else: base_path = os.path.abspath(".") return os.path.join(base_path, rel_path) @@ -57,6 +61,36 @@ class AssetManager: self.raw_title = load_raw(["ressources/title1.png"]) self.raw_logo = load_raw(["ressources/logo.jpg", "ressources/logo.png"]) + # Chat-Hintergrund laden & äußeren Rand automatisch zuschneiden + chat_img = load_raw([ + "ressources/chat_window_2.png", + "ressources/chat_window.png", + "ressources/chat_window_2.jpg", + "ressources/chat_window.jpg" + ]) + if not chat_img and os.path.exists(get_full_path("ressources")): + for root_dir, _, files in os.walk(get_full_path("ressources")): + for f in sorted(files, reverse=True): + if "chat_window" in f.lower() and f.lower().endswith((".png", ".jpg", ".jpeg")): + chat_img = Image.open(os.path.join(root_dir, f)).convert("RGBA") + break + + if chat_img: + px = chat_img.load() + w, h = chat_img.size + min_x, min_y, max_x, max_y = w, h, 0, 0 + for y in range(h): + for x in range(w): + r, g, b, a = px[x, y] + if a > 20 and not (r > 240 and g > 240 and b > 240): + if x < min_x: min_x = x + if y < min_y: min_y = y + if x > max_x: max_x = x + if y > max_y: max_y = y + if max_x > min_x and max_y > min_y: + chat_img = chat_img.crop((min_x, min_y, max_x + 1, max_y + 1)) + self.raw_chat_bg = chat_img + # 2. Rohe UI-Buttons laden + Standard-Instanzen erzeugen self.raw_btn_orange = load_raw(["ressources/button1.png", "ressources/button1.jpeg"]) self.raw_btn_orange_active = load_raw(["ressources/button1_active.png"]) @@ -66,17 +100,40 @@ class AssetManager: self.btn_orange, self.btn_orange_active = self.get_btn_pair("orange", 200, 50) self.sel_inactive, self.sel_active = self.get_btn_pair("purple", 150, 35) - # 3. Erfolgs-Banner laden + # 3. Erfolgs-Banner laden (inkl. automatischer Suche in ressources/) self.bonus_achieved_img = load_raw([ - "ressources/bonus_achived.jpg", - "ressources/bonus_achieved.jpg", - "ressources/bonus_achieved.png" + "ressources/bonus_achived.jpg", "ressources/bonus_achieved.jpg", + "ressources/bonus_achived.png", "ressources/bonus_achieved.png", + "ressources/bonus_achived.jpeg", "ressources/bonus_achieved.jpeg", + "ressources/bonus.png", "ressources/bonus.jpg" ]) self.yahtzee_achieved_img = load_raw([ - "ressources/yahtzee_achived.jpg", - "ressources/yahtzee_achieved.jpg", - "ressources/yahtzee_achieved.png" + "ressources/yahtzee_achived.jpg", "ressources/yahtzee_achieved.jpg", + "ressources/yahtzee_achived.png", "ressources/yahtzee_achieved.png", + "ressources/yahtzee_achived.jpeg", "ressources/yahtzee_achieved.jpeg", + "ressources/yahtzee.png", "ressources/yahtzee.jpg" ]) + self.additional_yahtzee_img = load_raw([ + "ressources/additional_yahtzee_achieved.png", + "ressources/additional_yahtzee_achived.png", + "ressources/additional_yahtzee_achieved.jpg", + "ressources/additional_yahtzee_achived.jpg" + ]) + + # Falls noch nicht gefunden: Suche flexibel nach Dateinamen in ressources/ + res_dir = get_full_path("ressources") + if os.path.exists(res_dir): + for root_dir, _, files in os.walk(res_dir): + for f in files: + low = f.lower() + if low.endswith((".png", ".jpg", ".jpeg")): + full_f = os.path.join(root_dir, f) + if not self.bonus_achieved_img and "bonus" in low: + self.bonus_achieved_img = Image.open(full_f).convert("RGBA") + elif not self.additional_yahtzee_img and "additional" in low and "yahtzee" in low: + self.additional_yahtzee_img = Image.open(full_f).convert("RGBA") + elif not self.yahtzee_achieved_img and "yahtzee" in low and "additional" not in low: + self.yahtzee_achieved_img = Image.open(full_f).convert("RGBA") # 4. Rohe Würfel für dynamische Größen for i in range(1, 7): @@ -100,6 +157,36 @@ class AssetManager: self.anim_cache_large.append(ImageTk.PhotoImage(f_rgba.resize((150, 150), Image.Resampling.LANCZOS))) except Exception as e: print(f"Fehler beim Laden des GIFs: {e}") + + # 6. Win & Lose GIFs (oder Bilder) laden + def load_anim_or_img(candidates, size=(200, 150)): + frames = [] + found_path = None + for c in candidates: + full = get_full_path(c) + if os.path.exists(full): + found_path = full + break + if not found_path and os.path.exists(get_full_path("ressources")): + key_word = "win" if "win" in candidates[0] else "lose" + for r_dir, _, f_list in os.walk(get_full_path("ressources")): + for f in f_list: + low = f.lower() + if low.startswith(key_word) and low.endswith((".gif", ".png", ".jpg", ".jpeg")): + found_path = os.path.join(r_dir, f) + break + if found_path: + try: + im = Image.open(found_path) + for frame in ImageSequence.Iterator(im): + f_rgba = frame.copy().convert("RGBA") + frames.append(ImageTk.PhotoImage(f_rgba.resize(size, Image.Resampling.LANCZOS))) + except Exception as e: + print(f"Fehler beim Laden von {found_path}: {e}") + return frames + + self.win_frames = load_anim_or_img(["ressources/win.gif", "ressources/win.jpg", "ressources/win.png"]) + self.lose_frames = load_anim_or_img(["ressources/lose.gif", "ressources/lose.jpg", "ressources/lose.png"]) def get_btn_pair(self, style="purple", width=150, height=35): """Gibt ein exakt auf (width, height) skaliertes Bildpaar (normal, hover) zurück.""" diff --git a/views/board_view.py b/views/board_view.py index d13e939..4dcc10b 100644 --- a/views/board_view.py +++ b/views/board_view.py @@ -6,6 +6,7 @@ from models.i18n import t from views.theme import create_img_button, BG_COLOR, FG_COLOR, ACCENT_ORANGE from views.resizing_bg import ResizingBG from views.image_die import ImageDie +from views.toast_chat import ToastChat class BoardView: def __init__(self, root_view): @@ -49,12 +50,16 @@ class BoardView: create_img_button(right_frame, t("btn_save_quit"), self.assets.sel_inactive, self.assets.sel_active, self.ctrl.save_and_quit).pack(side="right", padx=5) create_img_button(right_frame, t("btn_menu"), self.assets.sel_inactive, self.assets.sel_active, lambda: self.root.dialogs.show_menu_confirm_dialog()).pack(side="right", padx=5) create_img_button(right_frame, t("btn_help"), self.assets.sel_inactive, self.assets.sel_active, lambda: self.root.dialogs.show_help_dialog()).pack(side="right", padx=5) + create_img_button(right_frame, t("btn_chat_log"), self.assets.sel_inactive, self.assets.sel_active, self.root.show_chat_log_dialog).pack(side="right", padx=5) main_split = tk.Frame(content_frame, bg=BG_COLOR) main_split.pack(fill="both", expand=True, pady=10) self._build_left_panel(main_split) self._build_right_panel(main_split) + self.toast_chat = ToastChat(content_frame) + # Ganz am Ende von init_ui() in views/board_view.py: + self.toast_chat = ToastChat(self.root) def _build_left_panel(self, parent): self.dice_wrapper = tk.Frame(parent, bg=BG_COLOR) @@ -95,58 +100,70 @@ class BoardView: self.bg_r.place(relx=0, rely=0, relwidth=1, relheight=1) score_inner = tk.Frame(score_wrapper, bg=BG_COLOR) - score_inner.place(relx=0.5, rely=0.5, anchor="center") + score_inner.place(relx=0.5, rely=0.52, anchor="center") - tk.Label(score_inner, text=t("your_scorecard"), font=("Helvetica", 14, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE).pack(pady=5) + tk.Label(score_inner, text=t("your_scorecard"), font=("Helvetica", 12, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE).pack(pady=(0, 3)) grid_frame = tk.Frame(score_inner, bg=BG_COLOR) - grid_frame.pack(fill="x", pady=5) + grid_frame.pack(fill="x", pady=1) upper_frame = tk.Frame(grid_frame, bg=BG_COLOR) - upper_frame.grid(row=0, column=0, sticky="n", padx=5) + upper_frame.grid(row=0, column=0, sticky="n", padx=4) lower_frame = tk.Frame(grid_frame, bg=BG_COLOR) - lower_frame.grid(row=0, column=1, sticky="n", padx=5) + lower_frame.grid(row=0, column=1, sticky="n", padx=4) self.score_buttons = {} self.score_labels = {} for row, i in enumerate(range(6)): cat_key, cat_name_key = CATEGORIES[i] - btn = create_img_button(upper_frame, t(cat_name_key), self.assets.sel_inactive, self.assets.sel_active, command=lambda k=cat_key: self.ctrl.score_category(k)) - btn.grid(row=row, column=0, pady=2, sticky="w") + btn = create_img_button( + upper_frame, t(cat_name_key), self.assets.sel_inactive, self.assets.sel_active, + command=lambda k=cat_key: self.ctrl.score_category(k), + min_px_width=125, height=27, font_size=10 + ) + btn.grid(row=row, column=0, pady=1, sticky="w") self.score_buttons[cat_key] = btn - lbl = tk.Label(upper_frame, text="-", font=("Courier", 13, "bold"), bg=BG_COLOR, fg="#555", width=4) - lbl.grid(row=row, column=1, padx=5) + lbl = tk.Label(upper_frame, text="-", font=("Courier", 11, "bold"), bg=BG_COLOR, fg="#555", width=4) + lbl.grid(row=row, column=1, padx=3) self.score_labels[cat_key] = lbl - tk.Frame(upper_frame, bg="#444", height=1).grid(row=6, column=0, columnspan=2, sticky="ew", pady=5) - self.bonus_lbl = tk.Label(upper_frame, text=t("bonus_progress", 0), font=("Helvetica", 10, "bold"), bg=BG_COLOR, fg="#888") + tk.Frame(upper_frame, bg="#444", height=1).grid(row=6, column=0, columnspan=2, sticky="ew", pady=2) + self.bonus_lbl = tk.Label(upper_frame, text=t("bonus_progress", 0), font=("Helvetica", 9, "bold"), bg=BG_COLOR, fg="#888") self.bonus_lbl.grid(row=7, column=0, columnspan=2) for row, i in enumerate(range(6, 13)): cat_key, cat_name_key = CATEGORIES[i] - btn = create_img_button(lower_frame, t(cat_name_key), self.assets.sel_inactive, self.assets.sel_active, command=lambda k=cat_key: self.ctrl.score_category(k)) - btn.grid(row=row, column=0, pady=2, sticky="w") + btn = create_img_button( + lower_frame, t(cat_name_key), self.assets.sel_inactive, self.assets.sel_active, + command=lambda k=cat_key: self.ctrl.score_category(k), + min_px_width=125, height=27, font_size=10 + ) + btn.grid(row=row, column=0, pady=1, sticky="w") self.score_buttons[cat_key] = btn - lbl = tk.Label(lower_frame, text="-", font=("Courier", 13, "bold"), bg=BG_COLOR, fg="#555", width=4) - lbl.grid(row=row, column=1, padx=5) + lbl = tk.Label(lower_frame, text="-", font=("Courier", 11, "bold"), bg=BG_COLOR, fg="#555", width=4) + lbl.grid(row=row, column=1, padx=3) self.score_labels[cat_key] = lbl - tk.Frame(score_inner, bg="#444", height=1).pack(fill="x", pady=10) - self.total_lbl = tk.Label(score_inner, text=t("total_score", 0), font=("Courier", 16, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE) - self.total_lbl.pack() + tk.Frame(score_inner, bg="#444", height=1).pack(fill="x", pady=4) + self.total_lbl = tk.Label(score_inner, text=t("total_score", 0), font=("Courier", 14, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE) + self.total_lbl.pack(pady=0) if len(self.ctrl.model.players) > 1: bots_frame = tk.Frame(score_inner, bg=BG_COLOR, highlightbackground="#333", highlightthickness=1) - bots_frame.pack(fill="x", pady=15) - tk.Label(bots_frame, text=t("opponents_overview"), font=("Helvetica", 11, "bold"), bg=BG_COLOR, fg=FG_COLOR).pack(pady=5) + bots_frame.pack(fill="x", pady=(4, 0)) + tk.Label(bots_frame, text=t("opponents_overview"), font=("Helvetica", 10, "bold"), bg=BG_COLOR, fg=FG_COLOR).pack(pady=(2, 1)) self.bot_total_labels = {} for p in self.ctrl.model.players[1:]: row_f = tk.Frame(bots_frame, bg=BG_COLOR) - row_f.pack(fill="x", padx=10, pady=2) - lbl = tk.Label(row_f, text=f"{p.display_name}: 0", font=("Helvetica", 11), bg=BG_COLOR, fg=FG_COLOR) - lbl.pack(side="left") + row_f.pack(fill="x", padx=6, pady=1) + lbl = tk.Label(row_f, text=f"{p.display_name}: 0", font=("Helvetica", 9), bg=BG_COLOR, fg=FG_COLOR, anchor="w") + lbl.pack(side="left", padx=(0, 6)) self.bot_total_labels[p.name] = lbl - btn = create_img_button(row_f, t("details_btn"), self.assets.sel_inactive, self.assets.sel_active, command=lambda p=p: self.root.dialogs.show_bot_details(p)) + btn = create_img_button( + row_f, t("details_btn"), self.assets.sel_inactive, self.assets.sel_active, + command=lambda p=p: self.root.dialogs.show_bot_details(p), + min_px_width=70, height=23, font_size=9 + ) btn.pack(side="right") def _on_dice_wrapper_resize(self, event): @@ -246,4 +263,8 @@ class BoardView: else: if callback: callback() - anim_step() \ No newline at end of file + anim_step() + + def add_chat_message(self, sender, text, is_self_taunt=False): + if hasattr(self, "toast_chat") and self.toast_chat: + self.toast_chat.add_message(sender, text, is_self_taunt) \ No newline at end of file diff --git a/views/dialogs.py b/views/dialogs.py index 0220625..db6ecc0 100644 --- a/views/dialogs.py +++ b/views/dialogs.py @@ -20,15 +20,23 @@ class DialogManager: def _create_styled_modal(self, title, width=420, height=260): top = tk.Toplevel(self.root) top.title(title) - top.geometry(f"{width}x{height}") top.configure(bg=BG_COLOR) top.transient(self.root) - top.grab_set() self.root.update_idletasks() x = self.root.winfo_x() + (self.root.winfo_width() - width) // 2 y = self.root.winfo_y() + (self.root.winfo_height() - height) // 2 - top.geometry(f"+{x}+{y}") + top.geometry(f"{width}x{height}+{x}+{y}") + + def safe_grab(): + if top.winfo_exists(): + try: + top.wait_visibility() + top.grab_set() + except Exception: + pass + + top.after(30, safe_grab) return top def show_error(self, title, msg): @@ -50,45 +58,128 @@ class DialogManager: tk.Label(top, text=msg, font=("Helvetica", 11), bg=BG_COLOR, fg=FG_COLOR, justify="center").pack(pady=10) create_img_button(top, t("close_btn"), self.assets.sel_inactive, self.assets.sel_active, top.destroy).pack(pady=15) - def show_game_over_dialog(self, scoreboard, on_close=None): - height = 260 + len(scoreboard) * 38 - top = self._create_styled_modal(t("game_over_title"), 480, height) - + def show_game_over_dialog(self, scoreboard, human_won=True, on_close=None): + """Zeigt das Spielende mit Unterüberschrift, win.gif / lose.gif und Rangliste an.""" + go_frame = tk.Frame(self.root, bg=BG_COLOR, highlightbackground=ACCENT_ORANGE, highlightthickness=2) + go_frame.place(relx=0.33, rely=0.5, width=480, height=540, anchor="center") + go_frame.lift() + if self.assets.raw_bg: - bg = ResizingBG(top, self.assets.raw_bg, bg=BG_COLOR) + bg = ResizingBG(go_frame, self.assets.raw_bg, bg=BG_COLOR) bg.place(relx=0, rely=0, relwidth=1, relheight=1) - content = tk.Frame(top, bg=BG_COLOR) + content = tk.Frame(go_frame, bg=BG_COLOR) content.place(relx=0.5, rely=0.5, anchor="center") - tk.Label(content, text=t("game_over_title").upper(), font=("Helvetica", 20, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE).pack(pady=(10, 5)) - tk.Label(content, text=t("leaderboard"), font=("Helvetica", 12, "bold"), bg=BG_COLOR, fg="#888").pack(pady=(0, 15)) + # Hauptüberschrift + tk.Label( + content, text=t("game_over_title").upper(), + font=("Helvetica", 20, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE + ).pack(pady=(6, 2)) - board_frame = tk.Frame(content, bg=BG_COLOR, highlightbackground="#333", highlightthickness=1, padx=15, pady=10) - board_frame.pack(fill="x", pady=5) + # Neue Unterüberschrift: "GEWONNEN!!!" oder "Leider verloren...." + sub_text = t("game_over_win_sub") if human_won else t("game_over_lose_sub") + sub_color = "#00FF00" if human_won else "#FF4444" + tk.Label( + content, text=sub_text, + font=("Helvetica", 15, "bold"), bg=BG_COLOR, fg=sub_color + ).pack(pady=(0, 6)) + + # Animiertes GIF (win.gif oder lose.gif) + frames = self.assets.win_frames if human_won else self.assets.lose_frames + gif_lbl = tk.Label(content, bg=BG_COLOR, bd=0) + gif_lbl.pack(pady=4) + + anim_state = {"idx": 0, "job": None} + def animate_result_gif(): + if go_frame.winfo_exists() and frames: + frame_img = frames[anim_state["idx"] % len(frames)] + gif_lbl.config(image=frame_img) + anim_state["idx"] += 1 + anim_state["job"] = self.root.after(90, animate_result_gif) + + if frames: + animate_result_gif() + + tk.Label( + content, text=t("leaderboard"), + font=("Helvetica", 11, "bold"), bg=BG_COLOR, fg="#888" + ).pack(pady=(4, 6)) + + board_frame = tk.Frame(content, bg=BG_COLOR, highlightbackground="#333", highlightthickness=1, padx=15, pady=8) + board_frame.pack(fill="x", pady=4) for rank, (disp_name, score) in enumerate(scoreboard, 1): row = tk.Frame(board_frame, bg=BG_COLOR) - row.pack(fill="x", pady=4) + row.pack(fill="x", pady=3) color = "#FFD700" if rank == 1 else FG_COLOR - font_style = ("Helvetica", 12, "bold") if rank == 1 else ("Helvetica", 11) + font_style = ("Helvetica", 11, "bold") if rank == 1 else ("Helvetica", 10) - tk.Label(row, text=f"{rank}. {disp_name}", font=font_style, bg=BG_COLOR, fg=color, anchor="w").pack(side="left", padx=(0, 20)) - tk.Label(row, text=f"{score} {t('points_word')}", font=("Courier", 12, "bold"), bg=BG_COLOR, fg=color, anchor="e").pack(side="right") + tk.Label(row, text=f"{rank}. {disp_name}", font=font_style, bg=BG_COLOR, fg=color, anchor="w").pack(side="left", padx=(0, 16)) + tk.Label(row, text=f"{score} {t('points_word')}", font=("Courier", 11, "bold"), bg=BG_COLOR, fg=color, anchor="e").pack(side="right") def finish(): - top.destroy() + if anim_state["job"]: + try: + self.root.after_cancel(anim_state["job"]) + except Exception: + pass + if go_frame.winfo_exists(): + go_frame.destroy() if on_close: on_close() - top.protocol("WM_DELETE_WINDOW", finish) - create_img_button(content, t("close_btn"), self.assets.btn_orange, self.assets.btn_orange_active, finish).pack(pady=20) + create_img_button(content, t("close_btn"), self.assets.btn_orange, self.assets.btn_orange_active, finish).pack(pady=12) + + if hasattr(self.root, "toast_chat") and self.root.toast_chat: + self.root.toast_chat.lift() def show_help_dialog(self): top = self._create_styled_modal(t("help_title"), 440, 360) tk.Label(top, text=t("help_header"), font=("Helvetica", 14, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE).pack(pady=15) tk.Label(top, text=t("help_text"), font=("Helvetica", 11), bg=BG_COLOR, fg=FG_COLOR, justify="left", padx=20).pack(pady=10, anchor="w") create_img_button(top, t("close_btn"), self.assets.sel_inactive, self.assets.sel_active, top.destroy).pack(pady=20) + + def show_chat_log_dialog(self, history_list): + top = self._create_styled_modal(t("chat_log_title"), 540, 420) + tk.Label( + top, text=t("chat_log_title"), + font=("Helvetica", 14, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE + ).pack(pady=(12, 8)) + + log_frame = tk.Frame(top, bg="#16141F", highlightbackground="#38304C", highlightthickness=1) + log_frame.pack(fill="both", expand=True, padx=16, pady=6) + + scrollbar = tk.Scrollbar(log_frame, bg="#222", troughcolor=BG_COLOR) + scrollbar.pack(side="right", fill="y") + + text_widget = tk.Text( + log_frame, bg="#16141F", fg=FG_COLOR, font=("Helvetica", 10), + bd=0, highlightthickness=0, wrap="word", yscrollcommand=scrollbar.set, + padx=10, pady=8 + ) + text_widget.pack(side="left", fill="both", expand=True) + scrollbar.config(command=text_widget.yview) + + text_widget.tag_configure("time", foreground="#777777", font=("Courier", 9)) + text_widget.tag_configure("roll", foreground="#00E676", font=("Helvetica", 10, "bold")) + text_widget.tag_configure("taunt", foreground=ACCENT_ORANGE, font=("Helvetica", 10, "bold")) + text_widget.tag_configure("chat", foreground="#FF4444", font=("Helvetica", 10, "bold")) + text_widget.tag_configure("msg", foreground=FG_COLOR, font=("Helvetica", 10)) + + if not history_list: + text_widget.insert("end", t("chat_log_empty"), "msg") + else: + for item in history_list: + tag = "roll" if item.get("is_roll_log") else ("taunt" if item["color"] == ACCENT_ORANGE else "chat") + text_widget.insert("end", f"[{item['time']}] ", "time") + text_widget.insert("end", f"{item['sender']}: ", tag) + text_widget.insert("end", f"{item['text']}\n", "msg") + + text_widget.see("end") + text_widget.config(state="disabled") + + create_img_button(top, t("close_btn"), self.assets.sel_inactive, self.assets.sel_active, top.destroy).pack(pady=12) def show_menu_confirm_dialog(self): top = self._create_styled_modal(t("leave_title"), 400, 230) @@ -110,39 +201,42 @@ class DialogManager: create_img_button(btn_frame, t("discard_btn"), self.assets.btn_orange, self.assets.btn_orange_active, discard_and_exit).pack(side="left", padx=5) tk.Button(top, text=t("cancel_btn"), command=top.destroy, bg=BG_COLOR, fg="#888", bd=0, font=("Helvetica", 10)).pack(pady=5) - def show_achievement_banner(self, raw_img, on_close=None): - top = tk.Toplevel(self.root) - top.overrideredirect(True) - top.geometry("500x300") - top.configure(bg=BG_COLOR) - top.attributes("-topmost", True) - - self.root.update_idletasks() - x = self.root.winfo_x() + (self.root.winfo_width() - 500) // 2 - y = self.root.winfo_y() + (self.root.winfo_height() - 300) // 2 - top.geometry(f"+{x}+{y}") - - canvas = tk.Canvas(top, width=500, height=300, bg=BG_COLOR, highlightthickness=0, bd=0) - canvas.pack(fill="both", expand=True) - + def show_achievement_banner(self, raw_img, fallback_title="ACHIEVED!", on_close=None): + """Zeigt das Bonus- oder Yahtzee-Banner direkt zentriert im Hauptfenster an.""" + banner_overlay = tk.Frame(self.root, bg=BG_COLOR, highlightbackground=ACCENT_ORANGE, highlightthickness=2) + banner_overlay.place(relx=0.5, rely=0.5, width=520, height=320, anchor="center") + banner_overlay.lift() + + canvas = tk.Canvas(banner_overlay, width=500, height=300, bg=BG_COLOR, highlightthickness=0, bd=0) + canvas.pack(fill="both", expand=True, padx=8, pady=8) + if raw_img: img_tk = ImageTk.PhotoImage(raw_img.resize((500, 300), Image.Resampling.LANCZOS)) canvas.image_ref = img_tk - canvas.create_image(0, 0, image=img_tk, anchor="nw") + canvas.create_image(250, 150, image=img_tk, anchor="center") else: - tk.Label(canvas, text=t("achieved_fallback"), font=("Helvetica", 28, "bold"), fg=ACCENT_ORANGE, bg=BG_COLOR).place(relx=0.5, rely=0.5, anchor="center") + # Schicker Fallback im Goth-Stil, falls das Bild nicht geladen wurde + tk.Label( + canvas, text=fallback_title, font=("Helvetica", 28, "bold"), + fg=ACCENT_ORANGE, bg=BG_COLOR + ).place(relx=0.5, rely=0.42, anchor="center") + tk.Label( + canvas, text=t("achieved_fallback"), font=("Helvetica", 16, "bold"), + fg="#00FF00", bg=BG_COLOR + ).place(relx=0.5, rely=0.65, anchor="center") closed = [False] - def finish(): + def finish(event=None): if not closed[0]: closed[0] = True - if top.winfo_exists(): - top.destroy() + if banner_overlay.winfo_exists(): + banner_overlay.destroy() if on_close: on_close() - top.after(2500, finish) - canvas.bind("", lambda e: finish()) + self.root.after(2500, finish) + banner_overlay.bind("", finish) + canvas.bind("", finish) def ask_zero_score_confirm(self, cat_name, on_confirm): top = self._create_styled_modal(t("zero_confirm_title"), 400, 210) @@ -198,6 +292,8 @@ class DialogManager: if self.overlay_frame and self.overlay_frame.winfo_exists(): if self.overlay_text_lbl and self.overlay_text_lbl.winfo_exists(): self.overlay_text_lbl.config(text=text_msg) + if hasattr(self.root.board, "toast_chat") and self.root.board.toast_chat: + self.root.board.toast_chat.lift() return self.overlay_frame = tk.Frame(self.root, bg=BG_COLOR) @@ -219,6 +315,28 @@ class DialogManager: self.overlay_anim_step = 0 self._animate_overlay_gif() + # Wichtig: Toast-Chat immer ÜBER das Bot-Overlay heben! + if hasattr(self.root.board, "toast_chat") and self.root.board.toast_chat: + self.root.board.toast_chat.lift() + + def ask_roll_warning_confirm(self, header_text, body_text, on_confirm): + top = self._create_styled_modal(t("roll_warn_title"), 450, 260) + tk.Label(top, text=header_text, font=("Helvetica", 14, "bold"), bg=BG_COLOR, fg=ACCENT_ORANGE).pack(pady=15) + tk.Label( + top, text=body_text, + font=("Helvetica", 11), bg=BG_COLOR, fg=FG_COLOR, justify="center", wraplength=410 + ).pack(pady=5) + + btn_frame = tk.Frame(top, bg=BG_COLOR) + btn_frame.pack(pady=20) + + def confirm(): + top.destroy() + on_confirm() + + create_img_button(btn_frame, t("roll_anyway_btn"), self.assets.sel_inactive, self.assets.sel_active, confirm).pack(side="left", padx=5) + create_img_button(btn_frame, t("hold_and_stay_btn"), self.assets.btn_orange, self.assets.btn_orange_active, top.destroy).pack(side="left", padx=5) + def _animate_overlay_gif(self): if self.overlay_frame and self.overlay_frame.winfo_exists(): if self.assets.anim_cache_large: @@ -236,4 +354,4 @@ class DialogManager: self.anim_job = None if self.overlay_frame and self.overlay_frame.winfo_exists(): self.overlay_frame.destroy() - self.overlay_frame = None \ No newline at end of file + self.overlay_frame = None diff --git a/views/gui_view.py b/views/gui_view.py index 5b37a26..b8b15d4 100644 --- a/views/gui_view.py +++ b/views/gui_view.py @@ -6,6 +6,7 @@ from views.resizing_bg import ResizingBG from views.menu_views import MenuViews from views.board_view import BoardView from views.dialogs import DialogManager +from views.toast_chat import ToastChat class YahtzeeView(tk.Tk): def __init__(self, ctrl): @@ -15,7 +16,6 @@ class YahtzeeView(tk.Tk): self.configure(bg=BG_COLOR) self.minsize(800, 600) - # Zuletzt verwendete Fenstergröße wiederherstellen saved_geom = Database.load_setting("window_geometry", "950x750") saved_zoom = Database.load_setting("window_zoomed", "0") try: @@ -39,6 +39,7 @@ class YahtzeeView(tk.Tk): self.menus = MenuViews(self) self.board = BoardView(self) self.dialogs = DialogManager(self) + self.toast_chat = ToastChat(self) def _on_window_configure(self, event): if event.widget == self: @@ -75,12 +76,36 @@ class YahtzeeView(tk.Tk): self.unbind(str(i)) for widget in self.winfo_children(): + if hasattr(self, "toast_chat") and widget == self.toast_chat: + self.toast_chat.place_forget() + continue widget.destroy() if apply_global_bg and self.assets.raw_bg: self.bg_widget = ResizingBG(self, self.assets.raw_bg, bg=BG_COLOR) self.bg_widget.place(relx=0, rely=0, relwidth=1, relheight=1) + # --- Chat & Protokoll --- + def add_chat_message(self, sender, text, is_self_taunt=False, is_roll_log=False): + if hasattr(self, "toast_chat") and self.toast_chat: + self.toast_chat.add_message(sender, text, is_self_taunt, is_roll_log) + + def clear_chat_history(self): + if hasattr(self, "toast_chat") and self.toast_chat: + self.toast_chat.clear_history() + + def set_chat_endgame_mode(self, enabled=True): + if hasattr(self, "toast_chat") and self.toast_chat: + self.toast_chat.set_endgame_mode(enabled) + + def schedule_chat_hide(self, delay_ms=3500): + if hasattr(self, "toast_chat") and self.toast_chat: + self.toast_chat.schedule_hide(delay_ms) + + def show_chat_log_dialog(self): + hist = self.toast_chat.history if hasattr(self, "toast_chat") and self.toast_chat else [] + self.dialogs.show_chat_log_dialog(hist) + # --- Weiterleitungen an MenuViews --- def show_login(self, profiles): self.menus.show_login(profiles) def show_main_menu(self, profile_name, has_savegame): self.menus.show_main_menu(profile_name, has_savegame) @@ -102,21 +127,27 @@ class YahtzeeView(tk.Tk): def show_error(self, title, msg): self.dialogs.show_error(title, msg) def show_info(self, title, msg): self.dialogs.show_info(title, msg) def show_stats_popup(self, stats): self.dialogs.show_stats_popup(stats) - def show_centered_overlay(self, text_msg): self.dialogs.show_centered_overlay(text_msg) + def show_game_over_dialog(self, scoreboard, human_won=True, on_close=None): + self.dialogs.show_game_over_dialog(scoreboard, human_won, on_close) + def show_centered_overlay(self, text_msg): + self.dialogs.show_centered_overlay(text_msg) + if hasattr(self, "toast_chat") and self.toast_chat and self.toast_chat.visible_messages: + self.toast_chat.lift() def hide_centered_overlay(self): self.dialogs.hide_centered_overlay() def show_help_dialog(self): self.dialogs.show_help_dialog() def show_menu_confirm_dialog(self): self.dialogs.show_menu_confirm_dialog() def ask_zero_score_confirm(self, cat_name, on_confirm): self.dialogs.ask_zero_score_confirm(cat_name, on_confirm) def ask_better_option_confirm(self, current_cat_name, better_cat_name, better_pts, on_confirm): self.dialogs.ask_better_option_confirm(current_cat_name, better_cat_name, better_pts, on_confirm) + def ask_roll_warning_confirm(self, header_text, body_text, on_confirm): + self.dialogs.ask_roll_warning_confirm(header_text, body_text, on_confirm) - def show_game_over_dialog(self, scoreboard, on_close=None): - self.dialogs.show_game_over_dialog(scoreboard, on_close) - def show_achievement_banner(self, img_type, on_close=None): - if img_type == "bonus" and self.assets.bonus_achieved_img: - self.dialogs.show_achievement_banner(self.assets.bonus_achieved_img, on_close) - elif img_type == "yahtzee" and self.assets.yahtzee_achieved_img: - self.dialogs.show_achievement_banner(self.assets.yahtzee_achieved_img, on_close) + if img_type == "bonus": + self.dialogs.show_achievement_banner(self.assets.bonus_achieved_img, "BONUS +35!", on_close) + elif img_type == "yahtzee": + self.dialogs.show_achievement_banner(self.assets.yahtzee_achieved_img, "Y A H T Z E E ! (+50)", on_close) + elif img_type == "additional_yahtzee": + self.dialogs.show_achievement_banner(self.assets.additional_yahtzee_img, "YAHTZEE BONUS! (+100)", on_close) elif on_close: on_close() \ No newline at end of file diff --git a/views/theme.py b/views/theme.py index 7fe8188..39b487e 100644 --- a/views/theme.py +++ b/views/theme.py @@ -6,21 +6,20 @@ FG_COLOR = "#E0E0E0" ACCENT_ORANGE = "#FF7518" class DynamicImgButton(tk.Button): - """Ein Bild-Button, dessen Hintergrundgrafik automatisch mit der Textlänge mitwächst.""" - def __init__(self, parent, text, img, img_active, command, min_px_width=None): + """Ein Bild-Button, dessen Hintergrundgrafik automatisch mit Textlänge und Höhe skaliert.""" + def __init__(self, parent, text, img, img_active, command, min_px_width=None, height=None, font_size=11): self._assets = getattr(parent.winfo_toplevel(), "assets", None) - self._font = tkfont.Font(family="Helvetica", size=11, weight="bold") + self._font = tkfont.Font(family="Helvetica", size=font_size, weight="bold") self._min_px_width = min_px_width self._is_hovered = False - # Erkennen, ob es der orange Hauptbutton (Höhe 50) oder der lila Auswahlbutton (Höhe 35) ist if self._assets and img == self._assets.btn_orange: self._style = "orange" - self._height = 50 + self._height = height if height else 50 self._default_min = 200 else: self._style = "purple" - self._height = 35 + self._height = height if height else 35 self._default_min = 150 self._img_norm, self._img_act = self._get_scaled_images(text) @@ -36,7 +35,8 @@ class DynamicImgButton(tk.Button): self.bind("", self._on_leave) def _get_scaled_images(self, text_str): - text_px = self._font.measure(str(text_str)) + 36 # 18px Polsterung links & rechts + padding = 24 if self._height < 30 else 36 + text_px = self._font.measure(str(text_str)) + padding base_min = self._min_px_width if self._min_px_width else self._default_min target_w = max(base_min, text_px) if self._assets and hasattr(self._assets, "get_btn_pair"): @@ -62,5 +62,8 @@ class DynamicImgButton(tk.Button): configure = config -def create_img_button(parent, text, img, img_active, command, width=None, min_px_width=None): - return DynamicImgButton(parent, text, img, img_active, command, min_px_width=min_px_width) \ No newline at end of file +def create_img_button(parent, text, img, img_active, command, width=None, min_px_width=None, height=None, font_size=11): + return DynamicImgButton( + parent, text, img, img_active, command, + min_px_width=min_px_width, height=height, font_size=font_size + ) \ No newline at end of file diff --git a/views/toast_chat.py b/views/toast_chat.py new file mode 100644 index 0000000..4012570 --- /dev/null +++ b/views/toast_chat.py @@ -0,0 +1,210 @@ +import datetime +import tkinter as tk +from PIL import Image, ImageTk +from views.theme import BG_COLOR, FG_COLOR, ACCENT_ORANGE + +class ToastChat(tk.Frame): + """ + Stapelt einzelne Chat-Banner (chat_window_2.png) rechts unten. + - Im laufenden Spiel: maximal 3 Banner, blenden 3.5s nach der Bot-Runde automatisch aus. + - Am Spielende: bis zu 8 Banner gleichzeitig, bleiben lange sichtbar. + """ + def __init__(self, root_window): + super().__init__(root_window, bg=BG_COLOR, bd=0, highlightthickness=0) + self.root = root_window + self.assets = getattr(root_window, "assets", None) + + self.history = [] # Komplette Historie des Spiels (für Protokoll) + self.visible_messages = [] # Aktuell angezeigte Banner + self.queue = [] # Warteschlange für sanftes Nacheinander-Einblenden + self._queue_running = False + self._msg_counter = 0 + self._scroll_offset = 0 + self._fade_job = None + + # Dynamische Konfiguration: 3 im Spiel, 8 beim Spielende + self.max_visible = 3 + self.auto_hide_ms = 3800 + + self.item_w = 430 + self.item_h = 38 + self.gap = 3 + self.item_photo = None + + if self.assets and getattr(self.assets, "raw_chat_bg", None): + resized = self.assets.raw_chat_bg.resize((self.item_w, self.item_h), Image.Resampling.LANCZOS) + self.item_photo = ImageTk.PhotoImage(resized) + + def clear_history(self): + """Löscht Protokoll und setzt das Limit bei einem neuen Spiel wieder auf 3 zurück.""" + self.history.clear() + self.visible_messages.clear() + self.queue.clear() + self._scroll_offset = 0 + self._queue_running = False + self.max_visible = 3 + self.auto_hide_ms = 3800 + if self._fade_job: + try: + self.after_cancel(self._fade_job) + except Exception: + pass + self._fade_job = None + self.place_forget() + + def set_endgame_mode(self, enabled=True): + """Schaltet am Spielende auf bis zu 8 Nachrichten um.""" + if enabled: + self.max_visible = 8 + self.auto_hide_ms = 25000 # Am Spielende lange stehen lassen + else: + self.max_visible = 3 + self.auto_hide_ms = 3800 + self._scroll_offset = 0 + self._update_visible_slice() + self._render() + + def schedule_hide(self, delay_ms=3500): + """Blendet die Toast-Banner nach delay_ms (z.B. 3.5s nach Ende der Bot-Runde) aus.""" + if self._fade_job: + try: + self.after_cancel(self._fade_job) + except Exception: + pass + + def try_hide(): + # Falls die Queue gerade noch die letzte Nachricht abarbeitet, kurz warten + if self._queue_running or self.queue: + self._fade_job = self.after(600, try_hide) + else: + self._auto_hide() + + self._fade_job = self.after(delay_ms, try_hide) + + def add_message(self, sender, text, is_self_taunt=False, is_roll_log=False): + if self.history and self.history[-1]["sender"] == sender and self.history[-1]["text"] == text: + return + + if is_roll_log: + color = "#00E676" + elif is_self_taunt: + color = ACCENT_ORANGE + else: + color = "#FF4444" + + self.queue.append((sender, text, color, is_roll_log)) + if not self._queue_running: + self._process_queue() + + def _process_queue(self): + if not self.queue: + self._queue_running = False + return + + self._queue_running = True + sender, text, color, is_roll_log = self.queue.pop(0) + + self._msg_counter += 1 + timestamp = datetime.datetime.now().strftime("%H:%M:%S") + msg_obj = { + "id": self._msg_counter, + "time": timestamp, + "sender": sender, + "text": text, + "color": color, + "is_roll_log": is_roll_log + } + + self.history.append(msg_obj) + self._scroll_offset = 0 + self._update_visible_slice() + self._render() + + # Timer nach jeder Nachricht frisch aufsetzen + if self._fade_job: + try: + self.after_cancel(self._fade_job) + except Exception: + pass + self._fade_job = self.after(self.auto_hide_ms, self._auto_hide) + + # Nächste Nachricht nach 650ms einblenden + self.after(650, self._process_queue) + + def _update_visible_slice(self): + total = len(self.history) + end_idx = max(0, total - self._scroll_offset) + start_idx = max(0, end_idx - self.max_visible) + self.visible_messages = self.history[start_idx:end_idx] + + def _on_mousewheel(self, direction): + if len(self.history) <= self.max_visible: + return + max_offset = len(self.history) - self.max_visible + self._scroll_offset = max(0, min(max_offset, self._scroll_offset + direction)) + self._update_visible_slice() + self._render() + + if self._fade_job: + try: + self.after_cancel(self._fade_job) + except Exception: + pass + self._fade_job = self.after(5000, self._auto_hide) + + def _auto_hide(self): + self.visible_messages.clear() + self._render() + + def _render(self): + if not self.winfo_exists(): + return + + for child in self.winfo_children(): + child.destroy() + + if not self.visible_messages: + self.place_forget() + return + + for msg in self.visible_messages: + c = tk.Canvas( + self, width=self.item_w, height=self.item_h, + bg=BG_COLOR, bd=0, highlightthickness=0, cursor="hand2" + ) + c.pack(side="top", pady=self.gap // 2) + + if self.item_photo: + c.create_image(0, 0, image=self.item_photo, anchor="nw") + else: + c.create_rectangle( + 2, 2, self.item_w - 2, self.item_h - 2, + outline="#FF0000", fill="#14131D", width=2 + ) + + y_center = self.item_h // 2 + sender_str = f"[{msg['sender']}]: " + + sender_id = c.create_text( + 22, y_center, text=sender_str, + font=("Helvetica", 9, "bold"), fill=msg["color"], anchor="w" + ) + bbox = c.bbox(sender_id) + text_x = bbox[2] + 4 if bbox else 105 + + c.create_text( + text_x, y_center, text=msg["text"], + font=("Helvetica", 9), fill=FG_COLOR, anchor="w", + width=self.item_w - text_x - 20 + ) + + c.bind("", lambda e: self.root.show_chat_log_dialog()) + c.bind("", lambda e: self._on_mousewheel(1)) + c.bind("", lambda e: self._on_mousewheel(-1)) + c.bind("", lambda e: self._on_mousewheel(1 if e.delta > 0 else -1)) + + total_h = len(self.visible_messages) * (self.item_h + self.gap) + self.place(relx=0.985, rely=0.985, width=self.item_w, height=total_h, anchor="se") + self.lift() + self.after(60, self.lift) + self.after(300, self.lift) \ No newline at end of file diff --git a/yahtzee_profiles.db b/yahtzee_profiles.db index fe96a37..e0430fd 100644 Binary files a/yahtzee_profiles.db and b/yahtzee_profiles.db differ