feat: add 10er raus, Pyramid & TriPeaks Solitaire, custom game icons and Linux DB path fix

This commit is contained in:
thw 2026-11-24 20:50:08 +01:00
parent c5e303db9f
commit 8acff1058a
55 changed files with 4443 additions and 188 deletions

View File

@ -71,6 +71,12 @@ if "%DO_WIN%"=="0" if "%DO_UNIX%"=="0" if "%DO_OSX%"=="0" (
set "RAW_ARGS=--Win" set "RAW_ARGS=--Win"
) )
REM --- Echte Lauf-Erfolgsflags initialisieren ---
set "WIN_OK=0"
set "UNIX_OK=0"
set "OSX_OK=0"
set "ANY_FAILED=0"
REM ---------------------------------------------------- REM ----------------------------------------------------
REM 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!) REM 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!)
REM ---------------------------------------------------- REM ----------------------------------------------------
@ -136,82 +142,14 @@ REM ====================================================
if "%DO_WIN%"=="1" ( if "%DO_WIN%"=="1" (
echo. echo.
echo ---^> [WIN] Baue Windows Single-File .exe... echo ---^> [WIN] Baue Windows Single-File .exe...
call :FIND_PYTHON if exist "%PROJECT_ROOT%\dist\windows" rmdir /s /q "%PROJECT_ROOT%\dist\windows"
if "!WIN_PY!"=="" ( call :BUILD_WIN_TARGET
echo [BOOTSTRAP] Installiere Python 3.11 via winget...
winget install -e --id Python.Python.3.11 --scope machine --accept-source-agreements --accept-package-agreements
for %%P in ("%ProgramFiles%\Python311" "%LocalAppData%\Programs\Python\Python311" "C:\Python311") do (
if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!"
)
call :FIND_PYTHON
)
if "!WIN_PY!"=="" (
echo [ERROR] Python 3.11+ nicht gefunden!
exit /b 1
)
if "!DB_REBUILT!"=="0" (
call :REBUILD_INTERNAL_DB
if errorlevel 1 (
echo [ERROR] Erstellung von internal_base.db fehlgeschlagen!
if "%IS_ELEVATED%"=="1" pause
exit /b 1
)
)
!WIN_PY! -m pip --version >nul 2>nul
if errorlevel 1 !WIN_PY! -m ensurepip --upgrade
!WIN_PY! -c "import PIL, pygame, PyInstaller" >nul 2>nul
if errorlevel 1 ( if errorlevel 1 (
echo [BOOTSTRAP] Installiere Pillow, Pygame ^& PyInstaller... set "WIN_OK=0"
!WIN_PY! -m pip install --upgrade pip pillow pygame pyinstaller set "ANY_FAILED=1"
if errorlevel 1 exit /b 1 ) else (
set "WIN_OK=1"
) )
set "ICON_ARG="
if exist "%PROJECT_ROOT%\resources\images\game_icon.ico" (
set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico"
)
set "VER_ARG="
if exist "%PROJECT_ROOT%\build_scripts\version_info.txt" (
set "VER_ARG=--version-file %PROJECT_ROOT%\build_scripts\version_info.txt"
)
!WIN_PY! -m PyInstaller ^
--noconfirm ^
--noconsole ^
--onefile ^
--noupx ^
--clean ^
--distpath "%PROJECT_ROOT%\dist\windows" ^
--workpath "%PROJECT_ROOT%\build\windows" ^
--specpath "%PROJECT_ROOT%\build\windows" ^
!ICON_ARG! ^
!VER_ARG! ^
--add-data "%PROJECT_ROOT%\resources;resources" ^
--add-data "%PROJECT_ROOT%\games;games" ^
--collect-submodules games ^
--collect-submodules controller ^
--collect-submodules models ^
--collect-submodules view ^
--collect-submodules resources ^
--hidden-import tkinter ^
--hidden-import tkinter.ttk ^
--hidden-import tkinter.font ^
--hidden-import sqlite3 ^
--hidden-import PIL._tkinter_finder ^
--name "%APP_NAME%" ^
"%PROJECT_ROOT%\main.py"
if errorlevel 1 (
echo [ERROR] Windows-Build fehlgeschlagen!
if "%IS_ELEVATED%"=="1" pause
exit /b 1
)
if exist "%PROJECT_ROOT%\build\windows" rmdir /s /q "%PROJECT_ROOT%\build\windows"
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe
) )
REM ==================================================== REM ====================================================
@ -220,7 +158,14 @@ REM ====================================================
if "%DO_UNIX%"=="1" ( if "%DO_UNIX%"=="1" (
echo. echo.
echo ---^> [UNIX] Baue Linux Executable via VirtualBox VM "%UNIX_VM_NAME%"... echo ---^> [UNIX] Baue Linux Executable via VirtualBox VM "%UNIX_VM_NAME%"...
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux"
call :RUN_UNIX_VM_BUILD call :RUN_UNIX_VM_BUILD
if errorlevel 1 (
set "UNIX_OK=0"
set "ANY_FAILED=1"
) else (
set "UNIX_OK=1"
)
) )
REM ==================================================== REM ====================================================
@ -229,34 +174,47 @@ REM ====================================================
if "%DO_OSX%"=="1" ( if "%DO_OSX%"=="1" (
echo. echo.
echo ---^> [OSX] Baue macOS Binary via VirtualBox VM "%OSX_VM_NAME%"... echo ---^> [OSX] Baue macOS Binary via VirtualBox VM "%OSX_VM_NAME%"...
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos"
call :RUN_OSX_VM_BUILD call :RUN_OSX_VM_BUILD
if errorlevel 1 (
set "OSX_OK=0"
set "ANY_FAILED=1"
) else (
set "OSX_OK=1"
)
) )
echo. echo.
echo ==================================================== echo ====================================================
echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^): echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^):
if "%DO_WIN%"=="1" ( if "%DO_WIN%"=="1" (
if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" ( if "!WIN_OK!"=="1" if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
echo [WIN] OK: dist\windows\%APP_NAME%.exe echo [WIN] OK: dist\windows\%APP_NAME%.exe
) else ( ) else (
echo [WIN] FEHLGESCHLAGEN echo [WIN] FEHLGESCHLAGEN!
) )
) )
if "%DO_UNIX%"=="1" ( if "%DO_UNIX%"=="1" (
if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" ( if "!UNIX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^) echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^)
) else ( ) else (
echo [UNIX] FEHLGESCHLAGEN echo [UNIX] FEHLGESCHLAGEN! ^(VM "%UNIX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
) )
) )
if "%DO_OSX%"=="1" ( if "%DO_OSX%"=="1" (
if exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" ( if "!OSX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
echo [OSX] OK: dist\macos\%APP_NAME% ^(+ %APP_NAME%.app + %APP_NAME%_macOS.tar.gz^) echo [OSX] OK: dist\macos\%APP_NAME% ^(+ %APP_NAME%.app + %APP_NAME%_macOS.tar.gz^)
) else ( ) else (
echo [OSX] FEHLGESCHLAGEN echo [OSX] FEHLGESCHLAGEN! ^(VM "%OSX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
) )
) )
echo ==================================================== echo ====================================================
if "!ANY_FAILED!"=="1" (
echo [ERROR] Mindestens ein angefordertes Build-Ziel ist fehlgeschlagen!
if "%IS_ELEVATED%"=="1" pause
endlocal
exit /b 1
)
if "%IS_ELEVATED%"=="1" pause if "%IS_ELEVATED%"=="1" pause
endlocal endlocal
exit /b 0 exit /b 0
@ -265,6 +223,84 @@ exit /b 0
REM ==================================================== REM ====================================================
REM HILFSROUTINEN REM HILFSROUTINEN
REM ==================================================== REM ====================================================
:BUILD_WIN_TARGET
call :FIND_PYTHON
if "!WIN_PY!"=="" (
echo [BOOTSTRAP] Installiere Python 3.11 via winget...
winget install -e --id Python.Python.3.11 --scope machine --accept-source-agreements --accept-package-agreements
for %%P in ("%ProgramFiles%\Python311" "%LocalAppData%\Programs\Python\Python311" "C:\Python311") do (
if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!"
)
call :FIND_PYTHON
)
if "!WIN_PY!"=="" (
echo [ERROR] Python 3.11+ nicht gefunden!
exit /b 1
)
if "!DB_REBUILT!"=="0" (
call :REBUILD_INTERNAL_DB
if errorlevel 1 exit /b 1
)
!WIN_PY! -m pip --version >nul 2>nul
if errorlevel 1 !WIN_PY! -m ensurepip --upgrade
!WIN_PY! -c "import PIL, pygame, PyInstaller" >nul 2>nul
if errorlevel 1 (
echo [BOOTSTRAP] Installiere Pillow, Pygame ^& PyInstaller...
!WIN_PY! -m pip install --upgrade pip pillow pygame pyinstaller
if errorlevel 1 exit /b 1
)
set "ICON_ARG="
if exist "%PROJECT_ROOT%\resources\images\game_icon.ico" (
set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico"
)
set "VER_ARG="
if exist "%PROJECT_ROOT%\build_scripts\version_info.txt" (
set "VER_ARG=--version-file %PROJECT_ROOT%\build_scripts\version_info.txt"
)
!WIN_PY! -m PyInstaller ^
--noconfirm ^
--noconsole ^
--onefile ^
--noupx ^
--clean ^
--distpath "%PROJECT_ROOT%\dist\windows" ^
--workpath "%PROJECT_ROOT%\build\windows" ^
--specpath "%PROJECT_ROOT%\build\windows" ^
!ICON_ARG! ^
!VER_ARG! ^
--add-data "%PROJECT_ROOT%\resources;resources" ^
--add-data "%PROJECT_ROOT%\games;games" ^
--collect-submodules games ^
--collect-submodules controller ^
--collect-submodules models ^
--collect-submodules view ^
--collect-submodules resources ^
--hidden-import tkinter ^
--hidden-import tkinter.ttk ^
--hidden-import tkinter.font ^
--hidden-import sqlite3 ^
--hidden-import PIL._tkinter_finder ^
--name "%APP_NAME%" ^
"%PROJECT_ROOT%\main.py"
if errorlevel 1 (
echo [ERROR] Windows-Build fehlgeschlagen!
exit /b 1
)
if exist "%PROJECT_ROOT%\build\windows" rmdir /s /q "%PROJECT_ROOT%\build\windows"
if not exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
echo [ERROR] Erwartete Datei dist\windows\%APP_NAME%.exe wurde nicht erzeugt!
exit /b 1
)
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe
exit /b 0
:REBUILD_INTERNAL_DB :REBUILD_INTERNAL_DB
set "REBUILD_PY=" set "REBUILD_PY="
if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" ( if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
@ -273,11 +309,18 @@ if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
if exist "%PROJECT_ROOT%\rebuild_internal_db.py" ( if exist "%PROJECT_ROOT%\rebuild_internal_db.py" (
set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py" set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py"
) )
if not "!REBUILD_PY!"=="" if exist "%PROJECT_ROOT%\resources\code_res\sql" ( if not "!REBUILD_PY!"=="" (
echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien... if exist "%PROJECT_ROOT%\build_scripts\sql" (
!WIN_PY! "!REBUILD_PY!" echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien...
if errorlevel 1 exit /b 1 !WIN_PY! "!REBUILD_PY!"
set "DB_REBUILT=1" if errorlevel 1 exit /b 1
set "DB_REBUILT=1"
) else if exist "%PROJECT_ROOT%\resources\code_res\sql" (
echo ---^> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien...
!WIN_PY! "!REBUILD_PY!"
if errorlevel 1 exit /b 1
set "DB_REBUILT=1"
)
) )
exit /b 0 exit /b 0
@ -322,16 +365,25 @@ if "!VBOX_MANAGE!"=="" if exist "D:\Program Files\Oracle\VirtualBox\VBoxManage.e
) )
exit /b 0 exit /b 0
:PRINT_AVAILABLE_VMS
echo [HINWEIS] Registrierte VirtualBox-VMs fuer Benutzer "%USERNAME%":
"!VBOX_MANAGE!" list vms
if "%IS_ADMIN%"=="1" (
echo [HINWEIS] Das Skript laeuft als Administrator ^(ggf. anderes VirtualBox-Benutzerverzeichnis^)!
)
exit /b 0
:RUN_UNIX_VM_BUILD :RUN_UNIX_VM_BUILD
call :FIND_VBOX call :FIND_VBOX
if "!VBOX_MANAGE!"=="" ( if "!VBOX_MANAGE!"=="" (
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe Linux-VM-Build. echo [ERROR] VBoxManage.exe nicht gefunden - Linux-VM-Build fehlgeschlagen!
exit /b 1 exit /b 1
) )
"!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul "!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden! echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden!
call :PRINT_AVAILABLE_VMS
exit /b 1 exit /b 1
) )
@ -371,13 +423,17 @@ echo [UNIX-VM] Aktualisiere Projektquellen in "%UNIX_VM_NAME%"...
set "TMP_TAR_UNIX=%TEMP%\goth_unix_src.tar.gz" set "TMP_TAR_UNIX=%TEMP%\goth_unix_src.tar.gz"
if exist "!TMP_TAR_UNIX!" del /q "!TMP_TAR_UNIX!" if exist "!TMP_TAR_UNIX!" del /q "!TMP_TAR_UNIX!"
tar -czf "!TMP_TAR_UNIX!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" . tar -czf "!TMP_TAR_UNIX!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
if errorlevel 1 exit /b 1
ssh -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "mkdir -p %UNIX_REMOTE_DIR% && find %UNIX_REMOTE_DIR% -mindepth 1 -maxdepth 1 ! -name '.venv' -exec rm -rf {} +" ssh -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "mkdir -p %UNIX_REMOTE_DIR% && find %UNIX_REMOTE_DIR% -mindepth 1 -maxdepth 1 -not -name '.venv' -exec rm -rf {} +"
if errorlevel 1 exit /b 1
scp -P %UNIX_SSH_PORT% "!TMP_TAR_UNIX!" %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/src.tar.gz scp -P %UNIX_SSH_PORT% "!TMP_TAR_UNIX!" %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/src.tar.gz
set "SCP_ERR=!ERRORLEVEL!"
del /q "!TMP_TAR_UNIX!" 2>nul del /q "!TMP_TAR_UNIX!" 2>nul
if not "!SCP_ERR!"=="0" exit /b 1
echo [UNIX-VM] Kompiliere native Linux-ELF-Binary in der VM... echo [UNIX-VM] Kompiliere native Linux-ELF-Binary in der VM...
ssh -t -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "cd %UNIX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && tr -d '\r' < build_scripts/build.sh > build_scripts/_unix.sh && mv build_scripts/_unix.sh build_scripts/build.sh && chmod +x build_scripts/build.sh && ( [ -d .venv ] || python3 -m venv .venv || (sudo apt-get update -qq && sudo apt-get install -y python3-venv python3-tk python3-pip libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libfreetype6-dev && python3 -m venv .venv) ) && ./build_scripts/build.sh --Unix && tar --warning=no-file-changed -czf dist/%APP_NAME%_Linux.tar.gz -C dist/linux ." ssh -t -p %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST% "bash -lc 'set -e; cd %UNIX_REMOTE_DIR%; rm -rf dist build; tar -xzf src.tar.gz; rm -f src.tar.gz; tr -d \"\r\" < build_scripts/build.sh > build_scripts/_unix.sh; mv build_scripts/_unix.sh build_scripts/build.sh; chmod +x build_scripts/build.sh; if [ -d .venv ]; then :; else python3 -m venv .venv || (sudo apt-get update -qq && sudo apt-get install -y python3-venv python3-tk python3-pip libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libfreetype6-dev && python3 -m venv .venv); fi; ./build_scripts/build.sh --Unix; mkdir -p dist; rm -f dist/%APP_NAME%_Linux.tar.gz; tar --warning=no-file-changed -czf dist/%APP_NAME%_Linux.tar.gz -C dist/linux .'"
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] Linux-Build in der VM fehlgeschlagen! echo [ERROR] Linux-Build in der VM fehlgeschlagen!
@ -385,9 +441,7 @@ if errorlevel 1 (
exit /b 1 exit /b 1
) )
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux" mkdir "%PROJECT_ROOT%\dist\linux" 2>nul
mkdir "%PROJECT_ROOT%\dist\linux"
echo [UNIX-VM] Lade fertiges Linux-Build nach dist\linux herunter... echo [UNIX-VM] Lade fertiges Linux-Build nach dist\linux herunter...
scp -P %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/dist/%APP_NAME%_Linux.tar.gz "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz" scp -P %UNIX_SSH_PORT% %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_REMOTE_DIR%/dist/%APP_NAME%_Linux.tar.gz "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz"
if errorlevel 1 ( if errorlevel 1 (
@ -395,6 +449,10 @@ if errorlevel 1 (
exit /b 1 exit /b 1
) )
tar -xzf "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz" -C "%PROJECT_ROOT%\dist\linux" tar -xzf "%PROJECT_ROOT%\dist\linux\%APP_NAME%_Linux.tar.gz" -C "%PROJECT_ROOT%\dist\linux"
if not exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
echo [ERROR] Linux-Binary dist\linux\%APP_NAME% fehlt nach dem Entpacken!
exit /b 1
)
if "!UNIX_VM_WAS_RUNNING!"=="0" ( if "!UNIX_VM_WAS_RUNNING!"=="0" (
echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter... echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter...
@ -406,13 +464,14 @@ exit /b 0
:RUN_OSX_VM_BUILD :RUN_OSX_VM_BUILD
call :FIND_VBOX call :FIND_VBOX
if "!VBOX_MANAGE!"=="" ( if "!VBOX_MANAGE!"=="" (
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe macOS-VM-Build. echo [ERROR] VBoxManage.exe nicht gefunden - macOS-VM-Build fehlgeschlagen!
exit /b 1 exit /b 1
) )
"!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul "!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden! echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden!
call :PRINT_AVAILABLE_VMS
exit /b 1 exit /b 1
) )
@ -452,29 +511,35 @@ echo [OSX-VM] Aktualisiere Projektquellen in der macOS-VM ^(.venv_build_macos bl
set "TMP_TAR=%TEMP%\goth_osx_src.tar.gz" set "TMP_TAR=%TEMP%\goth_osx_src.tar.gz"
if exist "!TMP_TAR!" del /q "!TMP_TAR!" if exist "!TMP_TAR!" del /q "!TMP_TAR!"
tar -czf "!TMP_TAR!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" . tar -czf "!TMP_TAR!" --exclude=".git" --exclude="dist" --exclude="build" --exclude=".venv*" --exclude="__pycache__" -C "%PROJECT_ROOT%" .
if errorlevel 1 exit /b 1
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "mkdir -p %OSX_REMOTE_DIR% && find %OSX_REMOTE_DIR% -mindepth 1 -maxdepth 1 ! -name '.venv_build_macos' -exec rm -rf {} +" ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "mkdir -p %OSX_REMOTE_DIR% && find %OSX_REMOTE_DIR% -mindepth 1 -maxdepth 1 -not -name '.venv_build_macos' -exec rm -rf {} +"
if errorlevel 1 exit /b 1
scp -P %OSX_SSH_PORT% "!TMP_TAR!" %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/src.tar.gz scp -P %OSX_SSH_PORT% "!TMP_TAR!" %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/src.tar.gz
set "SCP_OSX_ERR=!ERRORLEVEL!"
del /q "!TMP_TAR!" 2>nul del /q "!TMP_TAR!" 2>nul
if not "!SCP_OSX_ERR!"=="0" exit /b 1
echo [OSX-VM] Kompiliere native macOS-Binary + .app Bundle in der VM... echo [OSX-VM] Kompiliere native macOS-Binary + .app Bundle in der VM...
ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:$PATH; cd %OSX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && ( [ -x .venv_build_macos/bin/python3 ] || (rm -rf .venv_build_macos && python3 -m venv .venv_build_macos) ) && ( .venv_build_macos/bin/python3 -c 'import PIL, pygame, PyInstaller' >/dev/null 2>&1 || .venv_build_macos/bin/python3 -m pip install --upgrade pip pillow pygame pyinstaller ) && ICON_OPT=''; if [ -f resources/images/game_icon.icns ]; then ICON_OPT='--icon resources/images/game_icon.icns'; elif [ -f resources/images/game_icon.ico ]; then ICON_OPT='--icon resources/images/game_icon.ico'; fi && .venv_build_macos/bin/python3 -m PyInstaller --noconfirm --windowed --onefile --noupx --clean --osx-bundle-identifier de.kuro.thegothcardgamecollection --distpath dist/macos --workpath build/macos --specpath build/macos $ICON_OPT --add-data 'resources:resources' --add-data 'games:games' --collect-submodules games --collect-submodules controller --collect-submodules models --collect-submodules view --collect-submodules resources --hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font --hidden-import sqlite3 --hidden-import PIL._tkinter_finder --name %APP_NAME% main.py && chmod +x dist/macos/%APP_NAME% 2>/dev/null || true && rm -rf build/macos && tar -czf dist/macos/%APP_NAME%_macOS.tar.gz -C dist/macos ." ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "/bin/bash -lc 'set -e; export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH; cd %OSX_REMOTE_DIR%; rm -rf dist build; tar -xzf src.tar.gz; rm -f src.tar.gz; if [ -x .venv_build_macos/bin/python3 ]; then :; else rm -rf .venv_build_macos && python3 -m venv .venv_build_macos; fi; .venv_build_macos/bin/python3 -c \"import PIL, pygame, PyInstaller\" >/dev/null 2>&1 || .venv_build_macos/bin/python3 -m pip install --upgrade pip pillow pygame pyinstaller; ICON_ARGS=(); if [ -f \"$PWD/resources/images/game_icon.icns\" ]; then ICON_ARGS=(--icon \"$PWD/resources/images/game_icon.icns\"); elif [ -f \"$PWD/resources/images/game_icon.ico\" ]; then ICON_ARGS=(--icon \"$PWD/resources/images/game_icon.ico\"); fi; .venv_build_macos/bin/python3 -m PyInstaller --noconfirm --windowed --onefile --noupx --clean --osx-bundle-identifier de.kuro.thegothcardgamecollection --distpath \"$PWD/dist/macos\" --workpath \"$PWD/build/macos\" --specpath \"$PWD/build/macos\" \"${ICON_ARGS[@]}\" --add-data \"$PWD/resources:resources\" --add-data \"$PWD/games:games\" --collect-submodules games --collect-submodules controller --collect-submodules models --collect-submodules view --collect-submodules resources --hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font --hidden-import sqlite3 --hidden-import PIL._tkinter_finder --name %APP_NAME% \"$PWD/main.py\"; chmod +x dist/macos/%APP_NAME%; rm -rf build/macos; tar -czf dist/%APP_NAME%_macOS.tar.gz -C dist/macos .'"
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] macOS-Build in der VM fehlgeschlagen! echo [ERROR] macOS-Build in der VM fehlgeschlagen!
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
exit /b 1 exit /b 1
) )
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos" mkdir "%PROJECT_ROOT%\dist\macos" 2>nul
mkdir "%PROJECT_ROOT%\dist\macos"
echo [OSX-VM] Lade fertiges macOS-Build nach dist\macos herunter... echo [OSX-VM] Lade fertiges macOS-Build nach dist\macos herunter...
scp -P %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/dist/macos/%APP_NAME%_macOS.tar.gz "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz" scp -P %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR%/dist/%APP_NAME%_macOS.tar.gz "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz"
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] Download des macOS-Artefakts fehlgeschlagen! echo [ERROR] Download des macOS-Artefakts fehlgeschlagen!
exit /b 1 exit /b 1
) )
tar -xzf "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz" -C "%PROJECT_ROOT%\dist\macos" tar -xzf "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz" -C "%PROJECT_ROOT%\dist\macos"
if not exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
echo [ERROR] macOS-Binary dist\macos\%APP_NAME% fehlt nach dem Entpacken!
exit /b 1
)
if "!VM_WAS_RUNNING!"=="0" ( if "!VM_WAS_RUNNING!"=="0" (
echo [OSX-VM] Fahre macOS-VM wieder sauber herunter... echo [OSX-VM] Fahre macOS-VM wieder sauber herunter...

0
games/party/__init__.py Normal file
View File

View File

View File

@ -0,0 +1,79 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/models/zehner_raus_ai.py
from __future__ import annotations
import random
from games.party.zehner_raus.models.zehner_raus_engine import (
ZehnerRausEngine,
ZehnerRausSeat,
)
from models.bavarian_deck import TEN_ORDER_INDEX, BavarianCard
class ZehnerRausBotAI:
"""KI-Entscheidungslogik (Stufen 0..6) für '10er raus'."""
@classmethod
def choose_card(
cls,
engine: ZehnerRausEngine,
bot: ZehnerRausSeat,
rng: random.Random | None = None,
) -> BavarianCard | None:
playable = engine.get_playable_cards(bot.seat_id)
if not playable:
return None
if len(playable) == 1:
return playable[0]
r = rng or random
lvl = max(0, min(6, int(bot.ai_level)))
if lvl == 0:
return r.choice(playable)
mistake_chance = {1: 0.45, 2: 0.25, 3: 0.12, 4: 0.05, 5: 0.0, 6: 0.0}[lvl]
if mistake_chance > 0.0 and r.random() < mistake_chance:
return r.choice(playable)
scored = [
(cls._evaluate_move(card, bot.hand, lvl), r.random(), card)
for card in playable
]
scored.sort(key=lambda item: (item[0], item[1]), reverse=True)
return scored[0][2]
@staticmethod
def _evaluate_move(
card: BavarianCard, hand: list[BavarianCard], ai_level: int
) -> float:
suit_indices = {c.order_index for c in hand if c.suit == card.suit}
idx = card.order_index
if idx == TEN_ORDER_INDEX:
own_rest = [i for i in suit_indices if i != TEN_ORDER_INDEX]
extremity_sum = sum(abs(i - TEN_ORDER_INDEX) for i in own_rest)
score = len(own_rest) * 3.2 + extremity_sum * 1.4
if not own_rest and ai_level >= 4:
score -= 6.5
return score
if idx > TEN_ORDER_INDEX:
own_above = [i for i in suit_indices if i > idx]
remaining_for_others = (8 - idx) - len(own_above)
score = len(own_above) * 4.5 + (idx - TEN_ORDER_INDEX) * 0.6
if idx == 8:
score += 2.0
elif not own_above and ai_level >= 3:
score -= remaining_for_others * (1.8 if ai_level >= 5 else 1.1)
return score
own_below = [i for i in suit_indices if i < idx]
remaining_for_others = idx - len(own_below)
score = len(own_below) * 4.5 + (TEN_ORDER_INDEX - idx) * 0.6
if idx == 0:
score += 2.0
elif not own_below and ai_level >= 3:
score -= remaining_for_others * (1.8 if ai_level >= 5 else 1.1)
return score

View File

@ -0,0 +1,166 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/models/zehner_raus_engine.py
from __future__ import annotations
from dataclasses import dataclass, field
import random
from models.bavarian_deck import (
BAVARIAN_RANKS,
TEN_ORDER_INDEX,
BavarianCard,
create_bavarian_deck,
)
from resources.code_res.game_constants import BAVARIAN_SUITS, ZR_NUM_PLAYERS
@dataclass
class ZehnerRausSeat:
seat_id: int
name: str
is_human: bool = False
ai_level: int = 1
hand: list[BavarianCard] = field(default_factory=list)
status_text: str = ""
passed_turns: int = 0
class ZehnerRausEngine:
"""
Regelwerk für '10er raus' (36 bayerische Karten, exakt 4 Spieler = je 9 Karten):
- Beliebiger Startspieler (rotiert nach der ersten Runde), es wird weitergeschoben
bis der erste einen 10er herauslegen kann.
- Von jedem gelegten 10er wächst die Farbreihe nach oben (U->O->K->A) und unten (9->8->7->6).
- Strikter Zugzwang: Wer eine passende Karte hat, MUSS legen; Passen ist nur ohne Zug erlaubt.
- Sobald der erste Spieler seine letzte Karte ablegt, endet die Runde sofort mit seinem Sieg!
"""
def __init__(self):
self.seats: list[ZehnerRausSeat] = []
self.lanes: dict[str, tuple[int, int] | None] = {
s: None for s in BAVARIAN_SUITS
}
self.turn_seat: int = 0
self.starter_seat: int = -1
self.winner_seat: int | None = None
self.turns_played: int = 0
self.last_played_card: BavarianCard | None = None
self.last_played_by: int | None = None
@property
def human_seat(self) -> ZehnerRausSeat:
return self.seats[0]
@property
def is_finished(self) -> bool:
return self.winner_seat is not None
def configure_seats(
self, human_name: str, bot_configs: list[tuple[int, str]]
) -> None:
self.seats = [ZehnerRausSeat(seat_id=0, name=human_name, is_human=True)]
for idx in range(1, ZR_NUM_PLAYERS):
if idx - 1 < len(bot_configs):
lvl, b_name = bot_configs[idx - 1]
else:
lvl, b_name = idx, f"Bot {idx}"
self.seats.append(
ZehnerRausSeat(
seat_id=idx, name=b_name, is_human=False, ai_level=lvl
)
)
def start_new_round(self, rng: random.Random | None = None) -> int:
r = rng or random
deck = create_bavarian_deck(include_six=True, shuffle=True, rng=r)
self.lanes = {s: None for s in BAVARIAN_SUITS}
self.winner_seat = None
self.turns_played = 0
self.last_played_card = None
self.last_played_by = None
suit_sort = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
for idx, seat in enumerate(self.seats):
chunk = deck[idx * 9 : (idx + 1) * 9]
chunk.sort(key=lambda c: (suit_sort[c.suit], c.order_index))
seat.hand = chunk
seat.status_text = ""
seat.passed_turns = 0
if self.starter_seat < 0:
self.starter_seat = r.randrange(ZR_NUM_PLAYERS)
else:
self.starter_seat = (self.starter_seat + 1) % ZR_NUM_PLAYERS
self.turn_seat = self.starter_seat
return self.turn_seat
def is_card_playable(self, card: BavarianCard) -> bool:
if self.is_finished:
return False
bounds = self.lanes[card.suit]
idx = card.order_index
if bounds is None:
return idx == TEN_ORDER_INDEX
low_idx, high_idx = bounds
return idx == low_idx - 1 or idx == high_idx + 1
def get_playable_cards(self, seat_id: int) -> list[BavarianCard]:
if self.is_finished or not (0 <= seat_id < len(self.seats)):
return []
return [c for c in self.seats[seat_id].hand if self.is_card_playable(c)]
def can_seat_pass(self, seat_id: int) -> bool:
return len(self.get_playable_cards(seat_id)) == 0
def play_card(self, seat_id: int, card: BavarianCard) -> bool:
if self.is_finished or seat_id != self.turn_seat:
return False
seat = self.seats[seat_id]
if card not in seat.hand or not self.is_card_playable(card):
return False
seat.hand.remove(card)
bounds = self.lanes[card.suit]
idx = card.order_index
if bounds is None:
self.lanes[card.suit] = (TEN_ORDER_INDEX, TEN_ORDER_INDEX)
else:
low_idx, high_idx = bounds
if idx < low_idx:
self.lanes[card.suit] = (idx, high_idx)
else:
self.lanes[card.suit] = (low_idx, idx)
self.last_played_card = card
self.last_played_by = seat_id
self.turns_played += 1
if not seat.hand:
self.winner_seat = seat_id
else:
self.turn_seat = (self.turn_seat + 1) % ZR_NUM_PLAYERS
return True
def pass_turn(self, seat_id: int) -> bool:
if self.is_finished or seat_id != self.turn_seat:
return False
if not self.can_seat_pass(seat_id):
return False
self.seats[seat_id].passed_turns += 1
self.turns_played += 1
self.turn_seat = (self.turn_seat + 1) % ZR_NUM_PLAYERS
return True
def lane_snapshot_ranks(self, suit: str) -> dict[str, str | int | None]:
bounds = self.lanes[suit]
if bounds is None:
return {"low": None, "ten": None, "high": None}
low_i, high_i = bounds
return {
"low": BAVARIAN_RANKS[low_i] if low_i < TEN_ORDER_INDEX else None,
"ten": "10",
"high": BAVARIAN_RANKS[high_i] if high_i > TEN_ORDER_INDEX else None,
"low_idx": low_i,
"high_idx": high_i,
}

View File

@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/start.py
from __future__ import annotations
from games.party.zehner_raus.views.zehner_raus_menu_view import ZehnerRausMenuView
from resources.code_res.game_constants import CAT_PARTY_OFFLINE
GAME_FOLDER_ID = "party/zehner_raus"
GAME_TITLE_KEY = "game_title_zehner_raus"
GAME_CATEGORY = CAT_PARTY_OFFLINE
def start_game(context) -> None:
ZehnerRausMenuView(context).show()

View File

@ -0,0 +1,394 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/views/zehner_raus_arena_renderer.py
from __future__ import annotations
from models.bavarian_deck import BAVARIAN_RANKS, TEN_ORDER_INDEX, BavarianCard
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
BAVARIAN_CARD_THEME,
BORDER_COLOR,
ERROR_FG,
FG_COLOR,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_SMALL_MIN,
MUTED_FG,
PLAYING_CARD_SIZE,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
ZR_BOT_BACK_SIZE = (42, 62)
ZR_MAX_HAND_CARD_H = 186
ZR_HAND_TOP_EXTEND_PX = 22
# Festes 2x2-Raster: Oben Eichel & Blatt, unten Herz & Schellen
ZR_GRID_SUITS = (
("E", 0, 0), # Oben links: Eichel
("B", 0, 1), # Oben rechts: Blatt
("H", 1, 0), # Unten links: Herz
("S", 1, 1), # Unten rechts: Schellen
)
class ZehnerRausArenaRenderer:
"""
Rendert für 10er raus:
- Außen links, oben und rechts die 3 Kultisten-Gegner
- Auf dem Tischfilz ein 2x2-Raster mit Mittelkreuz:
Oben: Eichel | Blatt
Unten: Herz | Schellen
- Unten die vergrößerte Spielerhand mit Gold-Highlight für legbare Karten.
"""
@staticmethod
def draw_bots(
view,
cw: int,
ch: int,
pad_x: int,
pad_top: int,
table_rect: tuple[int, int, int, int],
) -> tuple[int, int, int]:
"""Zeichnet die 3 Bots und gibt (top_bot_bottom_y, left_bot_right_x, right_bot_left_x) zurück."""
tx1, ty1, tx2, ty2 = table_rect
bots = view.engine.seats[1:]
if len(bots) < 3:
return ty1 + 20, tx1 + 60, tx2 - 60
box_w, box_h = 220, 90
mid_side_y = (ty1 + ty2) // 2 - 18
top_cy = max(pad_top + box_h // 2 - 6, ty1 + int(box_h * 0.30))
left_cx = max(pad_x + box_w // 2 - 10, tx1 + int(box_w * 0.24))
right_cx = min(cw - pad_x - box_w // 2 + 10, tx2 - int(box_w * 0.24))
coords = [
(left_cx, mid_side_y), # Sitz 1: Links
(cw // 2, top_cy), # Sitz 2: Oben Mitte
(right_cx, mid_side_y), # Sitz 3: Rechts
]
name_sz = max(14, FONT_SIZE_BODY - 1)
sub_sz = max(12, FONT_SIZE_SMALL_MIN)
back_ph = view.ctx.assets.get_card_back_photo(
size=ZR_BOT_BACK_SIZE, theme=BAVARIAN_CARD_THEME
)
if back_ph is not None:
view._photo_refs.append(back_ph)
for idx, seat in enumerate(bots[:3]):
bx, by = coords[idx]
is_turn = not view.engine.is_finished and view.engine.turn_seat == seat.seat_id
n_cards = len(seat.hand)
warn_last = n_cards == 1
view._draw_framed_panel(
bx,
by,
box_w,
box_h,
frame_style="gold" if is_turn else "purple",
status_border=ERROR_FG if warn_last else None,
)
if back_ph is not None and n_cards > 0:
vis_backs = min(5, n_cards)
step_b = 9
bx0 = bx - box_w // 2 + 14
by0 = by - ZR_BOT_BACK_SIZE[1] // 2
for bi in range(vis_backs):
view.arena_canvas.create_image(
bx0 + bi * step_b, by0, image=back_ph, anchor="nw", tags="fg"
)
txt_cx = bx + 30
max_tw = box_w - 96
else:
txt_cx = bx
max_tw = box_w - 28
n_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
cnt_txt = (
t("zr_bot_one_card_left")
if warn_last
else t("zr_bot_cards_left", n_cards)
)
cnt_col = ERROR_FG if warn_last else ACCENT_GOLD
act_txt = seat.status_text or "-"
n_ph = view._make_goth_photo(seat.name, name_sz, n_col, max_tw)
c_ph = view._make_goth_photo(cnt_txt, sub_sz, cnt_col, max_tw)
a_ph = view._make_goth_photo(act_txt, sub_sz, FG_COLOR, max_tw)
view._place_goth_photo_or_fallback(txt_cx, by - 22, n_ph, seat.name, name_sz, n_col)
view._place_goth_photo_or_fallback(txt_cx, by, c_ph, cnt_txt, sub_sz, cnt_col)
view._place_goth_photo_or_fallback(txt_cx, by + 22, a_ph, act_txt, sub_sz, FG_COLOR)
return (
top_cy + box_h // 2,
left_cx + box_w // 2,
right_cx - box_w // 2,
)
@staticmethod
def draw_bavarian_lanes(
view,
table_rect: tuple[int, int, int, int],
bot_bounds: tuple[int, int, int],
player_top_y: int,
) -> None:
"""
Zeichnet die 4 Farben kompakt in einem 2x2-Raster direkt auf den Tischfilz
(ohne Hintergrundkasten, nur getrennt durch ein sauberes Mittelkreuz):
Oben: Eichel | Blatt
Unten: Herz | Schellen
"""
tx1, ty1, tx2, ty2 = table_rect
top_obs_y, left_obs_x, right_obs_x = bot_bounds
hand_real_top = player_top_y - ZR_HAND_TOP_EXTEND_PX
felt_top = max(ty1 + 14, top_obs_y + 8)
felt_bot = min(ty2 - 12, hand_real_top - 10)
avail_h = max(170, felt_bot - felt_top)
felt_left = max(tx1 + 48, left_obs_x + 16)
felt_right = min(tx2 - 48, right_obs_x - 16)
avail_w = max(440, felt_right - felt_left)
grid_w = min(avail_w, 840)
grid_h = min(avail_h, 268)
gx1 = (felt_left + felt_right - grid_w) // 2
gy1 = felt_top + max(0, (avail_h - grid_h) // 2)
gx2 = gx1 + grid_w
gy2 = gy1 + grid_h
mid_x = (gx1 + gx2) // 2
mid_y = (gy1 + gy2) // 2
# Nur das freistehende Mittelkreuz direkt auf dem Tischfilz (kein Kasten in den Ecken!)
view.arena_canvas.create_line(
mid_x, gy1 + 4, mid_x, gy2 - 4,
fill=BORDER_COLOR,
width=2,
tags="fg",
)
view.arena_canvas.create_line(
gx1 + 12, mid_y, gx2 - 12, mid_y,
fill=BORDER_COLOR,
width=2,
tags="fg",
)
quad_w = grid_w // 2
quad_h = grid_h // 2
hdr_h = 24
pad_qx = 14
base_w, base_h = PLAYING_CARD_SIZE
card_h = max(62, min(94, quad_h - hdr_h - 14))
card_w = max(43, int(round(base_w * (card_h / max(1, base_h)))))
card_sz = (card_w, card_h)
inner_cards_w = max(160, quad_w - 2 * pad_qx)
step_x = min(card_w + 3, max(19, (inner_cards_w - card_w) // 8))
span_cards_w = card_w + 8 * step_x
last_card = view.engine.last_played_card
for suit, r_idx, c_idx in ZR_GRID_SUITS:
qx1 = gx1 + c_idx * quad_w
qy1 = gy1 + r_idx * quad_h
q_cx = qx1 + quad_w // 2
bounds = view.engine.lanes[suit]
is_done = bounds is not None and bounds[0] == 0 and bounds[1] == 8
# Untere Zeile bekommt minimal Abstand zur horizontalen Kreuzlinie
lbl_y = qy1 + (15 if r_idx == 1 else 11)
suit_lbl = t(f"bav_suit_{suit}")
if is_done:
suit_lbl = f"{suit_lbl} ✓"
s_col = ACCENT_GOLD if is_done else FONT_COLOR_TITLE_MAIN
s_ph = view._make_goth_photo(suit_lbl, FONT_SIZE_SMALL_MIN, s_col, quad_w - 24)
view._place_goth_photo_or_fallback(
q_cx, lbl_y, s_ph, suit_lbl, FONT_SIZE_SMALL_MIN, s_col
)
cards_x0 = q_cx - span_cards_w // 2
row_top = qy1 + hdr_h + max(3, (quad_h - hdr_h - card_h) // 2)
row_cy = row_top + card_h // 2
ten_x = cards_x0 + TEN_ORDER_INDEX * step_x
if bounds is None:
view.arena_canvas.create_rectangle(
ten_x,
row_top,
ten_x + card_w,
row_top + card_h,
fill="",
outline=SUBTLE_BORDER,
width=2,
tags="fg",
)
view.arena_canvas.create_text(
ten_x + card_w // 2,
row_cy,
text="10",
font=("Georgia", max(11, card_w // 3), "bold"),
fill=MUTED_FG,
tags="fg",
)
continue
low_idx, high_idx = bounds
if low_idx > 0:
nx_low = cards_x0 + (low_idx - 1) * step_x
ZehnerRausArenaRenderer._draw_next_hint_slot(
view, nx_low, row_top, card_w, card_h, BAVARIAN_RANKS[low_idx - 1]
)
if high_idx < 8:
nx_high = cards_x0 + (high_idx + 1) * step_x
ZehnerRausArenaRenderer._draw_next_hint_slot(
view, nx_high, row_top, card_w, card_h, BAVARIAN_RANKS[high_idx + 1]
)
for r_i in range(low_idx, high_idx + 1):
cx_card = cards_x0 + r_i * step_x
ZehnerRausArenaRenderer._draw_lane_card(
view,
BavarianCard(suit, BAVARIAN_RANKS[r_i]),
cx_card,
row_top,
card_sz,
last_card,
)
@staticmethod
def _draw_next_hint_slot(
view, x: int, y: int, card_w: int, card_h: int, rank_txt: str
) -> None:
view.arena_canvas.create_rectangle(
x,
y,
x + card_w,
y + card_h,
fill="#120e1b",
outline="#2d2340",
dash=(3, 3),
width=1,
tags="fg",
)
view.arena_canvas.create_text(
x + card_w // 2,
y + card_h // 2,
text=rank_txt,
font=("Georgia", max(10, card_w // 4)),
fill="#5a4c73",
tags="fg",
)
@staticmethod
def _draw_lane_card(
view,
card: BavarianCard,
x: int,
y: int,
card_sz: tuple[int, int],
last_card: BavarianCard | None,
) -> None:
cw, ch = card_sz
if card.order_index == TEN_ORDER_INDEX:
view.arena_canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
outline=ACCENT_GOTH, width=1, tags="fg",
)
ph = view.ctx.assets.get_card_photo(
card.image_filename, size=card_sz, theme=BAVARIAN_CARD_THEME
)
if ph is not None:
view._photo_refs.append(ph)
view.arena_canvas.create_image(x, y, image=ph, anchor="nw", tags="fg")
if last_card == card:
view.arena_canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
outline=ACCENT_GOLD, width=2, tags="fg",
)
@staticmethod
def draw_human_hand(
view, cw: int, player_zone_top: int, player_zone_bot: int
) -> list[tuple[BavarianCard, int, int, int, int]]:
human = view.engine.human_seat
eff_top = max(230, player_zone_top - ZR_HAND_TOP_EXTEND_PX)
avail_h = max(170, player_zone_bot - eff_top)
zone_cy = (eff_top + player_zone_bot) // 2
base_w, base_h = PLAYING_CARD_SIZE
target_h = max(118, min(ZR_MAX_HAND_CARD_H, avail_h - 42))
scale = target_h / max(1, base_h)
card_w = max(80, int(round(base_w * scale)))
card_h = int(round(base_h * scale))
card_sz = (card_w, card_h)
is_my_turn = not view.engine.is_finished and view.engine.turn_seat == 0
playable_set = (
set(view.engine.get_playable_cards(0)) if is_my_turn else set()
)
n_cards = len(human.hand)
max_hand_w = max(380, cw - 180)
step = min(card_w + 10, max(44, (max_hand_w - card_w) // max(1, n_cards - 1)))
span_w = card_w + max(0, n_cards - 1) * step if n_cards else card_w
lbl_txt = t("zr_player_hand_lbl", n_cards)
lbl_sz = max(13, FONT_SIZE_BODY - 2)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN)
txt_w = lbl_ph.width() if lbl_ph is not None else 280
box_w = max(380, min(cw - 72, max(span_w + 76, txt_w + 68)))
box_h = min(avail_h + 6, card_h + 44)
box_cx = cw // 2
view._draw_framed_panel(
box_cx,
zone_cy,
box_w,
box_h,
frame_style="gold" if is_my_turn else "purple",
)
hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
start_x = box_cx - span_w // 2
base_top = (zone_cy - 10) - card_h // 2
for idx, card in enumerate(human.hand):
is_playable = card in playable_set
cx_left = start_x + idx * step
cy_top = base_top - (10 if is_playable else 0)
ph = view.ctx.assets.get_card_photo(
card.image_filename, size=card_sz, theme=BAVARIAN_CARD_THEME
)
if ph is not None:
view._photo_refs.append(ph)
view.arena_canvas.create_image(
cx_left, cy_top, image=ph, anchor="nw", tags="fg"
)
if is_playable:
view.arena_canvas.create_rectangle(
cx_left - 2,
cy_top - 2,
cx_left + card_w + 2,
cy_top + card_h + 2,
outline=ACCENT_GOLD,
width=2,
tags="fg",
)
hit_right = (cx_left + card_w) if idx == n_cards - 1 else (cx_left + step)
hit_rects.append((card, cx_left, cy_top, hit_right, cy_top + card_h))
view._place_goth_photo_or_fallback(
box_cx, zone_cy + box_h // 2 - 15, lbl_ph, lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN
)
return hit_rects

View File

@ -0,0 +1,237 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/views/zehner_raus_menu_view.py
from __future__ import annotations
import tkinter as tk
from games.party.zehner_raus.views.zehner_raus_table_view import ZehnerRausTableView
from models.database import Database
from resources.code_res.game_constants import (
BOT_LEVEL_COUNT,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
ZR_BOT_COUNT,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
GAME_FOLDER_ID = "party/zehner_raus"
GAME_TITLE_KEY = "game_title_zehner_raus"
class ZehnerRausMenuView:
"""Vorauswahl-Menü für 10er raus mit 3 festen Pflicht-Mitspielern (ohne Goldbeutel)."""
def __init__(self, context):
self.ctx = context
self._photo_refs: list = []
self._bot_entries: list[GothEntry] = []
self._bot_lvl_vars: list[tk.StringVar] = []
self._bot_dds: list[GothDropdown] = []
def _collect_and_save_bots(self) -> list[tuple[int, str]]:
pid = self.ctx.profile["id"]
lvl_by_label = {t(f"bot_level_{i}"): i for i in range(BOT_LEVEL_COUNT)}
active_bots: list[tuple[int, str]] = []
to_save: dict[int, tuple[str, int]] = {}
for idx in range(ZR_BOT_COUNT):
raw_name = (
self._bot_entries[idx].get().strip()
if idx < len(self._bot_entries)
else ""
)
b_name = raw_name or t("bot_default_name", idx + 1)
lvl = lvl_by_label.get(
self._bot_lvl_vars[idx].get(), min(BOT_LEVEL_COUNT - 1, idx + 1)
)
active_bots.append((lvl, b_name))
to_save[idx] = (b_name, lvl)
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
return active_bots
def show(self):
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self._bot_entries.clear()
self._bot_lvl_vars.clear()
self._bot_dds.clear()
self.ctx.refresh_game_progress()
def refresh_menu():
if self._bot_entries:
self._collect_and_save_bots()
self.show()
self.ctx.build_game_topbar(
self.ctx.root,
t("zr_menu_topbar"),
stats_endpoint=GAME_FOLDER_ID,
stats_enabled=True,
on_stats_back=refresh_menu,
on_lang_refresh=refresh_menu,
)
cv = MenuBodyCanvas(self.ctx)
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
ai_labels = [t(f"bot_level_{i}") for i in range(BOT_LEVEL_COUNT)]
for i in range(ZR_BOT_COUNT):
def_name = t("bot_default_name", i + 1)
def_lvl = min(BOT_LEVEL_COUNT - 1, i + 1)
if i in saved_bots:
s_name, s_lvl = saved_bots[i]
b_name = s_name or def_name
b_lvl = (
max(0, min(BOT_LEVEL_COUNT - 1, int(s_lvl)))
if int(s_lvl) >= 0
else def_lvl
)
else:
b_name, b_lvl = def_name, def_lvl
entry = GothEntry(
cv,
self.ctx.assets,
width=240,
height=36,
textvariable=tk.StringVar(value=b_name),
)
l_var = tk.StringVar(value=t(f"bot_level_{b_lvl}"))
dd = GothDropdown(
cv,
self.ctx.assets,
values=ai_labels,
textvariable=l_var,
sound_mgr=self.ctx.sounds,
width=270,
height=36,
)
self._bot_entries.append(entry)
self._bot_lvl_vars.append(l_var)
self._bot_dds.append(dd)
def start_round():
bots = self._collect_and_save_bots()
ZehnerRausTableView(
self.ctx,
variant_key="zehner_raus_std",
bot_configs=bots,
on_back_to_menu=self.show,
)
start_btn = ImageButton(
cv,
t("zr_start_btn"),
btn_fire,
btn_fire,
start_round,
sound_mgr=self.ctx.sounds,
width=210,
height=40,
style="fire",
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(22, int(h * 0.05))
title_ph = self.ctx.assets.get_goth_text_photo(
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
)
sub_ph = self.ctx.assets.get_goth_text_photo(
t("zr_menu_subtitle"),
FONT_SIZE_BODY,
FONT_COLOR_BODY_MUTED,
max_width=box_w,
align="left",
)
self._photo_refs.extend([title_ph, sub_ph])
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
cur_y += title_ph.height() + 4
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
cur_y += sub_ph.height() + 18
s1_ph = self.ctx.assets.get_goth_text_photo(
t("zr_rules_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(s1_ph)
cv.create_image(x_left + 6, cur_y, image=s1_ph, anchor="nw", tags="fg")
cur_y += s1_ph.height() + 6
r_box_h = 74
r_cy = cur_y + r_box_h // 2
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, r_box_h))
if r_box:
self._photo_refs.append(r_box)
cv.create_image(cx, r_cy, image=r_box, anchor="center", tags="fg")
v_ph = self.ctx.assets.get_goth_text_photo(
t("variant_zehner_raus_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
d_ph = self.ctx.assets.get_goth_text_photo(
t("zr_rule_summary"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 56, align="left"
)
self._photo_refs.extend([v_ph, d_ph])
cv.create_image(x_left + 28, r_cy - 14, image=v_ph, anchor="w", tags="fg")
cv.create_image(x_left + 28, r_cy + 15, image=d_ph, anchor="w", tags="fg")
cur_y += r_box_h + 18
s2_ph = self.ctx.assets.get_goth_text_photo(
t("zr_bots_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(s2_ph)
cv.create_image(x_left + 6, cur_y, image=s2_ph, anchor="nw", tags="fg")
cur_y += s2_ph.height() + 6
b_box_h = 236
b_cy = cur_y + b_box_h // 2
b_box = self.ctx.assets.get_box_photo("box_big", (box_w, b_box_h))
if b_box:
self._photo_refs.append(b_box)
cv.create_image(cx, b_cy, image=b_box, anchor="center", tags="fg")
dd_w = max(220, box_w - 430)
for idx in range(ZR_BOT_COUNT):
ry = cur_y + 38 + idx * 50
seat_lbl = self.ctx.assets.get_goth_text_photo(
t("zr_seat_lbl", idx + 2), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
self._photo_refs.append(seat_lbl)
cv.create_image(x_left + 32, ry, image=seat_lbl, anchor="w", tags="fg")
cv.create_window(x_left + 130, ry, window=self._bot_entries[idx], anchor="w", tags="fg")
dd = self._bot_dds[idx]
if dd._width != dd_w:
dd._width = dd_w
dd.configure(width=dd_w)
dd._render_closed()
cv.create_window(x_left + 390, ry, window=dd, anchor="w", tags="fg")
cv.create_window(
x_left + box_w - 32, cur_y + b_box_h - 36, window=start_btn, anchor="e", tags="fg"
)
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))

View File

@ -0,0 +1,175 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/views/zehner_raus_result_dialog.py
from __future__ import annotations
from resources.code_res.game_constants import (
BAVARIAN_CARD_THEME,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_SMALL_MIN,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
from view.widgets.image_button import ImageButton
MINI_BAV_CARD_SIZE = (42, 62)
class ZehnerRausResultDialog(CasinoResultDialogBase):
"""Ergebnis-Overlay für 10er raus (ohne Goldbeutel-Zeilen, mit Restkarten-Übersicht)."""
def __init__(
self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu
):
dlg_w = 720
dlg_h = 430 + (22 if result_data.get("new_level_title") else 0)
super().__init__(
parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu
)
def _build_scene(self):
"""Überschreibt den Gold-Fußbereich durch einen reinen XP- & Level-Abschluss."""
from PIL import Image, ImageTk
w, h = self._dlg_w, self._dlg_h
cx = w // 2
self._photo_refs.clear()
bg_src = (
self.assets.raw_bg_vertical
or self.assets.raw_bg_horizontal
or self.assets.raw_bg
)
if bg_src is not None:
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
self._photo_refs.append(bg_ph)
self.create_image(0, 0, image=bg_ph, anchor="nw")
outer_box = self.assets.get_box_photo("box_big", (w - 6, h - 6))
if outer_box:
self._photo_refs.append(outer_box)
self.create_image(cx, h // 2, image=outer_box, anchor="center")
p_won = bool(self.data.get("player_won"))
hl_ph = self.assets.get_goth_text_photo(
self.data["headline"],
24,
FONT_COLOR_TITLE_MAIN if p_won else FONT_COLOR_STATUS_LOSS,
max_width=w - 64,
)
self._photo_refs.append(hl_ph)
cur_y = 28
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
cur_y += hl_ph.height() + 12
cur_y = self._draw_showdown_middle(w, cx, cur_y)
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
cur_y += 14
xp_line = t("bj_popup_xp_earned", self.data["xp_gained"])
if self.data.get("new_level_title"):
xp_line = f"{xp_line} | {self.data['new_level_title']}"
xp_ph = self.assets.get_goth_text_photo(
xp_line,
FONT_SIZE_BODY + 1,
FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB,
max_width=w - 72,
)
self._photo_refs.append(xp_ph)
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
btn_y = h - 36
b_next = ImageButton(
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
self._handle_next, sound_mgr=self.sounds, width=205, height=38, style="fire",
)
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
self._handle_menu, sound_mgr=self.sounds, width=175, height=38, style="amethyst",
)
self.create_window(42, btn_y, window=b_next, anchor="w")
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
hdr_ph = self.assets.get_goth_text_photo(
t("zr_popup_remaining_hdr"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(hdr_ph)
self.create_image(36, cur_y + 10, image=hdr_ph, anchor="w")
cur_y += 24
seats = self.data.get("seats_summary", [])
cols = 2
gap_x, gap_y = 14, 10
card_w = (w - 72 - gap_x) // cols
card_h = 112
win_box = self.assets.get_box_photo("box_gold_small", (card_w, card_h))
std_box = self.assets.get_box_photo("box_purple", (card_w, card_h))
if win_box:
self._photo_refs.append(win_box)
if std_box:
self._photo_refs.append(std_box)
for idx, entry in enumerate(seats):
r_i, c_i = divmod(idx, cols)
sx = 36 + c_i * (card_w + gap_x) + card_w // 2
sy = cur_y + r_i * (card_h + gap_y) + card_h // 2
is_win = entry["is_winner"]
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
n_ph = self.assets.get_goth_text_photo(
entry["name"],
FONT_SIZE_SMALL_MIN + 2,
FONT_COLOR_TITLE_MAIN if is_win else FONT_COLOR_HEADING_SUB,
max_width=card_w - 28,
)
rem_txt = (
t("zr_popup_cards_zero")
if is_win
else t("zr_popup_cards_rem", len(entry["cards"]))
)
r_ph = self.assets.get_goth_text_photo(
rem_txt,
FONT_SIZE_SMALL_MIN,
FONT_COLOR_STATUS_WIN if is_win else FONT_COLOR_BODY_DEFAULT,
max_width=card_w - 28,
)
self._photo_refs.extend([n_ph, r_ph])
self.create_image(sx, sy - card_h // 2 + 19, image=n_ph, anchor="center")
self.create_image(sx, sy + card_h // 2 - 17, image=r_ph, anchor="center")
c_photos = [
ph
for img_name in entry["cards"]
if (
ph := self.assets.get_card_photo(
img_name, size=MINI_BAV_CARD_SIZE, theme=BAVARIAN_CARD_THEME
)
)
]
self._photo_refs.extend(c_photos)
if c_photos:
cw_m, ch_m = MINI_BAV_CARD_SIZE
n_c = len(c_photos)
step = min(22, max(12, (card_w - 36 - cw_m) // max(1, n_c - 1)))
span = cw_m + (n_c - 1) * step
x0 = sx - span // 2
for ci, cph in enumerate(c_photos):
self.create_image(x0 + ci * step, sy - ch_m // 2 + 1, image=cph, anchor="nw")
return cur_y + 2 * (card_h + gap_y) + 4

View File

@ -0,0 +1,314 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/views/zehner_raus_table_view.py
from __future__ import annotations
import time
import tkinter as tk
from games.party.zehner_raus.models.zehner_raus_ai import ZehnerRausBotAI
from games.party.zehner_raus.models.zehner_raus_engine import ZehnerRausEngine
from games.party.zehner_raus.views.zehner_raus_arena_renderer import (
ZehnerRausArenaRenderer,
)
from games.party.zehner_raus.views.zehner_raus_result_dialog import (
ZehnerRausResultDialog,
)
from models.bavarian_deck import BavarianCard
from models.progression import Progression
from resources.code_res.game_constants import ZR_BOT_TURN_DELAY_MS, ZR_VARIANTS
from resources.code_res.i18n import t
from view.widgets.casino_arena_base import CasinoArenaBase
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "party/zehner_raus"
class ZehnerRausTableView(CasinoArenaBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
def __init__(
self,
context,
variant_key: str,
bot_configs: list[tuple[int, str]],
on_back_to_menu,
):
v_key = variant_key if variant_key in ZR_VARIANTS else "zehner_raus_std"
cfg = ZR_VARIANTS[v_key]
self._init_arena_state(context, v_key, cfg, on_back_to_menu)
self._bot_configs = list(bot_configs)
self.engine = ZehnerRausEngine()
self.engine.configure_seats(self.ctx.profile["name"], self._bot_configs)
self.round_start_time: float = time.time()
self._hand_hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
self._last_popup_payload: dict | None = None
self.ctx.sounds.play_ingame_music()
self._build_ui()
self._start_new_round()
def _build_ui(self):
self._build_arena_shell(on_lang_refresh=self._on_language_switched)
self.arena_canvas.bind("<ButtonPress-1>", self._on_canvas_click)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
self._menu_btn = ImageButton(
self.bottom_bar,
t("bj_popup_to_menu_btn"),
btn_norm,
btn_purp,
lambda: self._cleanup_and_go(self.on_back_to_menu),
sound_mgr=self.ctx.sounds,
width=156,
height=30,
style="amethyst",
)
def _on_arena_resize_redraw(self):
self._render_table()
def _on_language_switched(self):
ImageButton.close_active_hover_tip()
self._cancel_fx_overlay()
self._build_ui()
self._render_table()
if self.engine.is_finished and self._last_popup_payload is not None:
self._open_result_popup(
self._localize_popup(self._last_popup_payload), play_fx=False
)
else:
self._sync_turn_controls()
def _refresh_header(self):
turn_name = (
self.engine.seats[self.engine.turn_seat].name
if not self.engine.is_finished
else "-"
)
hud_line = t(
"zr_hud_round_info",
turn_name,
len(self.engine.human_seat.hand),
self.engine.turns_played,
)
self._set_hud_segments(*hud_line.split("|"))
def _start_new_round(self):
self._cancel_jobs()
if self._result_dialog is not None:
self._result_dialog.close_dialog()
self._result_dialog = None
ImageButton.close_active_hover_tip()
self._last_popup_payload = None
self.round_start_time = time.time()
self.engine.start_new_round()
self.ctx.sounds.play("deal")
if not self._canvas_alive():
self._build_ui()
self._render_table()
self._process_turn()
def _render_table(self):
if not self._canvas_alive():
return
cw, ch, pad_x, pad_top, _pad_bot, p_top, p_bot, table_rect = (
self._prepare_arena_surface()
)
top_obs = ZehnerRausArenaRenderer.draw_bots(
self, cw, ch, pad_x, pad_top, table_rect
)
bot_bounds = ZehnerRausArenaRenderer.draw_bots(
self, cw, ch, pad_x, pad_top, table_rect
)
ZehnerRausArenaRenderer.draw_bavarian_lanes(
self, table_rect, bot_bounds, p_top
)
self._hand_hit_rects = ZehnerRausArenaRenderer.draw_human_hand(
self, cw, p_top, p_bot
)
if self.arena_canvas.find_withtag("modal_dim_veil"):
self.arena_canvas.tag_raise("modal_dim_veil")
self._refresh_header()
if self._result_dialog is not None and self._result_dialog.winfo_exists():
tk.Widget.tkraise(self._result_dialog)
def _sync_turn_controls(self):
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
return
if self.engine.is_finished:
self.status_var.set("")
self._set_bottom_buttons([])
return
if self.engine.turn_seat != 0:
self.status_var.set("")
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
return
playable = self.engine.get_playable_cards(0)
if playable:
self.status_var.set(t("zr_status_your_turn_play", len(playable)))
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
else:
self.status_var.set(t("zr_status_your_turn_pass"))
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
pass_btn = ImageButton(
self.bottom_bar,
t("zr_btn_pass"),
btn_fire,
btn_fire,
self._on_human_pass,
sound_mgr=self.ctx.sounds,
width=184,
height=30,
style="fire",
hover_text=lambda: t("zr_tip_pass"),
)
self._set_bottom_buttons([pass_btn], overflow_buttons=[self._menu_btn])
def _process_turn(self):
if not self._canvas_alive():
return
if self.engine.is_finished:
self._finalize_round()
return
self._sync_turn_controls()
if self.engine.turn_seat != 0:
self._turn_job = self.ctx.root.after(
ZR_BOT_TURN_DELAY_MS, self._execute_bot_turn
)
def _on_canvas_click(self, event):
if (
self._fx_overlay is not None
or self._result_dialog is not None
or self.engine.is_finished
or self.engine.turn_seat != 0
):
return
for card, x1, y1, x2, y2 in reversed(self._hand_hit_rects):
if x1 <= event.x <= x2 and y1 <= event.y <= y2:
if self.engine.play_card(0, card):
self.ctx.sounds.play("click")
self._render_table()
self._process_turn()
return
def _on_human_pass(self):
if self.engine.pass_turn(0):
self.ctx.sounds.play("stand")
self._render_table()
self._process_turn()
def _execute_bot_turn(self):
self._turn_job = None
if not self._canvas_alive() or self.engine.is_finished:
return
seat_id = self.engine.turn_seat
if seat_id == 0:
return
bot = self.engine.seats[seat_id]
chosen = ZehnerRausBotAI.choose_card(self.engine, bot)
if chosen is not None and self.engine.play_card(seat_id, chosen):
self.ctx.sounds.play("click")
bot.status_text = t(
"zr_act_played", t(f"bav_suit_{chosen.suit}"), chosen.rank
)
else:
self.engine.pass_turn(seat_id)
bot.status_text = t("zr_act_passed")
self._render_table()
self._process_turn()
def _finalize_round(self):
self._set_bottom_buttons([])
self.status_var.set("")
winner_id = self.engine.winner_seat
human_won = winner_id == 0
duration = max(1.0, time.time() - self.round_start_time)
prog_before = self.ctx.refresh_game_progress()
opp_levels = [s.ai_level for s in self.engine.seats[1:]]
xp_gained = Progression.calculate_match_xp(
player_level=prog_before["level"],
opponent_levels=opp_levels,
outcome_type="WIN" if human_won else "LOSE",
variant_mult=self.cfg["xp_mult"],
)
old_lvl, new_lvl = self.ctx.record_result(
self.variant_key,
won=human_won,
duration_sec=duration,
points_gained=xp_gained,
)
self.topbar.update_level_xp_text()
self.ctx.sounds.play("win" if human_won else "lose")
payload = {
"player_won": human_won,
"winner_name": self.engine.seats[winner_id].name if winner_id is not None else "",
"xp_gained": xp_gained,
"leveled_to": new_lvl if new_lvl > old_lvl else None,
"seats_summary": [
{
"name": s.name,
"is_winner": s.seat_id == winner_id,
"cards": [c.image_filename for c in s.hand],
}
for s in self.engine.seats
],
}
self._last_popup_payload = payload
self._open_result_popup(self._localize_popup(payload), play_fx=True)
@staticmethod
def _localize_popup(payload: dict) -> dict:
p_won = payload["player_won"]
headline = (
t("zr_popup_you_won")
if p_won
else t("zr_popup_bot_won", payload["winner_name"])
)
lvl_to = payload["leveled_to"]
lvl_str = (
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
if lvl_to is not None
else None
)
return {
"headline": headline,
"player_won": p_won,
"xp_gained": payload["xp_gained"],
"new_level_title": lvl_str,
"seats_summary": payload["seats_summary"],
}
def _show_result_dialog_now(self, popup_data: dict):
if not self._canvas_alive():
return
self._result_dialog = ZehnerRausResultDialog(
parent=self.arena_canvas,
assets=self.ctx.assets,
sounds=self.ctx.sounds,
result_data=popup_data,
on_next_round=self._start_new_round,
on_back_to_menu=lambda: self._cleanup_and_go(self.on_back_to_menu),
)
def _open_result_popup(self, popup_data: dict, play_fx: bool = True):
self._play_outcome_fx_then(
popup_data.get("player_won"),
play_fx,
lambda: self._show_result_dialog_now(popup_data),
)

View File

@ -2,60 +2,104 @@
# games/solitaire/base/card_animator.py # games/solitaire/base/card_animator.py
from __future__ import annotations from __future__ import annotations
import random
import time import time
import tkinter as tk import tkinter as tk
from typing import Callable from typing import Callable, Iterable
from PIL import Image, ImageTk
class CardFlightAnimator: class CardFlightAnimator:
""" """
Schneller, nicht-blockierender Canvas-Animator für gleitende Kartenbewegungen. Zentraler, nicht-blockierender Canvas-Animator für alle Solitaire-Tische:
Nutzt Canvas-Tag-Verschiebung (canvas.move) ohne teures Neu-Rendern des Hintergrunds. 1. Gleitende Kartenflüge zwischen Stapeln (start / flush)
2. Rotierend nach unten aus dem Fenster fallende Karten (spawn_falling_cards)
3. Kurzes horizontales Fehler-Wackeln bei ungültigen Kombis (start_shake)
""" """
FRAME_MS = 14 # ~70 FPS Zielrate auf Tkinter FRAME_MS = 14
FALL_STEP_MS = 16
SHAKE_OFFSETS_PX: tuple[int, ...] = (-7, 7, -5, 5, -3, 3, 0)
SHAKE_STEP_MS = 26
def __init__(self, root: tk.Misc, canvas: tk.Canvas): def __init__(self, root: tk.Misc, canvas: tk.Canvas):
self.root = root self.root = root
self.canvas = canvas self.canvas = canvas
# 1. Lineare Kartenflüge
self._job: str | None = None self._job: str | None = None
self._flights: list[dict] = [] self._flights: list[dict] = []
self._on_done: Callable[[], None] | None = None self._on_done: Callable[[], None] | None = None
self._start_ts: float = 0.0 self._start_ts: float = 0.0
self._duration_sec: float = 0.12 self._duration_sec: float = 0.12
# 2. Rotierend herausfallende Karten
self._fall_job: str | None = None
self._falling_cards: list[dict] = []
self._fall_photo_refs: list[ImageTk.PhotoImage] = []
# 3. Horizontales Fehler-Wackeln
self._shake_job: str | None = None
self._shake_refs: set[tuple] = set()
self._shake_dx: int = 0
@property @property
def is_active(self) -> bool: def is_active(self) -> bool:
return self._job is not None return self._job is not None
@property
def has_shake(self) -> bool:
return bool(self._shake_refs)
def _canvas_alive(self) -> bool:
try:
return bool(self.canvas.winfo_exists())
except Exception:
return False
def cancel(self): def cancel(self):
"""Bricht laufende Timer sofort ab (z. B. beim Schließen des Fensters).""" """Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab."""
if self._job is not None: if self._job is not None:
try: try:
self.root.after_cancel(self._job) self.root.after_cancel(self._job)
except Exception: except Exception:
pass pass
self._job = None self._job = None
try: if self._canvas_alive_safe():
if self.canvas.winfo_exists(): self.canvas.delete("anim_flight")
self.canvas.delete("anim_flight")
except Exception:
pass
self._flights.clear() self._flights.clear()
self._on_done = None self._on_done = None
self.cancel_falling()
self.cancel_shake()
def _canvas_alive_safe(self) -> bool:
try:
return bool(self.canvas.winfo_exists())
except Exception:
return False
def flush(self): def flush(self):
""" """Beendet eine laufende Flug-Animation sofort sauber im Zielzustand."""
Beendet eine laufende Animation sofort sauber im Zielzustand,
damit schnelle Klickfolgen des Spielers niemals ausgebremst werden.
"""
if not self.is_active: if not self.is_active:
return return
cb = self._on_done cb = self._on_done
self.cancel() if self._job is not None:
try:
self.root.after_cancel(self._job)
except Exception:
pass
self._job = None
if self._canvas_alive_safe():
self.canvas.delete("anim_flight")
self._flights.clear()
self._on_done = None
if callable(cb): if callable(cb):
cb() cb()
# ------------------------------------------------------------------
# 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste)
# ------------------------------------------------------------------
def start( def start(
self, self,
flights: list[dict], flights: list[dict],
@ -63,29 +107,12 @@ class CardFlightAnimator:
duration_ms: int = 115, duration_ms: int = 115,
on_done: Callable[[], None] | None = None, on_done: Callable[[], None] | None = None,
): ):
"""
flights: Liste aus Dicts:
{
"card": SolitaireCard,
"start": (x0, y0),
"end": (x1, y1),
"highlight": Optional[str],
}
"""
self.flush() self.flush()
if not flights: if not flights or not self._canvas_alive():
if callable(on_done): if callable(on_done):
on_done() on_done()
return return
try:
if not self.canvas.winfo_exists():
if callable(on_done):
on_done()
return
except Exception:
return
active_flights: list[dict] = [] active_flights: list[dict] = []
max_dist = 0.0 max_dist = 0.0
for idx, item in enumerate(flights): for idx, item in enumerate(flights):
@ -112,15 +139,15 @@ class CardFlightAnimator:
"cur_y": float(sy), "cur_y": float(sy),
}) })
# Bei minimaler Distanz (< 4 px) direkt fertigstellen
if max_dist < 4.0: if max_dist < 4.0:
self.canvas.delete("anim_flight") self.canvas.delete("anim_flight")
if callable(on_done): if callable(on_done):
on_done() on_done()
return return
# Kurze Wege noch knackiger, weite Wege über den ganzen Tisch minimal länger scaled_ms = max(
scaled_ms = max(65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45)))) 65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45)))
)
self._flights = active_flights self._flights = active_flights
self._on_done = on_done self._on_done = on_done
self._duration_sec = scaled_ms / 1000.0 self._duration_sec = scaled_ms / 1000.0
@ -129,19 +156,13 @@ class CardFlightAnimator:
def _step(self): def _step(self):
self._job = None self._job = None
try: if not self._canvas_alive():
if not self.canvas.winfo_exists():
self._flights.clear()
self._on_done = None
return
except Exception:
self._flights.clear() self._flights.clear()
self._on_done = None self._on_done = None
return return
elapsed = time.perf_counter() - self._start_ts elapsed = time.perf_counter() - self._start_ts
t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec))) t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec)))
# Cubic Ease-Out: spritziger Start, weiches Einrasten am Zielstapel
ease = 1.0 - ((1.0 - t_raw) ** 3) ease = 1.0 - ((1.0 - t_raw) ** 3)
for fl in self._flights: for fl in self._flights:
@ -169,4 +190,163 @@ class CardFlightAnimator:
try: try:
self._job = self.root.after(self.FRAME_MS, self._step) self._job = self.root.after(self.FRAME_MS, self._step)
except Exception: except Exception:
self._job = None self._job = None
# ------------------------------------------------------------------
# 2. Drehendes Herausfallen abgeräumter Karten (Pyramid / Effects)
# ------------------------------------------------------------------
def cancel_falling(self):
if self._fall_job is not None:
try:
self.root.after_cancel(self._fall_job)
except Exception:
pass
self._fall_job = None
self._falling_cards.clear()
self._fall_photo_refs.clear()
if self._canvas_alive():
self.canvas.delete("falling_fx")
@staticmethod
def _load_scaled_card_pil(assets, card, card_size: tuple[int, int]) -> Image.Image | None:
card_path = assets.res.get_card_path(card.filename)
raw_pil = None
if hasattr(assets, "_get_raw_card_pil"):
raw_pil = assets._get_raw_card_pil(card_path)
elif card_path.is_file():
try:
with Image.open(card_path) as im:
raw_pil = im.convert("RGBA")
except Exception:
raw_pil = None
if raw_pil is None:
return None
return raw_pil.convert("RGBA").resize(card_size, Image.Resampling.BILINEAR)
def spawn_falling_cards(
self,
assets,
card_size: tuple[int, int],
items: list[tuple[object, tuple[int, int]]],
):
"""Lässt abgeräumte Karten leicht hochhüpfen und sich drehend nach unten herausfallen."""
if not self._canvas_alive() or not items:
return
cw, ch = card_size
n = len(items)
for idx, (card, (sx, sy)) in enumerate(items):
base_pil = self._load_scaled_card_pil(assets, card, card_size)
if base_pil is None:
continue
dir_sign = (-1 if idx == 0 else 1) if n >= 2 else random.choice((-1, 1))
self._falling_cards.append({
"pil": base_pil,
"cx": float(sx + cw // 2),
"cy": float(sy + ch // 2),
"vx": dir_sign * random.uniform(1.8, 4.2),
"vy": random.uniform(-6.4, -3.8),
"angle": 0.0,
"ang_vel": dir_sign * random.uniform(7.5, 13.5),
})
if self._falling_cards and self._fall_job is None:
self._step_falling()
def redraw_falling_layer(self):
if not self._falling_cards or not self._canvas_alive():
return
self.canvas.delete("falling_fx")
self._fall_photo_refs.clear()
for p in self._falling_cards:
rot_pil = p["pil"].rotate(
p["angle"], resample=Image.Resampling.BILINEAR, expand=True
)
tk_ph = ImageTk.PhotoImage(rot_pil)
self._fall_photo_refs.append(tk_ph)
self.canvas.create_image(
int(round(p["cx"])),
int(round(p["cy"])),
image=tk_ph,
anchor="center",
tags=("falling_fx",),
)
if self.canvas.find_withtag("modal_dim_veil"):
self.canvas.tag_lower("falling_fx", "modal_dim_veil")
def _step_falling(self):
self._fall_job = None
if not self._canvas_alive():
self._falling_cards.clear()
self._fall_photo_refs.clear()
return
limit_y = max(600, self.canvas.winfo_height()) + 240
survivors: list[dict] = []
for p in self._falling_cards:
p["cx"] += p["vx"]
p["cy"] += p["vy"]
p["vy"] += 1.20
p["angle"] = (p["angle"] + p["ang_vel"]) % 360.0
if p["cy"] < limit_y:
survivors.append(p)
self._falling_cards = survivors
if not self._falling_cards:
self._fall_photo_refs.clear()
self.canvas.delete("falling_fx")
return
self.redraw_falling_layer()
try:
self._fall_job = self.root.after(self.FALL_STEP_MS, self._step_falling)
except Exception:
self._fall_job = None
# ------------------------------------------------------------------
# 3. Horizontales Fehler-Wackeln (Pyramid & TriPeaks)
# ------------------------------------------------------------------
def cancel_shake(self, on_clear: Callable[[], None] | None = None):
was_shaking = bool(self._shake_refs) or (self._shake_job is not None)
if self._shake_job is not None:
try:
self.root.after_cancel(self._shake_job)
except Exception:
pass
self._shake_job = None
self._shake_refs.clear()
self._shake_dx = 0
if was_shaking and callable(on_clear) and self._canvas_alive():
on_clear()
def shake_state_for(self, ref: tuple) -> tuple[bool, int]:
if ref in self._shake_refs:
return True, self._shake_dx
return False, 0
def start_shake(self, refs: Iterable[tuple], redraw_cb: Callable[[], None]):
self.cancel_shake()
self._shake_refs = {r for r in refs if r is not None}
if not self._shake_refs or not self._canvas_alive():
return
def _step_shake(idx: int):
self._shake_job = None
if not self._canvas_alive():
self._shake_refs.clear()
self._shake_dx = 0
return
if idx >= len(self.SHAKE_OFFSETS_PX):
self._shake_refs.clear()
self._shake_dx = 0
redraw_cb()
return
self._shake_dx = self.SHAKE_OFFSETS_PX[idx]
redraw_cb()
try:
self._shake_job = self.root.after(
self.SHAKE_STEP_MS, lambda: _step_shake(idx + 1)
)
except Exception:
self._shake_job = None
_step_shake(0)

View File

View File

@ -0,0 +1,312 @@
# -*- coding: utf-8 -*-
# games/solitaire/pyramid/models/pyramid_engine.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireBaseEngine, SolitaireCard
from games.solitaire.pyramid.models.pyramid_solver import generate_solvable_pyramid_deal
from resources.code_res.game_constants import PYRAMID_REDEALS_BY_DIFF
class PyramidEngine(SolitaireBaseEngine):
"""
Spiellogik für Pyramid Solitaire:
- 7-reihige Pyramide (28 offene Karten; frei, sobald beide Kinder darunter entfernt wurden)
- Rechts zwei offene Stapel: Linker Stapel (stock, aufgedeckt) & rechte Ablage (waste, aufgedeckt)
- Sowohl Pyramide+Stapel als auch Linker Stapel + Rechte Ablage können auf 13 gepaart werden!
- Weiterblättern erfolgt explizit über den Button "Nächste Karte".
"""
NUM_ROWS = 7
SCORE_PYRAMID_CARD = 15
SCORE_PILE_CARD = 5
SCORE_ROW_CLEAR_BONUS = 25
def __init__(self, difficulty: int = 1, seed: int | None = None):
super().__init__()
self.difficulty: int = max(0, min(3, int(difficulty)))
self.seed: int | None = seed
self.max_redeals: int = PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2)
self.redeals_used: int = 0
self.stagnant_cycles: int = 0
self._progress_in_cycle: bool = False
self.pyramid: list[list[SolitaireCard | None]] = []
self.stock: list[SolitaireCard] = []
self.waste: list[SolitaireCard] = []
self.removed: list[SolitaireCard] = []
self.new_game(difficulty=self.difficulty, seed=seed)
def new_game(self, difficulty: int | None = None, seed: int | None = None):
if difficulty is not None:
self.difficulty = max(0, min(3, int(difficulty)))
self.seed = seed
self.max_redeals = PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2)
self.redeals_used = 0
self.stagnant_cycles = 0
self._progress_in_cycle = False
self.reset_tracking()
self.pyramid, self.stock = generate_solvable_pyramid_deal(
difficulty=self.difficulty, seed=seed
)
self.waste = []
self.removed = []
self.capture_initial_state()
@property
def redeals_remaining(self) -> int:
return max(0, self.max_redeals - self.redeals_used)
@property
def pyramid_remaining_count(self) -> int:
return sum(1 for row in self.pyramid for c in row if c is not None)
@property
def pyramid_cleared_count(self) -> int:
return 28 - self.pyramid_remaining_count
@property
def can_advance_stock(self) -> bool:
if self.won:
return False
if self.stock:
return True
return bool(
self.waste
and self.redeals_used < self.max_redeals
and self.stagnant_cycles < 3
)
@property
def is_stock_locked(self) -> bool:
if self.stock:
return False
if not self.waste:
return True
return self.redeals_used >= self.max_redeals or self.stagnant_cycles >= 3
def is_pyramid_exposed(self, row: int, col: int) -> bool:
if not (0 <= row < self.NUM_ROWS and 0 <= col <= row):
return False
if self.pyramid[row][col] is None:
return False
if row == self.NUM_ROWS - 1:
return True
return (
self.pyramid[row + 1][col] is None
and self.pyramid[row + 1][col + 1] is None
)
def get_card_at_ref(self, ref: tuple) -> SolitaireCard | None:
zone = ref[0]
if zone == "pyramid":
_, r, c = ref
if self.is_pyramid_exposed(r, c):
return self.pyramid[r][c]
return None
if zone == "stock":
return self.stock[-1] if self.stock else None
if zone == "waste":
return self.waste[-1] if self.waste else None
return None
def _pop_ref(self, ref: tuple) -> SolitaireCard:
zone = ref[0]
if zone == "pyramid":
_, r, c = ref
card = self.pyramid[r][c]
assert card is not None
self.pyramid[r][c] = None
row_cleared = all(x is None for x in self.pyramid[r])
self._score_add(
self.SCORE_PYRAMID_CARD + (self.SCORE_ROW_CLEAR_BONUS if row_cleared else 0)
)
return card
if zone == "stock":
card = self.stock.pop()
self._score_add(self.SCORE_PILE_CARD)
return card
card = self.waste.pop()
self._score_add(self.SCORE_PILE_CARD)
return card
def _score_add(self, pts: int):
self.score = max(0, self.score + pts)
def _check_victory(self) -> bool:
if self.pyramid_remaining_count == 0:
self.mark_won()
return True
return False
def can_remove_single(self, ref: tuple) -> bool:
if self.won:
return False
c = self.get_card_at_ref(ref)
return c is not None and c.value == 13
def can_pair_refs(self, ref_a: tuple, ref_b: tuple) -> tuple[bool, int]:
if self.won or ref_a == ref_b:
return False, 0
ca = self.get_card_at_ref(ref_a)
cb = self.get_card_at_ref(ref_b)
if ca is None or cb is None:
return False, 0
total = ca.value + cb.value
return (total == 13), total
def remove_king(self, ref: tuple, record_undo: bool = True) -> bool:
if not self.can_remove_single(ref):
return False
if record_undo:
self.push_undo()
card = self._pop_ref(ref)
self.removed.append(card)
self.moves += 1
self._progress_in_cycle = True
self.stagnant_cycles = 0
self._check_victory()
return True
def remove_pair(self, ref_a: tuple, ref_b: tuple, record_undo: bool = True) -> bool:
ok, _s = self.can_pair_refs(ref_a, ref_b)
if not ok:
return False
if record_undo:
self.push_undo()
c1 = self._pop_ref(ref_a)
c2 = self._pop_ref(ref_b)
self.removed.extend([c1, c2])
self.moves += 1
self._progress_in_cycle = True
self.stagnant_cycles = 0
self._check_victory()
return True
def draw_or_recycle_stock(self) -> tuple[bool, str]:
"""Button 'Nächste Karte': Schiebt die linke offene Karte auf die rechte Ablage (oder Redeal)."""
if self.won:
return False, ""
if self.stock:
self.push_undo()
card = self.stock.pop()
card.face_up = True
self.waste.append(card)
self.moves += 1
return True, "draw"
if not self.waste:
return False, "empty"
if self.redeals_used >= self.max_redeals:
return False, "redeal_limit"
if self.stagnant_cycles >= 3:
return False, "stagnant"
self.push_undo()
if not self._progress_in_cycle:
self.stagnant_cycles += 1
if self.stagnant_cycles >= 3:
self._undo_stack.pop()
return False, "stagnant"
self._progress_in_cycle = False
self.redeals_used += 1
recycled = list(reversed(self.waste))
for c in recycled:
c.face_up = True
self.stock = recycled
self.waste = []
self.moves += 1
return True, "recycle"
def get_all_exposed_refs(self) -> list[tuple]:
refs: list[tuple] = [
("pyramid", r, c)
for r in range(self.NUM_ROWS)
for c in range(r + 1)
if self.is_pyramid_exposed(r, c)
]
if self.stock:
refs.append(("stock",))
if self.waste:
refs.append(("waste",))
return refs
def can_auto_complete(self) -> bool:
return False
def auto_complete_step(self, record_undo: bool = False) -> bool:
_ = record_undo
return False
def has_any_meaningful_move(self) -> bool:
if self.won:
return True
refs = self.get_all_exposed_refs()
for i, ra in enumerate(refs):
ca = self.get_card_at_ref(ra)
if ca is None:
continue
if ca.value == 13:
return True
for rb in refs[i + 1 :]:
cb = self.get_card_at_ref(rb)
if cb is not None and ca.value + cb.value == 13:
return True
return self.can_advance_stock
def get_hint(self) -> dict | None:
refs = self.get_all_exposed_refs()
for ref in refs:
c = self.get_card_at_ref(ref)
if c is not None and c.value == 13:
return {"type": "single", "refs": [ref]}
for i, ra in enumerate(refs):
ca = self.get_card_at_ref(ra)
if ca is None:
continue
for rb in refs[i + 1 :]:
cb = self.get_card_at_ref(rb)
if cb is not None and ca.value + cb.value == 13:
return {"type": "pair", "refs": [ra, rb]}
if self.can_advance_stock:
return {"type": "draw", "refs": [("next_btn",)]}
return None
def serialize_board(self) -> dict:
return {
"difficulty": self.difficulty,
"max_redeals": self.max_redeals,
"redeals_used": self.redeals_used,
"stagnant_cycles": self.stagnant_cycles,
"progress_in_cycle": self._progress_in_cycle,
"pyramid": [
[c.to_dict() if c is not None else None for c in row]
for row in self.pyramid
],
"stock": [c.to_dict() for c in self.stock],
"waste": [c.to_dict() for c in self.waste],
"removed": [c.to_dict() for c in self.removed],
}
def restore_board(self, board: dict):
self.difficulty = max(0, min(3, int(board.get("difficulty", 1))))
self.max_redeals = int(
board.get("max_redeals", PYRAMID_REDEALS_BY_DIFF.get(self.difficulty, 2))
)
self.redeals_used = int(board.get("redeals_used", 0))
self.stagnant_cycles = int(board.get("stagnant_cycles", 0))
self._progress_in_cycle = bool(board.get("progress_in_cycle", False))
self.pyramid = [
[SolitaireCard.from_dict(d) if d is not None else None for d in row]
for row in board["pyramid"]
]
self.stock = [SolitaireCard.from_dict(d) for d in board.get("stock", [])]
for c in self.stock:
c.face_up = True
self.waste = [SolitaireCard.from_dict(d) for d in board.get("waste", [])]
for c in self.waste:
c.face_up = True
self.removed = [SolitaireCard.from_dict(d) for d in board.get("removed", [])]

View File

@ -0,0 +1,238 @@
# -*- coding: utf-8 -*-
# games/solitaire/pyramid/models/pyramid_solver.py
from __future__ import annotations
import heapq
import random
from dataclasses import dataclass
from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
from resources.code_res.game_constants import PYRAMID_REDEALS_BY_DIFF, SUITS
_SUIT = tuple(c // 13 for c in range(52))
_VAL = tuple((c % 13) + 1 for c in range(52))
_CHILD_MASKS: tuple[int, ...] = tuple(
0
if r == 6
else (
(1 << (((r + 1) * (r + 2)) // 2 + c))
| (1 << (((r + 1) * (r + 2)) // 2 + c + 1))
)
for r in range(7)
for c in range(r + 1)
)
@dataclass
class PyramidSolveReport:
solvable: bool
nodes_expanded: int
layout_hardness: float
def _decode_card(cid: int) -> SolitaireCard:
return SolitaireCard(
suit=SUITS[_SUIT[cid]],
rank=SOLITAIRE_RANKS[cid % 13],
face_up=True,
deck_id=0,
)
def _exposed_pyramid_indices(pyr_mask: int) -> list[int]:
out: list[int] = []
m = pyr_mask
while m:
lsb = m & -m
idx = lsb.bit_length() - 1
if (pyr_mask & _CHILD_MASKS[idx]) == 0:
out.append(idx)
m ^= lsb
return out
def evaluate_pyramid_hardness(pyr_ids: list[int], stock_ids: list[int]) -> float:
score = 0.0
for r in range(7):
row_base = (r * (r + 1)) // 2
depth_weight = (6 - r) * 1.6
for c in range(r + 1):
idx = row_base + c
v = _VAL[pyr_ids[idx]]
if v == 13:
score -= 2.8 if r == 6 else 1.2
if r < 6:
left_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c]]
right_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c + 1]]
if v + left_v == 13:
score += 6.5 + depth_weight
if v + right_v == 13:
score += 6.5 + depth_weight
bottom_vals = [_VAL[pyr_ids[21 + c]] for c in range(7)]
if stock_ids:
bottom_vals.append(_VAL[stock_ids[-1]])
immediate_pairs = sum(1 for v in bottom_vals if v == 13)
for i in range(len(bottom_vals)):
for j in range(i + 1, len(bottom_vals)):
if bottom_vals[i] + bottom_vals[j] == 13:
immediate_pairs += 1
score -= immediate_pairs * 4.0
return score
def solve_pyramid_deal(
deck_ids: list[int], max_redeals: int, max_nodes: int = 3800
) -> PyramidSolveReport:
"""
Prüft Lösbarkeit mit offenem Talon (stock_t[-1]) + offener Ablage (waste_t[-1]):
Beide Oberkarten sind mit freien Pyramidenkarten UND direkt miteinander kombinierbar.
"""
pyr_ids = deck_ids[:28]
stock_ids = deck_ids[28:]
hardness = evaluate_pyramid_hardness(pyr_ids, stock_ids)
init_mask = (1 << 28) - 1
start_state = (init_mask, tuple(stock_ids), (), max_redeals)
visited: set[tuple] = {start_state}
pq: list[tuple[int, int, int, tuple]] = []
counter = 0
def heuristic(pyr_m: int, redeals_rem: int) -> int:
return pyr_m.bit_count() * 4 - redeals_rem * 2
heapq.heappush(pq, (heuristic(init_mask, max_redeals), 0, counter, start_state))
nodes = 0
while pq and nodes < max_nodes:
_prio, depth, _tie, state = heapq.heappop(pq)
pyr_m, stock_t, waste_t, redeals_rem = state
nodes += 1
if pyr_m == 0:
return PyramidSolveReport(True, nodes, hardness)
exposed = _exposed_pyramid_indices(pyr_m)
next_states: list[tuple] = []
# 1. Freie Könige (13) direkt abräumen (Pyramide, linker Stapel oder rechte Ablage)
king_cleared = False
for idx in exposed:
if _VAL[pyr_ids[idx]] == 13:
next_states.append((pyr_m & ~(1 << idx), stock_t, waste_t, redeals_rem))
king_cleared = True
break
if not king_cleared and stock_t and _VAL[stock_t[-1]] == 13:
next_states.append((pyr_m, stock_t[:-1], waste_t, redeals_rem))
king_cleared = True
if not king_cleared and waste_t and _VAL[waste_t[-1]] == 13:
next_states.append((pyr_m, stock_t, waste_t[:-1], redeals_rem))
king_cleared = True
if not king_cleared:
# 2. Zwei freie Pyramidenkarten paaren
for i_pos in range(len(exposed)):
idx_a = exposed[i_pos]
va = _VAL[pyr_ids[idx_a]]
for j_pos in range(i_pos + 1, len(exposed)):
idx_b = exposed[j_pos]
if va + _VAL[pyr_ids[idx_b]] == 13:
nm = pyr_m & ~((1 << idx_a) | (1 << idx_b))
next_states.append((nm, stock_t, waste_t, redeals_rem))
# 3. Pyramidenkarte + linker Stapel / rechte Ablage
if stock_t:
vs = _VAL[stock_t[-1]]
for idx_a in exposed:
if _VAL[pyr_ids[idx_a]] + vs == 13:
next_states.append((pyr_m & ~(1 << idx_a), stock_t[:-1], waste_t, redeals_rem))
if waste_t:
vw = _VAL[waste_t[-1]]
for idx_a in exposed:
if _VAL[pyr_ids[idx_a]] + vw == 13:
next_states.append((pyr_m & ~(1 << idx_a), stock_t, waste_t[:-1], redeals_rem))
# 4. Linker Stapel + rechte Ablage direkt miteinander paaren
if stock_t and waste_t and (_VAL[stock_t[-1]] + _VAL[waste_t[-1]] == 13):
next_states.append((pyr_m, stock_t[:-1], waste_t[:-1], redeals_rem))
# 5. Button "Nächste Karte": Linke Karte nach rechts legen oder Redeal
if stock_t:
next_states.append((pyr_m, stock_t[:-1], waste_t + (stock_t[-1],), redeals_rem))
elif waste_t and redeals_rem > 0:
recycled_stock = tuple(reversed(waste_t))
next_states.append((pyr_m, recycled_stock, (), redeals_rem - 1))
for ns in next_states:
if ns[0] == 0:
return PyramidSolveReport(True, nodes, hardness)
if ns not in visited:
visited.add(ns)
counter += 1
heapq.heappush(
pq, (heuristic(ns[0], ns[3]) + depth // 3, depth + 1, counter, ns)
)
return PyramidSolveReport(False, nodes, hardness)
def generate_solvable_pyramid_deal(
difficulty: int = 1,
seed: int | None = None,
) -> tuple[list[list[SolitaireCard | None]], list[SolitaireCard]]:
rng = random.Random(seed) if seed is not None else random.Random()
diff = max(0, min(3, int(difficulty)))
max_redeals = PYRAMID_REDEALS_BY_DIFF.get(diff, 2)
hardness_targets = {0: -6.0, 1: 8.0, 2: 18.0, 3: 28.0}
target = hardness_targets[diff]
node_budget = 2800 if diff <= 1 else 4400
base_deck = list(range(52))
candidates: list[tuple[float, list[int]]] = []
for _attempt in range(280):
trial = list(base_deck)
rng.shuffle(trial)
report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=node_budget)
if not report.solvable:
continue
composite = report.layout_hardness + (report.nodes_expanded / 45.0)
candidates.append((composite, trial))
if diff == 0 and composite <= 2.0:
break
if diff == 1 and 2.0 <= composite <= 22.0:
break
if diff == 2 and composite >= 14.0 and len(candidates) >= 2:
break
if diff == 3 and len(candidates) >= 2:
break
if len(candidates) >= 3:
break
while not candidates:
trial = list(base_deck)
rng.shuffle(trial)
report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=5200)
if report.solvable:
candidates.append((report.layout_hardness + report.nodes_expanded / 45.0, trial))
if diff == 3:
best_ids = max(candidates, key=lambda x: x[0])[1]
elif diff == 0:
best_ids = min(candidates, key=lambda x: x[0])[1]
else:
best_ids = min(candidates, key=lambda x: abs(x[0] - target))[1]
pyramid: list[list[SolitaireCard | None]] = []
cursor = 0
for r in range(7):
row = [_decode_card(best_ids[cursor + c]) for c in range(r + 1)]
pyramid.append(row)
cursor += r + 1
stock = [_decode_card(cid) for cid in best_ids[28:]]
return pyramid, stock

View File

@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
# games/solitaire/pyramid/start.py
from games.solitaire.pyramid.views.pyramid_menu_view import PyramidMenuView
from resources.code_res.game_constants import CAT_SOLO
GAME_TITLE_KEY = "game_title_pyramid"
GAME_FOLDER_ID = "solitaire/pyramid"
GAME_CATEGORY = CAT_SOLO
def start_game(context):
PyramidMenuView(context).show(ask_resume_popup=True)

View File

@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# games/solitaire/pyramid/views/pyramid_menu_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.pyramid.views.pyramid_table_view import PyramidTableView
from resources.code_res.game_constants import PYRAMID_VARIANTS
GAME_FOLDER_ID = "solitaire/pyramid"
GAME_TITLE_KEY = "game_title_pyramid"
class PyramidMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "py_menu_topbar"
SUBTITLE_KEY = "py_menu_subtitle"
CONTROLS_HINT_KEY = "py_controls_hint"
DIFF_SETTING_PREFIX = "pyramid_diff"
DEFAULT_VARIANT_KEY = "pyramid_std"
REQUIRED_BOARD_KEYS = ("pyramid", "stock")
MODE_LABEL_KEY = "py_variant_info_lbl"
DESC_KEY_PREFIX = "py_desc_"
def _variants_dict(self) -> dict[str, dict]:
return PYRAMID_VARIANTS
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
PyramidTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

View File

@ -0,0 +1,652 @@
# -*- coding: utf-8 -*-
# games/solitaire/pyramid/views/pyramid_table_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_table_controller import SolitaireTableController
from games.solitaire.pyramid.models.pyramid_engine import PyramidEngine
from resources.code_res.game_constants import (
ACCENT_GOLD,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FONT_COLOR_BODY_MUTED,
FONT_SIZE_SMALL_MIN,
PYRAMID_VARIANTS,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "solitaire/pyramid"
GAME_TITLE_KEY = "game_title_pyramid"
class PyramidTableView(SolitaireTableController):
GAME_FOLDER_ID = GAME_FOLDER_ID
HAS_AUTOCOMPLETE_BTN = False
SPEED_THRESHOLDS_SEC = (120, 220)
SOCKET_PAD_PX = 6
def __init__(
self,
context,
variant_key: str = "pyramid_std",
difficulty: int = 1,
on_back_to_menu=None,
resume_state_json: str | None = None,
):
v_key = variant_key if variant_key in PYRAMID_VARIANTS else "pyramid_std"
cfg = PYRAMID_VARIANTS[v_key]
self._init_controller_state(context, v_key, cfg, difficulty, on_back_to_menu)
self._selected_ref: tuple | None = None
self.next_card_btn: ImageButton | None = None
self._pyr_coords: list[list[tuple[int, int]]] = [
[(0, 0) for _ in range(r + 1)] for r in range(7)
]
self._stock_xy: tuple[int, int] = (0, 0)
self._waste_xy: tuple[int, int] = (0, 0)
self._next_btn_center: tuple[int, int] = (0, 0)
if resume_state_json:
self.engine = PyramidEngine.__new__(PyramidEngine)
super(PyramidEngine, self.engine).__init__()
self.engine.difficulty = self.difficulty
self.engine.seed = None
self.engine.max_redeals = 2
self.engine.redeals_used = 0
self.engine.stagnant_cycles = 0
self.engine._progress_in_cycle = False
self.engine.pyramid = []
self.engine.stock = []
self.engine.waste = []
self.engine.removed = []
try:
self.engine.load_json(resume_state_json)
self.difficulty = self.engine.difficulty
except Exception:
self.engine.new_game(difficulty=self.difficulty)
else:
self.engine = PyramidEngine(difficulty=self.difficulty)
self._finish_startup(is_resumed=bool(resume_state_json))
def _build_ui(self):
super()._build_ui()
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
self.next_card_btn = ImageButton(
self.canvas,
t("py_btn_next_card", len(self.engine.stock)),
btn_norm,
btn_purp,
self._on_next_card_clicked,
sound_mgr=self.ctx.sounds,
width=196,
height=36,
style="amethyst",
)
self._bind_root("<space>", lambda _e: self._on_next_card_shortcut())
def _on_next_card_shortcut(self) -> str:
if not self._is_ui_locked():
self.ctx.sounds.play("click")
self._on_next_card_clicked()
return "break"
def _sync_buttons(self):
super()._sync_buttons()
if self.next_card_btn is not None and self.next_card_btn.winfo_exists():
locked = self._is_ui_locked()
lbl = (
t("py_btn_next_card", len(self.engine.stock))
if self.engine.stock
else t("py_btn_redeal", self.engine.redeals_remaining)
)
self.next_card_btn.set_text(lbl)
self.next_card_btn.set_enabled((not locked) and self.engine.can_advance_stock)
def _extra_hud_suffix(self) -> str:
return t(
"py_hud_extra",
self.engine.pyramid_cleared_count,
self.engine.redeals_remaining,
self.engine.max_redeals,
)
def _reset_engine_for_new_deal(self):
if self.animator:
self.animator.cancel_shake()
self.animator.cancel_falling()
self._selected_ref = None
self.engine.new_game(difficulty=self.difficulty)
def _on_undo(self):
if self.animator:
self.animator.cancel_shake()
self.animator.cancel_falling()
self._selected_ref = None
super()._on_undo()
def _on_undo_all(self):
if self.animator:
self.animator.cancel_shake()
self.animator.cancel_falling()
self._selected_ref = None
super()._on_undo_all()
def _ref_screen_xy(self, ref: tuple) -> tuple[int, int]:
if ref[0] == "pyramid":
return self._pyr_coords[ref[1]][ref[2]]
if ref[0] == "waste":
return self._waste_xy
return self._stock_xy
def _trigger_mismatch_shake(self, refs: list[tuple]):
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator is not None:
self.animator.start_shake(refs, self.redraw)
def _execute_clear_with_fall(
self, refs: list[tuple], engine_action_fn, override_first_xy: tuple[int, int] | None = None
) -> bool:
spawn_items: list[tuple[SolitaireCard, tuple[int, int]]] = []
for idx, r in enumerate(refs):
c = self.engine.get_card_at_ref(r)
if c is not None:
xy = override_first_xy if (idx == 0 and override_first_xy is not None) else self._ref_screen_xy(r)
spawn_items.append((c, xy))
if not engine_action_fn():
return False
self.ctx.sounds.play("click")
self._after_player_move()
if not self.engine.won and self.animator is not None:
self.animator.spawn_falling_cards(self.ctx.assets, self.card_size, spawn_items)
return True
def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]:
pos: dict[tuple[str, str, int], tuple[int, int]] = {}
for r in range(7):
for c in range(r + 1):
card = self.engine.pyramid[r][c]
if card is not None:
pos[self._card_key(card)] = self._pyr_coords[r][c]
for card in self.engine.stock:
pos[self._card_key(card)] = self._stock_xy
for card in self.engine.waste:
pos[self._card_key(card)] = self._waste_xy
off_y = max(560, self.canvas.winfo_height()) + 30
for card in self.engine.removed:
pos[self._card_key(card)] = (self.canvas.winfo_width() // 2, off_y)
return pos
def _ordered_moved_cards(self, moved_keys: set[tuple[str, str, int]]) -> list[SolitaireCard]:
ordered: list[SolitaireCard] = []
for r in range(7):
for c in range(r + 1):
card = self.engine.pyramid[r][c]
if card is not None and self._card_key(card) in moved_keys:
ordered.append(card)
for pile in (self.engine.stock, self.engine.waste):
for card in pile:
if self._card_key(card) in moved_keys:
ordered.append(card)
return ordered
def _recompute_and_draw(self):
self._resize_job = None
if not self._canvas_alive() or self._fx_overlay is not None:
return
cw, ch = max(680, self.canvas.winfo_width()), max(420, self.canvas.winfo_height())
aspect = self._get_card_aspect()
margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch)
v_top = max(16, int(top_pad * 0.36))
v_bot = max(14, int(bot_pad * 0.34))
self._frame_bot_pad = v_bot
usable_w = max(560, cw - 2 * margin_x)
usable_h = max(260, ch - v_top - v_bot)
card_w_by_h = int(round((usable_h / (1.0 + 6 * 0.39)) / aspect))
card_w_by_w = int(usable_w / 10.35)
card_w = max(64, min(138, card_w_by_w, card_w_by_h))
card_h = int(round(card_w * aspect))
self.card_size = (card_w, card_h)
col_gap = max(8, int(card_w * 0.10))
step_x = card_w + col_gap
row_dy = max(28, min(int(card_h * 0.40), (usable_h - card_h) // 6))
pyr_total_w = 6 * step_x + card_w
pyr_total_h = 6 * row_dy + card_h
side_gap = max(34, int(card_w * 0.50))
pair_gap = max(22, int(card_w * 0.28))
side_total_w = 2 * card_w + pair_gap
full_w = pyr_total_w + side_gap + side_total_w
start_x = max(margin_x, (cw - full_w) // 2)
pyr_apex_x = start_x + (pyr_total_w - card_w) // 2
pyr_top_y = v_top + max(0, (usable_h - pyr_total_h) // 2)
for r in range(7):
row_x0 = int(round(pyr_apex_x - r * (step_x / 2.0)))
ry = pyr_top_y + r * row_dy
for c in range(r + 1):
self._pyr_coords[r][c] = (row_x0 + c * step_x, ry)
# Beide offenen Stapel + Button "Nächste Karte" sauber vertikal zentrieren
side_block_h = card_h + 62
deck_y = pyr_top_y + max(22, (pyr_total_h - side_block_h) // 2)
stock_x = start_x + pyr_total_w + side_gap
waste_x = stock_x + card_w + pair_gap
self._stock_xy = (stock_x, deck_y)
self._waste_xy = (waste_x, deck_y)
self._next_btn_center = (
stock_x + side_total_w // 2,
deck_y + card_h + self.SOCKET_PAD_PX + 28,
)
self.redraw()
def _draw_deck_socket(self, x: int, y: int, highlight_color: str | None = None):
cw, ch = self.card_size
pad = self.SOCKET_PAD_PX
outer_col = highlight_color if highlight_color else BORDER_COLOR
outer_w = 2 if highlight_color else 1
self.canvas.create_rectangle(
x - pad,
y - pad,
x + cw + pad,
y + ch + pad,
fill=CELL_BG,
outline=outer_col,
width=outer_w,
)
self.canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
fill="", outline=SUBTLE_BORDER, width=1,
)
def _draw_pile_caption(self, cx: int, y: int, txt: str, color: str = FONT_COLOR_BODY_MUTED):
ph = self.ctx.assets.get_goth_text_photo(txt, FONT_SIZE_SMALL_MIN, color)
self._canvas_ui_refs.append(ph)
self.canvas.create_image(cx, y, image=ph, anchor="center")
def redraw(
self,
exclude_source: dict | None = None,
hidden_card_keys: set[tuple[str, str, int]] | None = None,
):
if not self._canvas_alive():
return
canvas_w, canvas_h = self._prepare_canvas_frame(680, 420)
cw, _ch = self.card_size
hidden = hidden_card_keys or set()
if self._selected_ref is not None and self.engine.get_card_at_ref(self._selected_ref) is None:
self._selected_ref = None
hint_refs = set(self._active_hint.get("refs", [])) if self._active_hint else set()
# 1. 7-stufige Pyramide zeichnen
for r in range(7):
for c in range(r + 1):
px, py = self._pyr_coords[r][c]
card = self.engine.pyramid[r][c]
ref = ("pyramid", r, c)
if exclude_source and exclude_source.get("ref") == ref:
card = None
if card is None or self._card_key(card) in hidden:
if r == 0 and self.engine.pyramid[0][0] is None:
self._draw_slot(px, py, symbol="13", symbol_color=ACCENT_GOLD)
continue
exposed = self.engine.is_pyramid_exposed(r, c)
is_shaking, s_dx = (
self.animator.shake_state_for(ref) if self.animator else (False, 0)
)
hl = (
ERROR_FG
if is_shaking
else (ACCENT_GOLD if (ref == self._selected_ref or ref in hint_refs) else None)
)
self._draw_card_at(
card,
px + s_dx,
py,
tags=(f"pyr_{r}_{c}",),
highlight_color=hl,
dim_non_movable=not exposed,
)
# 2. Linker Stapel (OFFEN aufgedeckt & direkt auswählbar!)
sx, sy = self._stock_xy
stock_ref = ("stock",)
st_shaking, st_dx = (
self.animator.shake_state_for(stock_ref) if self.animator else (False, 0)
)
st_hl = (
ERROR_FG
if st_shaking
else (ACCENT_GOLD if (stock_ref == self._selected_ref or stock_ref in hint_refs) else None)
)
self._draw_deck_socket(sx, sy, highlight_color=None if st_shaking else st_hl)
s_pile = list(self.engine.stock)
if exclude_source and exclude_source.get("ref") == stock_ref and s_pile:
s_pile = s_pile[:-1]
s_pile = [c for c in s_pile if self._card_key(c) not in hidden]
if s_pile:
if st_shaking and len(s_pile) >= 2:
self._draw_card_at(s_pile[-2], sx, sy, tags=("pyr_stock_under",))
elif len(s_pile) >= 4:
self._draw_card_at(s_pile[-2], sx - 2, sy - 2)
self._draw_card_at(
s_pile[-1], sx + st_dx, sy, tags=("pyr_stock_top",), highlight_color=st_hl
)
else:
locked = self.engine.is_stock_locked
sym = "" if locked else ("↻" if self.engine.waste else "—")
self._draw_slot(
sx,
sy,
symbol=sym,
symbol_color=ACCENT_GOLD if sym == "↻" else SUBTLE_BORDER,
draw_red_cross=bool(locked and self.engine.waste),
)
self._draw_pile_caption(
sx + cw // 2, sy - self.SOCKET_PAD_PX - 14, t("py_lbl_stock", len(self.engine.stock))
)
# 3. Rechter Ablagestapel (OFFEN aufgedeckt & mit Links oder Pyramide kombinierbar!)
wx, wy = self._waste_xy
waste_ref = ("waste",)
w_shaking, w_dx = (
self.animator.shake_state_for(waste_ref) if self.animator else (False, 0)
)
w_hl = (
ERROR_FG
if w_shaking
else (ACCENT_GOLD if (waste_ref == self._selected_ref or waste_ref in hint_refs) else None)
)
self._draw_deck_socket(wx, wy, highlight_color=None if w_shaking else w_hl)
w_pile = list(self.engine.waste)
if exclude_source and exclude_source.get("ref") == waste_ref and w_pile:
w_pile = w_pile[:-1]
w_pile = [c for c in w_pile if self._card_key(c) not in hidden]
if w_pile:
if w_shaking and len(w_pile) >= 2:
self._draw_card_at(w_pile[-2], wx, wy, tags=("pyr_waste_under",))
self._draw_card_at(
w_pile[-1], wx + w_dx, wy, tags=("pyr_waste_top",), highlight_color=w_hl
)
else:
self._draw_slot(wx, wy, symbol="◇", symbol_color=SUBTLE_BORDER)
self._draw_pile_caption(
wx + cw // 2, wy - self.SOCKET_PAD_PX - 14, t("py_lbl_waste", len(self.engine.waste))
)
# 4. Button "Nächste Karte" mittig unter den beiden Stapeln platzieren
if self.next_card_btn is not None and self.next_card_btn.winfo_exists():
bx, by = self._next_btn_center
if ("next_btn",) in hint_refs:
bw, bh = self.next_card_btn.pixel_width, self.next_card_btn.pixel_height
self.canvas.create_rectangle(
bx - bw // 2 - 4,
by - bh // 2 - 4,
bx + bw // 2 + 4,
by + bh // 2 + 4,
outline=ACCENT_GOLD,
width=2,
)
self.canvas.create_window(bx, by, window=self.next_card_btn, anchor="center")
if self.animator is not None:
self.animator.redraw_falling_layer()
self._finish_canvas_frame(canvas_w, canvas_h, exclude_source, hidden)
def _find_first_overlapping_tag(self, row: int, col: int) -> str | None:
for nr in range(row + 1, 7):
for nc in range(nr + 1):
if self.engine.pyramid[nr][nc] is not None:
tag = f"pyr_{nr}_{nc}"
if self.canvas.find_withtag(tag):
return tag
return None
def _hover_card_probe(self, x: int, y: int) -> dict | None:
if self.animator and self.animator.has_shake:
return None
cw, ch = self.card_size
for r in range(6, -1, -1):
for c in range(r, -1, -1):
card = self.engine.pyramid[r][c]
if card is None:
continue
px, py = self._pyr_coords[r][c]
if px <= x <= px + cw and py <= y <= py + ch:
under_tag = (
None
if self.engine.is_pyramid_exposed(r, c)
else self._find_first_overlapping_tag(r, c)
)
return {
"card": card,
"x": px,
"y": py,
"size": self.card_size,
"under_tag": under_tag,
}
sx, sy = self._stock_xy
if self.engine.stock and sx <= x <= sx + cw and sy <= y <= sy + ch:
return {"card": self.engine.stock[-1], "x": sx, "y": sy, "size": self.card_size, "under_tag": None}
wx, wy = self._waste_xy
if self.engine.waste and wx <= x <= wx + cw and wy <= y <= wy + ch:
return {"card": self.engine.waste[-1], "x": wx, "y": wy, "size": self.card_size, "under_tag": None}
return None
def _hit_test(self, x: int, y: int) -> dict | None:
cw, ch = self.card_size
for r in range(6, -1, -1):
for c in range(r, -1, -1):
card = self.engine.pyramid[r][c]
if card is None:
continue
px, py = self._pyr_coords[r][c]
if px <= x <= px + cw and py <= y <= py + ch:
if not self.engine.is_pyramid_exposed(r, c):
return None
ref = ("pyramid", r, c)
return {"zone": "pyramid", "ref": ref, "cards": [card], "origin": (px, py)}
# Klick auf den linken Stapel wählt IMMER die offene Karte aus (oder bei leerem Stapel Redeal)
sx, sy = self._stock_xy
if sx <= x <= sx + cw and sy <= y <= sy + ch:
if self.engine.stock:
ref = ("stock",)
return {"zone": "stock", "ref": ref, "cards": [self.engine.stock[-1]], "origin": (sx, sy)}
return None
wx, wy = self._waste_xy
if self.engine.waste and wx <= x <= wx + cw and wy <= y <= wy + ch:
ref = ("waste",)
return {"zone": "waste", "ref": ref, "cards": [self.engine.waste[-1]], "origin": (wx, wy)}
return None
def _on_next_card_clicked(self):
"""Schiebt per Button 'Nächste Karte' die linke Karte nach rechts (oder Redeal)."""
if self._is_ui_locked():
return
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator:
self.animator.flush()
self.animator.cancel_shake()
self._clear_hint()
self._selected_ref = None
self.engine.start_timer_if_needed()
def do_advance() -> bool:
ok, reason = self.engine.draw_or_recycle_stock()
if not ok:
if reason == "redeal_limit":
self.status_var.set(t("sol_redeal_limit_msg", self.engine.max_redeals))
elif reason == "stagnant":
self.status_var.set(t("sol_stock_stagnant_msg"))
self.redraw()
self._check_deadlock_and_prompt()
return ok
self._run_animated_action(do_advance, duration_ms=95, after_cb=self._after_player_move)
def _handle_click(self, info: dict):
if self.animator:
self.animator.cancel_shake()
ref = info.get("ref")
if ref is None:
return
card = self.engine.get_card_at_ref(ref)
if card is None:
return
# König (13) ohne aktive Vorwahl -> sofort drehend herausfallen lassen
if card.value == 13 and self._selected_ref is None:
self._execute_clear_with_fall([ref], lambda: self.engine.remove_king(ref))
return
# Zweite Karte angeklickt -> Paar (inkl. Links + Rechts!) prüfen
if self._selected_ref is not None:
if self._selected_ref == ref:
self._selected_ref = None
self.ctx.sounds.play("click")
self.redraw()
return
prev_ref = self._selected_ref
prev_card = self.engine.get_card_at_ref(prev_ref)
ok, total = self.engine.can_pair_refs(prev_ref, ref)
self._selected_ref = None
if ok:
self._execute_clear_with_fall(
[prev_ref, ref], lambda: self.engine.remove_pair(prev_ref, ref)
)
return
if prev_card is not None:
self.status_var.set(
t("py_sum_mismatch_msg", prev_card.label, prev_card.value, card.label, card.value, total)
)
self.ctx.sounds.play("click")
self._trigger_mismatch_shake([prev_ref, ref])
return
# Erste Karte angeklickt (auch links auf dem Stapel!) -> immer erst auswählen!
self._selected_ref = ref
self.status_var.set("")
self.ctx.sounds.play("click")
self.redraw()
def _smart_auto_move(self, info: dict):
self._handle_click(info)
def _on_mouse_up(self, event):
info, was_dragging = self._press_info, self._dragging
self._press_info, self._dragging = None, False
if not info:
return
if not was_dragging:
self._handle_click(info)
return
self.canvas.delete("drag_ghost")
ox, oy = info["origin"]
sx, sy = info["start_xy"]
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
if self._try_drop(info, drop_x, drop_y):
return
cards: list[SolitaireCard] = info.get("cards", [])
if cards and self.animator:
hidden_keys = {self._card_key(cards[0])}
self.redraw(hidden_card_keys=hidden_keys)
self.animator.start(
[{"card": cards[0], "start": (drop_x, drop_y), "end": (ox, oy)}],
self._draw_card_at,
duration_ms=85,
on_done=self.redraw,
)
else:
self.redraw()
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
if self.animator:
self.animator.cancel_shake()
src_ref = info.get("ref")
cards = info.get("cards", [])
if src_ref is None or not cards:
return False
cw, ch = self.card_size
cx, cy = drop_x + cw // 2, drop_y + ch // 2
if cards[0].value == 13 and self._selected_ref is None:
ox, oy = info["origin"]
if abs(drop_x - ox) > 18 or abs(drop_y - oy) > 18:
return self._execute_clear_with_fall(
[src_ref],
lambda: self.engine.remove_king(src_ref),
override_first_xy=(drop_x, drop_y),
)
return False
candidates: list[tuple[int, tuple]] = []
for r in range(7):
for c in range(r + 1):
if not self.engine.is_pyramid_exposed(r, c):
continue
t_ref = ("pyramid", r, c)
if t_ref == src_ref:
continue
px, py = self._pyr_coords[r][c]
dx, dy = abs(cx - (px + cw // 2)), abs(cy - (py + ch // 2))
if dx <= int(cw * 0.72) and dy <= int(ch * 0.72):
candidates.append((dx + dy, t_ref))
for t_ref, (tx, ty) in ((("stock",), self._stock_xy), (("waste",), self._waste_xy)):
if t_ref == src_ref or self.engine.get_card_at_ref(t_ref) is None:
continue
dx, dy = abs(cx - (tx + cw // 2)), abs(cy - (ty + ch // 2))
if dx <= int(cw * 0.72) and dy <= int(ch * 0.72):
candidates.append((dx + dy, t_ref))
candidates.sort(key=lambda item: item[0])
for _dist, dst_ref in candidates:
ok, total = self.engine.can_pair_refs(src_ref, dst_ref)
self._selected_ref = None
if ok:
return self._execute_clear_with_fall(
[src_ref, dst_ref],
lambda: self.engine.remove_pair(src_ref, dst_ref),
override_first_xy=(drop_x, drop_y),
)
dst_card = self.engine.get_card_at_ref(dst_ref)
if dst_card is not None:
self.status_var.set(
t("py_sum_mismatch_msg", cards[0].label, cards[0].value, dst_card.label, dst_card.value, total)
)
self.ctx.root.after(95, lambda a=src_ref, b=dst_ref: self._trigger_mismatch_shake([a, b]))
return False
return False

View File

View File

@ -0,0 +1,247 @@
# -*- coding: utf-8 -*-
# games/solitaire/tripeaks/models/tripeaks_engine.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireBaseEngine, SolitaireCard
from games.solitaire.tripeaks.models.tripeaks_solver import (
TRIPEAKS_CHILDREN,
generate_solvable_tripeaks_deal,
is_tripeaks_adjacent_val,
)
from resources.code_res.game_constants import TRIPEAKS_REDEALS_BY_DIFF
class TriPeaksEngine(SolitaireBaseEngine):
"""
Spiellogik für TriPeaks Solitaire:
- 28 Karten in 3 Gipfeln (Indices 0..2 = Gipfelspitzen; 18..27 = offene Basisreihe)
- Sobald beide Kinder einer Karte entfernt sind, deckt sie sich automatisch auf
- Jede offene freie Karte mit Wert ±1 zur Ablagekarte (inkl. Ass <-> König!) kann gespielt werden
- Kombo-Punkte steigen mit jeder Karte in Folge ohne Talon-Zug; Gipfel-Abräumen gibt Extrabonus!
"""
NUM_SLOTS = 28
PEAK_INDICES = (0, 1, 2)
SCORE_BASE_CARD = 10
SCORE_STREAK_STEP = 5
SCORE_PEAK_BONUS = 50
def __init__(self, difficulty: int = 1, seed: int | None = None):
super().__init__()
self.difficulty: int = max(0, min(3, int(difficulty)))
self.seed: int | None = seed
self.max_redeals: int = TRIPEAKS_REDEALS_BY_DIFF.get(self.difficulty, 1)
self.redeals_used: int = 0
self.stagnant_cycles: int = 0
self._progress_in_cycle: bool = False
self.streak: int = 0
self.board: list[SolitaireCard | None] = [None] * self.NUM_SLOTS
self.stock: list[SolitaireCard] = []
self.waste: list[SolitaireCard] = []
self.new_game(difficulty=self.difficulty, seed=seed)
def new_game(self, difficulty: int | None = None, seed: int | None = None):
if difficulty is not None:
self.difficulty = max(0, min(3, int(difficulty)))
self.seed = seed
self.max_redeals = TRIPEAKS_REDEALS_BY_DIFF.get(self.difficulty, 1)
self.redeals_used = 0
self.stagnant_cycles = 0
self._progress_in_cycle = False
self.streak = 0
self.reset_tracking()
self.board, self.stock, self.waste = generate_solvable_tripeaks_deal(
difficulty=self.difficulty, seed=seed
)
self._refresh_face_up_states()
self.capture_initial_state()
@property
def redeals_remaining(self) -> int:
return max(0, self.max_redeals - self.redeals_used)
@property
def peaks_cleared_count(self) -> int:
return sum(1 for p_idx in self.PEAK_INDICES if self.board[p_idx] is None)
@property
def board_remaining_count(self) -> int:
return sum(1 for c in self.board if c is not None)
@property
def waste_top(self) -> SolitaireCard | None:
return self.waste[-1] if self.waste else None
@property
def is_stock_locked(self) -> bool:
if self.stock:
return False
if len(self.waste) <= 1:
return True
return self.redeals_used >= self.max_redeals or self.stagnant_cycles >= 3
def is_slot_exposed(self, idx: int) -> bool:
if not (0 <= idx < self.NUM_SLOTS) or self.board[idx] is None:
return False
children = TRIPEAKS_CHILDREN[idx]
if not children:
return True
return self.board[children[0]] is None and self.board[children[1]] is None
def _refresh_face_up_states(self):
for idx, card in enumerate(self.board):
if card is not None and self.is_slot_exposed(idx):
card.face_up = True
def can_play_slot(self, idx: int) -> bool:
if self.won or not self.is_slot_exposed(idx) or not self.waste:
return False
card = self.board[idx]
assert card is not None
return is_tripeaks_adjacent_val(card.value, self.waste[-1].value)
def play_slot(self, idx: int, record_undo: bool = True) -> bool:
if not self.can_play_slot(idx):
return False
if record_undo:
self.push_undo()
card = self.board[idx]
assert card is not None
self.board[idx] = None
card.face_up = True
self.waste.append(card)
self.streak += 1
pts = self.SCORE_BASE_CARD + (self.streak - 1) * self.SCORE_STREAK_STEP
if idx in self.PEAK_INDICES:
pts += self.SCORE_PEAK_BONUS
self.score = max(0, self.score + pts)
self.moves += 1
self._progress_in_cycle = True
self.stagnant_cycles = 0
self._refresh_face_up_states()
if self.board_remaining_count == 0:
self.mark_won()
return True
def draw_or_recycle_stock(self) -> tuple[bool, str]:
if self.won:
return False, ""
if self.stock:
self.push_undo()
card = self.stock.pop()
card.face_up = True
self.waste.append(card)
self.streak = 0
self.moves += 1
return True, "draw"
if len(self.waste) <= 1:
return False, "empty"
if self.redeals_used >= self.max_redeals:
return False, "redeal_limit"
if self.stagnant_cycles >= 3:
return False, "stagnant"
self.push_undo()
if not self._progress_in_cycle:
self.stagnant_cycles += 1
if self.stagnant_cycles >= 3:
self._undo_stack.pop()
return False, "stagnant"
self._progress_in_cycle = False
self.redeals_used += 1
recycled = list(reversed(self.waste))
for c in recycled:
c.face_up = False
first_up = recycled.pop()
first_up.face_up = True
self.stock = recycled
self.waste = [first_up]
self.streak = 0
self.moves += 1
return True, "recycle"
def can_auto_complete(self) -> bool:
return False
def auto_complete_step(self, record_undo: bool = False) -> bool:
_ = record_undo
return False
def has_any_meaningful_move(self) -> bool:
if self.won:
return True
for idx in range(self.NUM_SLOTS):
if self.can_play_slot(idx):
return True
if self.stock:
return True
if len(self.waste) > 1 and self.redeals_used < self.max_redeals and self.stagnant_cycles < 3:
return True
return False
def get_hint(self) -> dict | None:
# Bevorzuge Karten, die direkt neue verdeckte Karten in der Reihe darüber freilegen!
playable = [idx for idx in range(self.NUM_SLOTS) if self.can_play_slot(idx)]
if playable:
def _priority(slot_i: int) -> tuple[int, int]:
# 1. Gipfelspitze sofort abräumen, 2. legt direkt Elternkarte frei
if slot_i in self.PEAK_INDICES:
return (3, -slot_i)
unblocks = 0
for p_i in range(18):
if self.board[p_i] is not None and slot_i in TRIPEAKS_CHILDREN[p_i]:
c1, c2 = TRIPEAKS_CHILDREN[p_i]
other = c2 if c1 == slot_i else c1
if self.board[other] is None:
unblocks += 2
else:
unblocks += 1
return (unblocks, -slot_i)
playable.sort(key=_priority, reverse=True)
return {"type": "play", "refs": [("board", playable[0])]}
if not self.is_stock_locked:
return {"type": "draw", "refs": [("stock",)]}
return None
def serialize_board(self) -> dict:
return {
"difficulty": self.difficulty,
"max_redeals": self.max_redeals,
"redeals_used": self.redeals_used,
"stagnant_cycles": self.stagnant_cycles,
"progress_in_cycle": self._progress_in_cycle,
"streak": self.streak,
"board": [c.to_dict() if c is not None else None for c in self.board],
"stock": [c.to_dict() for c in self.stock],
"waste": [c.to_dict() for c in self.waste],
}
def restore_board(self, board: dict):
self.difficulty = max(0, min(3, int(board.get("difficulty", 1))))
self.max_redeals = int(
board.get("max_redeals", TRIPEAKS_REDEALS_BY_DIFF.get(self.difficulty, 1))
)
self.redeals_used = int(board.get("redeals_used", 0))
self.stagnant_cycles = int(board.get("stagnant_cycles", 0))
self._progress_in_cycle = bool(board.get("progress_in_cycle", False))
self.streak = int(board.get("streak", 0))
self.board = [
SolitaireCard.from_dict(d) if d is not None else None
for d in board["board"]
]
self.stock = [SolitaireCard.from_dict(d) for d in board.get("stock", [])]
for c in self.stock:
c.face_up = False
self.waste = [SolitaireCard.from_dict(d) for d in board.get("waste", [])]
for c in self.waste:
c.face_up = True
self._refresh_face_up_states()

View File

@ -0,0 +1,264 @@
# -*- coding: utf-8 -*-
# games/solitaire/tripeaks/models/tripeaks_solver.py
from __future__ import annotations
import heapq
import random
from dataclasses import dataclass
from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
from resources.code_res.game_constants import SUITS, TRIPEAKS_REDEALS_BY_DIFF
_SUIT = tuple(c // 13 for c in range(52))
_VAL = tuple((c % 13) + 1 for c in range(52))
# Klassische 28-Karten-TriPeaks-Geometrie in Halb-Karten-Schritten (x_half = 0..18):
# Reihe 0 (3 Gipfel): Indices 0..2 -> x_half: 3, 9, 15
# Reihe 1 (6 Karten): Indices 3..8 -> x_half: 2,4 | 8,10 | 14,16
# Reihe 2 (9 Karten): Indices 9..17 -> x_half: 1,3,5 | 7,9,11 | 13,15,17
# Reihe 3 (10 Basis): Indices 18..27 -> x_half: 0,2,4,6,8,10,12,14,16,18
TRIPEAKS_LAYOUT: tuple[tuple[int, int], ...] = (
# Row 0 (Peaks)
(0, 3), (0, 9), (0, 15),
# Row 1
(1, 2), (1, 4), (1, 8), (1, 10), (1, 14), (1, 16),
# Row 2
(2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (2, 11), (2, 13), (2, 15), (2, 17),
# Row 3 (Base, initially face-up)
(3, 0), (3, 2), (3, 4), (3, 6), (3, 8), (3, 10), (3, 12), (3, 14), (3, 16), (3, 18),
)
_POS_TO_IDX: dict[tuple[int, int], int] = {
pos: idx for idx, pos in enumerate(TRIPEAKS_LAYOUT)
}
TRIPEAKS_CHILDREN: tuple[tuple[int, ...], ...] = tuple(
()
if r == 3
else (_POS_TO_IDX[(r + 1, xh - 1)], _POS_TO_IDX[(r + 1, xh + 1)])
for (r, xh) in TRIPEAKS_LAYOUT
)
TRIPEAKS_CHILD_MASKS: tuple[int, ...] = tuple(
0 if not ch else ((1 << ch[0]) | (1 << ch[1]))
for ch in TRIPEAKS_CHILDREN
)
def is_tripeaks_adjacent_val(va: int, vb: int) -> bool:
diff = abs(va - vb)
return diff == 1 or diff == 12
@dataclass
class TriPeaksSolveReport:
solvable: bool
nodes_expanded: int
layout_hardness: float
def _decode_card(cid: int, face_up: bool) -> SolitaireCard:
return SolitaireCard(
suit=SUITS[_SUIT[cid]],
rank=SOLITAIRE_RANKS[cid % 13],
face_up=face_up,
deck_id=0,
)
def _exposed_indices(board_mask: int) -> list[int]:
out: list[int] = []
m = board_mask
while m:
lsb = m & -m
idx = lsb.bit_length() - 1
if (board_mask & TRIPEAKS_CHILD_MASKS[idx]) == 0:
out.append(idx)
m ^= lsb
return out
def evaluate_tripeaks_hardness(board_ids: list[int], start_waste_id: int) -> float:
"""
Bewertet die strukturelle Schwierigkeit eines TriPeaks-Bretts:
- Viele benachbarte Ränge (±1) in der offenen 10er-Basisreihe erlauben sofort lange Ketten (leicht).
- Gleiche Ränge direkt übereinander oder isolierte Sprünge bremsen Ketten aus (schwer).
"""
score = 18.0
base_vals = [_VAL[board_ids[i]] for i in range(18, 28)]
w_val = _VAL[start_waste_id]
start_hits = sum(1 for v in base_vals if is_tripeaks_adjacent_val(v, w_val))
if start_hits == 0:
score += 10.0
else:
score -= start_hits * 3.5
adj_pairs = 0
for i in range(len(base_vals)):
for j in range(i + 1, len(base_vals)):
if is_tripeaks_adjacent_val(base_vals[i], base_vals[j]):
adj_pairs += 1
score -= adj_pairs * 1.4
for idx in range(18):
vp = _VAL[board_ids[idx]]
c1, c2 = TRIPEAKS_CHILDREN[idx]
if vp == _VAL[board_ids[c1]] or vp == _VAL[board_ids[c2]]:
score += 3.2
if is_tripeaks_adjacent_val(vp, _VAL[board_ids[c1]]):
score -= 1.5
if is_tripeaks_adjacent_val(vp, _VAL[board_ids[c2]]):
score -= 1.5
return score
def solve_tripeaks_deal(
deck_ids: list[int], max_redeals: int, max_nodes: int = 4200
) -> TriPeaksSolveReport:
"""
deck_ids[0..27] = 28 Tableau-Karten
deck_ids[28] = erste offene Startkarte auf der Ablage (Waste)
deck_ids[29..51] = 23 verdeckte Talon-Karten (stock_t[-1] wird als Nächstes gezogen)
"""
board_ids = deck_ids[:28]
first_waste = deck_ids[28]
stock_ids = deck_ids[29:]
hardness = evaluate_tripeaks_hardness(board_ids, first_waste)
init_mask = (1 << 28) - 1
# Für 0 Redeals brauchen wir nur den Wert der obersten Waste-Karte zu speichern -> kollabiert Zustände extrem!
use_compact_waste = (max_redeals == 0)
if use_compact_waste:
start_state = (init_mask, len(stock_ids), _VAL[first_waste])
else:
start_state = (init_mask, tuple(stock_ids), (first_waste,), max_redeals)
visited: set[tuple] = {start_state}
pq: list[tuple[int, int, int, tuple]] = []
counter = 0
heapq.heappush(pq, (28 * 4 - max_redeals * 3, 0, counter, start_state))
nodes = 0
while pq and nodes < max_nodes:
_prio, depth, _tie, state = heapq.heappop(pq)
nodes += 1
if use_compact_waste:
b_mask, stock_len, top_val = state
if b_mask == 0:
return TriPeaksSolveReport(True, nodes, hardness)
exposed = _exposed_indices(b_mask)
next_states: list[tuple] = []
for idx in exposed:
iv = _VAL[board_ids[idx]]
if is_tripeaks_adjacent_val(iv, top_val):
next_states.append((b_mask & ~(1 << idx), stock_len, iv))
if stock_len > 0:
drawn_cid = stock_ids[stock_len - 1]
next_states.append((b_mask, stock_len - 1, _VAL[drawn_cid]))
for ns in next_states:
if ns[0] == 0:
return TriPeaksSolveReport(True, nodes, hardness)
if ns not in visited:
visited.add(ns)
counter += 1
h = ns[0].bit_count() * 4 + (23 - ns[1])
heapq.heappush(pq, (h + depth // 4, depth + 1, counter, ns))
else:
b_mask, stock_t, waste_t, redeals_rem = state
if b_mask == 0:
return TriPeaksSolveReport(True, nodes, hardness)
exposed = _exposed_indices(b_mask)
top_val = _VAL[waste_t[-1]]
next_states = []
for idx in exposed:
cid = board_ids[idx]
if is_tripeaks_adjacent_val(_VAL[cid], top_val):
next_states.append((b_mask & ~(1 << idx), stock_t, waste_t + (cid,), redeals_rem))
if stock_t:
next_states.append((b_mask, stock_t[:-1], waste_t + (stock_t[-1],), redeals_rem))
elif len(waste_t) > 1 and redeals_rem > 0:
# Redeal: Waste umdrehen, erste Karte sofort als neue offene Ablagekarte aufdecken
recycled = list(reversed(waste_t))
new_first = recycled.pop()
next_states.append((b_mask, tuple(recycled), (new_first,), redeals_rem - 1))
for ns in next_states:
if ns[0] == 0:
return TriPeaksSolveReport(True, nodes, hardness)
if ns not in visited:
visited.add(ns)
counter += 1
h = ns[0].bit_count() * 4 - ns[3] * 3
heapq.heappush(pq, (h + depth // 4, depth + 1, counter, ns))
return TriPeaksSolveReport(False, nodes, hardness)
def generate_solvable_tripeaks_deal(
difficulty: int = 1,
seed: int | None = None,
) -> tuple[list[SolitaireCard | None], list[SolitaireCard], list[SolitaireCard]]:
"""
Erzeugt ein garantiert lösbares TriPeaks-Deck (28er Tableau, 23er Talon, 1 Start-Waste)
passend zur Schwierigkeit (0..3 -> 2 / 1 / 0 / 0 Redeals).
"""
rng = random.Random(seed) if seed is not None else random.Random()
diff = max(0, min(3, int(difficulty)))
max_redeals = TRIPEAKS_REDEALS_BY_DIFF.get(diff, 1)
targets = {0: -4.0, 1: 8.0, 2: 14.0, 3: 28.0}
target = targets[diff]
node_budget = 3000 if diff <= 1 else 4800
base_deck = list(range(52))
candidates: list[tuple[float, list[int]]] = []
for _attempt in range(320):
trial = list(base_deck)
rng.shuffle(trial)
report = solve_tripeaks_deal(trial, max_redeals=max_redeals, max_nodes=node_budget)
if not report.solvable:
continue
composite = report.layout_hardness + (report.nodes_expanded / 45.0)
candidates.append((composite, trial))
if diff == 0 and composite <= 2.0:
break
if diff == 1 and 2.0 <= composite <= 18.0:
break
if diff == 2 and 10.0 <= composite <= 24.0 and len(candidates) >= 2:
break
if diff == 3 and composite >= 22.0 and len(candidates) >= 2:
break
if len(candidates) >= 4:
break
while not candidates:
trial = list(base_deck)
rng.shuffle(trial)
report = solve_tripeaks_deal(trial, max_redeals=max_redeals, max_nodes=6000)
if report.solvable:
candidates.append((report.layout_hardness + report.nodes_expanded / 45.0, trial))
if diff == 3:
best = max(candidates, key=lambda x: x[0])[1]
elif diff == 0:
best = min(candidates, key=lambda x: x[0])[1]
else:
best = min(candidates, key=lambda x: abs(x[0] - target))[1]
# Reihen 0..2 (Indices 0..17) starten verdeckt, Reihe 3 (Indices 18..27) startet offen!
board: list[SolitaireCard | None] = [
_decode_card(best[i], face_up=(i >= 18)) for i in range(28)
]
waste = [_decode_card(best[28], face_up=True)]
stock = [_decode_card(cid, face_up=False) for cid in best[29:]]
return board, stock, waste

View File

@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
# games/solitaire/tripeaks/start.py
from games.solitaire.tripeaks.views.tripeaks_menu_view import TriPeaksMenuView
from resources.code_res.game_constants import CAT_SOLO
GAME_TITLE_KEY = "game_title_tripeaks"
GAME_FOLDER_ID = "solitaire/tripeaks"
GAME_CATEGORY = CAT_SOLO
def start_game(context):
TriPeaksMenuView(context).show(ask_resume_popup=True)

View File

@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# games/solitaire/tripeaks/views/tripeaks_menu_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.tripeaks.views.tripeaks_table_view import TriPeaksTableView
from resources.code_res.game_constants import TRIPEAKS_VARIANTS
GAME_FOLDER_ID = "solitaire/tripeaks"
GAME_TITLE_KEY = "game_title_tripeaks"
class TriPeaksMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "tp_menu_topbar"
SUBTITLE_KEY = "tp_menu_subtitle"
CONTROLS_HINT_KEY = "tp_controls_hint"
DIFF_SETTING_PREFIX = "tripeaks_diff"
DEFAULT_VARIANT_KEY = "tripeaks_std"
REQUIRED_BOARD_KEYS = ("board", "waste")
MODE_LABEL_KEY = "tp_variant_info_lbl"
DESC_KEY_PREFIX = "tp_desc_"
def _variants_dict(self) -> dict[str, dict]:
return TRIPEAKS_VARIANTS
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
TriPeaksTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

View File

@ -0,0 +1,462 @@
# -*- coding: utf-8 -*-
# games/solitaire/tripeaks/views/tripeaks_table_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_table_controller import SolitaireTableController
from games.solitaire.tripeaks.models.tripeaks_engine import TriPeaksEngine
from games.solitaire.tripeaks.models.tripeaks_solver import TRIPEAKS_LAYOUT
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_SMALL_MIN,
SUBTLE_BORDER,
TRIPEAKS_VARIANTS,
)
from resources.code_res.i18n import t
GAME_FOLDER_ID = "solitaire/tripeaks"
GAME_TITLE_KEY = "game_title_tripeaks"
class TriPeaksTableView(SolitaireTableController):
GAME_FOLDER_ID = GAME_FOLDER_ID
HAS_AUTOCOMPLETE_BTN = False
SPEED_THRESHOLDS_SEC = (95, 185)
SOCKET_PAD_PX = 6
def __init__(
self,
context,
variant_key: str = "tripeaks_std",
difficulty: int = 1,
on_back_to_menu=None,
resume_state_json: str | None = None,
):
v_key = variant_key if variant_key in TRIPEAKS_VARIANTS else "tripeaks_std"
cfg = TRIPEAKS_VARIANTS[v_key]
self._init_controller_state(context, v_key, cfg, difficulty, on_back_to_menu)
self._slot_coords: list[tuple[int, int]] = [(0, 0)] * 28
self._stock_xy: tuple[int, int] = (0, 0)
self._waste_xy: tuple[int, int] = (0, 0)
if resume_state_json:
self.engine = TriPeaksEngine.__new__(TriPeaksEngine)
super(TriPeaksEngine, self.engine).__init__()
self.engine.difficulty = self.difficulty
self.engine.seed = None
self.engine.max_redeals = 1
self.engine.redeals_used = 0
self.engine.stagnant_cycles = 0
self.engine._progress_in_cycle = False
self.engine.streak = 0
self.engine.board = [None] * 28
self.engine.stock = []
self.engine.waste = []
try:
self.engine.load_json(resume_state_json)
self.difficulty = self.engine.difficulty
except Exception:
self.engine.new_game(difficulty=self.difficulty)
else:
self.engine = TriPeaksEngine(difficulty=self.difficulty)
self._finish_startup(is_resumed=bool(resume_state_json))
def _build_ui(self):
super()._build_ui()
self._bind_root("<space>", lambda _e: self._on_space_draw())
def _on_space_draw(self) -> str:
if not self._is_ui_locked():
self._trigger_draw_or_recycle()
return "break"
def _extra_hud_suffix(self) -> str:
return t(
"tp_hud_extra",
self.engine.streak,
self.engine.peaks_cleared_count,
self.engine.redeals_remaining,
self.engine.max_redeals,
)
def _reset_engine_for_new_deal(self):
if self.animator:
self.animator.cancel_shake()
self.engine.new_game(difficulty=self.difficulty)
def _on_undo(self):
if self.animator:
self.animator.cancel_shake()
super()._on_undo()
def _on_undo_all(self):
if self.animator:
self.animator.cancel_shake()
super()._on_undo_all()
def _trigger_mismatch_shake(self, slot_idx: int):
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator is not None:
self.animator.start_shake([("board", slot_idx), ("waste",)], self.redraw)
def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]:
pos: dict[tuple[str, str, int], tuple[int, int]] = {}
for idx, card in enumerate(self.engine.board):
if card is not None:
pos[self._card_key(card)] = self._slot_coords[idx]
for card in self.engine.stock:
pos[self._card_key(card)] = self._stock_xy
for card in self.engine.waste:
pos[self._card_key(card)] = self._waste_xy
return pos
def _ordered_moved_cards(self, moved_keys: set[tuple[str, str, int]]) -> list[SolitaireCard]:
ordered: list[SolitaireCard] = []
for card in self.engine.board:
if card is not None and self._card_key(card) in moved_keys:
ordered.append(card)
for pile in (self.engine.stock, self.engine.waste):
for card in pile:
if self._card_key(card) in moved_keys:
ordered.append(card)
return ordered
def _recompute_and_draw(self):
self._resize_job = None
if not self._canvas_alive() or self._fx_overlay is not None:
return
cw, ch = max(680, self.canvas.winfo_width()), max(420, self.canvas.winfo_height())
aspect = self._get_card_aspect()
margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch)
v_top = max(14, int(top_pad * 0.34))
v_bot = max(14, int(bot_pad * 0.34))
self._frame_bot_pad = v_bot
usable_w = max(580, cw - 2 * margin_x)
usable_h = max(270, ch - v_top - v_bot)
# Breite: 10 Basiskarten nebeneinander (18 Halb-Schritte + 1 Kartenbreite)
# Höhe: 4 Gipfel-Reihen (1 + 3*0.44 Kartenhöhen) + Abstand + untere Deck/Ablage-Zeile (1 Kartenhöhe)
card_w_by_w = int(usable_w / 10.75)
card_w_by_h = int(round((usable_h / 3.68) / aspect))
card_w = max(58, min(124, card_w_by_w, card_w_by_h))
card_h = int(round(card_w * aspect))
self.card_size = (card_w, card_h)
half_step_x = max(31, int(round((card_w + max(6, int(card_w * 0.08))) / 2.0)))
row_dy = max(28, int(round(card_h * 0.44)))
peaks_total_w = 18 * half_step_x + card_w
peaks_total_h = 3 * row_dy + card_h
bottom_gap = max(32, min(54, usable_h - peaks_total_h - card_h - 12))
scene_h = peaks_total_h + bottom_gap + card_h
start_x = max(margin_x, (cw - peaks_total_w) // 2)
start_y = v_top + max(0, (usable_h - scene_h) // 2)
for idx, (r, xh) in enumerate(TRIPEAKS_LAYOUT):
self._slot_coords[idx] = (start_x + xh * half_step_x, start_y + r * row_dy)
# Unten mittig unter den 3 Gipfeln: [Verdeckter Talon] [Offene Ablage (±1)]
pair_gap = max(28, int(card_w * 0.36))
pair_w = 2 * card_w + pair_gap
pair_x0 = (cw - pair_w) // 2
deck_y = start_y + peaks_total_h + bottom_gap
self._stock_xy = (pair_x0, deck_y)
self._waste_xy = (pair_x0 + card_w + pair_gap, deck_y)
self.redraw()
def _draw_deck_socket(self, x: int, y: int, highlight_color: str | None = None):
cw, ch = self.card_size
pad = self.SOCKET_PAD_PX
outer_col = highlight_color if highlight_color else BORDER_COLOR
outer_w = 2 if highlight_color else 1
self.canvas.create_rectangle(
x - pad, y - pad, x + cw + pad, y + ch + pad,
fill=CELL_BG, outline=outer_col, width=outer_w,
)
self.canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
fill="", outline=SUBTLE_BORDER, width=1,
)
def _draw_pile_caption(self, cx: int, y: int, txt: str, color: str = FONT_COLOR_BODY_MUTED):
ph = self.ctx.assets.get_goth_text_photo(txt, FONT_SIZE_SMALL_MIN, color)
self._canvas_ui_refs.append(ph)
self.canvas.create_image(cx, y, image=ph, anchor="center")
def redraw(
self,
exclude_source: dict | None = None,
hidden_card_keys: set[tuple[str, str, int]] | None = None,
):
if not self._canvas_alive():
return
canvas_w, canvas_h = self._prepare_canvas_frame(680, 420)
cw, ch = self.card_size
hidden = hidden_card_keys or set()
hint_refs = set(self._active_hint.get("refs", [])) if self._active_hint else set()
# 1. Alle 28 Plätze der 3 Gipfel von oben (Reihe 0) nach unten (Reihe 3) zeichnen
for idx in range(28):
px, py = self._slot_coords[idx]
card = self.engine.board[idx]
ref = ("board", idx)
if exclude_source and exclude_source.get("ref") == ref:
card = None
if card is None or self._card_key(card) in hidden:
if idx in TriPeaksEngine.PEAK_INDICES and self.engine.board[idx] is None:
self._draw_slot(px, py, symbol="▲", symbol_color=ACCENT_GOLD)
continue
is_shaking, s_dx = (
self.animator.shake_state_for(ref) if self.animator else (False, 0)
)
hl = (
ERROR_FG
if is_shaking
else (ACCENT_GOLD if ref in hint_refs else None)
)
self._draw_card_at(
card,
px + s_dx,
py,
tags=(f"tp_slot_{idx}",),
highlight_color=hl,
)
# 2. Verdeckter Zieh-Stapel unten links
sx, sy = self._stock_xy
draw_hl = ACCENT_GOLD if ("stock",) in hint_refs else None
locked = self.engine.is_stock_locked
vis_stock = [c for c in self.engine.stock if self._card_key(c) not in hidden]
self._draw_deck_socket(sx, sy, highlight_color=draw_hl)
if vis_stock:
back_ph = self.ctx.assets.get_card_back_photo(
self.cfg["back_color"], size=self.card_size
)
if back_ph is not None:
if len(vis_stock) >= 10:
self.canvas.create_image(sx - 3, sy - 3, image=back_ph, anchor="nw")
elif len(vis_stock) >= 4:
self.canvas.create_image(sx - 2, sy - 2, image=back_ph, anchor="nw")
self.canvas.create_image(sx, sy, image=back_ph, anchor="nw", tags=("tp_stock_back",))
if draw_hl:
self.canvas.create_rectangle(
sx - 2, sy - 2, sx + cw + 2, sy + ch + 2, outline=draw_hl, width=2
)
else:
self._draw_slot(sx, sy, symbol="↻", highlight_color=draw_hl)
else:
sym = "" if locked else ("↻" if len(self.engine.waste) > 1 else "—")
self._draw_slot(
sx,
sy,
symbol=sym,
symbol_color=ACCENT_GOLD if sym == "↻" else SUBTLE_BORDER,
highlight_color=draw_hl,
draw_red_cross=bool(locked and len(self.engine.waste) > 1),
)
stock_lbl = (
t("tp_lbl_draw", len(self.engine.stock))
if self.engine.stock
else t("tp_lbl_redeal", self.engine.redeals_remaining)
)
self._draw_pile_caption(sx + cw // 2, sy - self.SOCKET_PAD_PX - 14, stock_lbl)
# 3. Offene Ablagekarte (±1 Zielstapel) unten rechts
wx, wy = self._waste_xy
w_shaking, w_dx = (
self.animator.shake_state_for(("waste",)) if self.animator else (False, 0)
)
drag_can_drop = False
if self._dragging and self._press_info and self._press_info.get("ref"):
slot_i = self._press_info["ref"][1]
drag_can_drop = self.engine.can_play_slot(slot_i)
w_hl = ERROR_FG if w_shaking else (ACCENT_GOTH if drag_can_drop else None)
self._draw_deck_socket(wx, wy, highlight_color=None if w_shaking else w_hl)
w_pile = [c for c in self.engine.waste if self._card_key(c) not in hidden]
if w_pile:
if w_shaking and len(w_pile) >= 2:
self._draw_card_at(w_pile[-2], wx, wy, tags=("tp_waste_under",))
self._draw_card_at(w_pile[-1], wx + w_dx, wy, tags=("tp_waste_top",), highlight_color=w_hl)
else:
self._draw_slot(wx, wy, symbol="±1", symbol_color=SUBTLE_BORDER)
self._draw_pile_caption(
wx + cw // 2, wy - self.SOCKET_PAD_PX - 14, t("tp_lbl_waste"), FONT_COLOR_TITLE_MAIN
)
self._finish_canvas_frame(canvas_w, canvas_h, exclude_source, hidden)
def _find_first_overlapping_tag(self, idx: int) -> str | None:
cur_row = TRIPEAKS_LAYOUT[idx][0]
for lower_idx in range(idx + 1, 28):
if TRIPEAKS_LAYOUT[lower_idx][0] > cur_row and self.engine.board[lower_idx] is not None:
tag = f"tp_slot_{lower_idx}"
if self.canvas.find_withtag(tag):
return tag
return None
def _hover_card_probe(self, x: int, y: int) -> dict | None:
if self.animator and self.animator.has_shake:
return None
cw, ch = self.card_size
for idx in range(27, -1, -1):
card = self.engine.board[idx]
if card is None or not card.face_up:
continue
px, py = self._slot_coords[idx]
if px <= x <= px + cw and py <= y <= py + ch:
under_tag = (
None
if self.engine.is_slot_exposed(idx)
else self._find_first_overlapping_tag(idx)
)
return {"card": card, "x": px, "y": py, "size": self.card_size, "under_tag": under_tag}
wx, wy = self._waste_xy
if self.engine.waste and wx <= x <= wx + cw and wy <= y <= wy + ch:
return {"card": self.engine.waste[-1], "x": wx, "y": wy, "size": self.card_size, "under_tag": None}
return None
def _hit_test(self, x: int, y: int) -> dict | None:
cw, ch = self.card_size
pad = self.SOCKET_PAD_PX
sx, sy = self._stock_xy
if sx - pad <= x <= sx + cw + pad and sy - pad <= y <= sy + ch + pad:
return {"zone": "stock", "cards": [], "origin": (sx, sy)}
for idx in range(27, -1, -1):
card = self.engine.board[idx]
if card is None:
continue
px, py = self._slot_coords[idx]
if px <= x <= px + cw and py <= y <= py + ch:
if not self.engine.is_slot_exposed(idx):
return None
return {
"zone": "board",
"ref": ("board", idx),
"cards": [card],
"origin": (px, py),
}
return None
def _trigger_draw_or_recycle(self):
if self.animator:
self.animator.cancel_shake()
# Fall A: Neue Karte vom linken Stapel ziehen -> gleitet verdeckt nach rechts und deckt dort auf!
if self.engine.stock:
self.engine.start_timer_if_needed()
ok, _reason = self.engine.draw_or_recycle_stock()
if not ok:
return
self.ctx.sounds.play("click")
drawn = self.engine.waste[-1]
drawn.face_up = False
hidden_key = {self._card_key(drawn)}
self.redraw(hidden_card_keys=hidden_key)
def _reveal_on_waste():
drawn.face_up = True
if self._canvas_alive():
self._after_player_move()
if self.animator:
self.animator.start(
[{"card": drawn, "start": self._stock_xy, "end": self._waste_xy}],
self._draw_card_at,
duration_ms=92,
on_done=_reveal_on_waste,
)
else:
_reveal_on_waste()
return
# Fall B: Redeal (Ablagestapel umdrehen)
def do_recycle() -> bool:
ok, reason = self.engine.draw_or_recycle_stock()
if not ok:
if reason == "redeal_limit":
self.status_var.set(t("sol_redeal_limit_msg", self.engine.max_redeals))
elif reason == "stagnant":
self.status_var.set(t("sol_stock_stagnant_msg"))
self.redraw()
self._check_deadlock_and_prompt()
return ok
if self._run_animated_action(do_recycle, duration_ms=105, after_cb=self._after_player_move):
self.ctx.sounds.play("click")
def _handle_click(self, info: dict):
if self.animator:
self.animator.cancel_shake()
if info.get("zone") == "stock":
self._trigger_draw_or_recycle()
return
ref = info.get("ref")
if not ref:
return
slot_idx = ref[1]
card = self.engine.board[slot_idx]
if card is None:
return
if self.engine.can_play_slot(slot_idx):
if self._run_animated_action(
lambda: self.engine.play_slot(slot_idx),
duration_ms=98,
after_cb=self._after_player_move,
):
self.ctx.sounds.play("click")
return
# Passt nicht (±1 verletzt) -> Status-Hinweis + rotes Wackeln von Karte & Ablage!
w_top = self.engine.waste_top
if w_top is not None:
self.status_var.set(t("tp_adj_mismatch_msg", card.label, w_top.label))
self.ctx.sounds.play("click")
self._trigger_mismatch_shake(slot_idx)
def _smart_auto_move(self, info: dict):
self._handle_click(info)
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
if self.animator:
self.animator.cancel_shake()
ref = info.get("ref")
cards = info.get("cards", [])
if not ref or not cards:
return False
slot_idx = ref[1]
cw, ch = self.card_size
cx, cy = drop_x + cw // 2, drop_y + ch // 2
wx, wy = self._waste_xy
if abs(cx - (wx + cw // 2)) <= int(cw * 0.90) and abs(cy - (wy + ch // 2)) <= int(ch * 0.90):
if self.engine.can_play_slot(slot_idx):
return self.engine.play_slot(slot_idx)
w_top = self.engine.waste_top
if w_top is not None:
self.status_var.set(t("tp_adj_mismatch_msg", cards[0].label, w_top.label))
self.ctx.root.after(95, lambda s=slot_idx: self._trigger_mismatch_shake(s))
return False

57
models/bavarian_deck.py Normal file
View File

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
# models/bavarian_deck.py
from __future__ import annotations
from dataclasses import dataclass
import random
from resources.code_res.game_constants import BAVARIAN_RANKS, BAVARIAN_SUITS
BAVARIAN_RANK_ORDER: dict[str, int] = {
rank: idx for idx, rank in enumerate(BAVARIAN_RANKS)
}
# Index 0='6', 1='7', 2='8', 3='9', 4='10', 5='U', 6='O', 7='K', 8='A'
TEN_ORDER_INDEX = BAVARIAN_RANK_ORDER["10"]
@dataclass(frozen=True)
class BavarianCard:
"""Repräsentiert eine bayerische Spielkarte (Eichel, Blatt/Gras, Herz, Schellen)."""
suit: str
rank: str
@property
def order_index(self) -> int:
return BAVARIAN_RANK_ORDER[self.rank]
@property
def image_filename(self) -> str:
return f"{self.suit}{self.rank}.png"
@property
def short_code(self) -> str:
return f"{self.suit}{self.rank}"
def to_list(self) -> list[str]:
return [self.suit, self.rank]
@classmethod
def from_list(cls, raw: list[str] | tuple[str, str]) -> "BavarianCard":
return cls(suit=str(raw[0]), rank=str(raw[1]))
def create_bavarian_deck(
include_six: bool = True,
shuffle: bool = True,
rng: random.Random | None = None,
) -> list[BavarianCard]:
ranks = BAVARIAN_RANKS if include_six else BAVARIAN_RANKS[1:]
cards = [
BavarianCard(suit=s, rank=r)
for s in BAVARIAN_SUITS
for r in ranks
]
if shuffle:
(rng or random).shuffle(cards)
return cards

View File

@ -22,14 +22,19 @@ def _resolve_bundle_root() -> Path:
def _resolve_user_data_dir() -> Path: def _resolve_user_data_dir() -> Path:
"""Fallback-Speicherort neben der ausführbaren Datei bzw. im Benutzerverzeichnis.""" """Fallback-Speicherort neben der ausführbaren Datei (niemals /tmp!) bzw. im Benutzerverzeichnis."""
if getattr(sys, "frozen", False): if getattr(sys, "frozen", False):
exe_dir = Path(sys.executable).resolve().parent raw_exe = os.environ.get("ARGV0") or (sys.argv[0] if sys.argv else sys.executable)
if ".app/Contents/MacOS" not in str(exe_dir).replace("\\", "/") and os.access(exe_dir, os.W_OK): exe_dir = Path(raw_exe).expanduser().resolve().parent
exe_str = str(exe_dir).replace("\\", "/")
if (
".app/Contents/MacOS" not in exe_str
and not exe_str.startswith("/tmp")
and "/_MEI" not in exe_str
and os.access(exe_dir, os.W_OK)
):
return exe_dir return exe_dir
fallback_dir = Path.home() / ".local" / "share" / "TheGothCardgameCollection" return DbLocator._default_installed_data_dir()
fallback_dir.mkdir(parents=True, exist_ok=True)
return fallback_dir
return Path(__file__).resolve().parent.parent return Path(__file__).resolve().parent.parent
@ -144,7 +149,9 @@ class Database:
if not candidate_file.is_file(): if not candidate_file.is_file():
return False return False
try: try:
with sqlite3.connect(f"{candidate_file.resolve().as_uri()}?mode=ro", uri=True) as test_c: # Kein ?mode=ro erzwingen, da SQLite bei offenen -wal Dateien sonst unter Linux
# mangels Schreibrecht fuer -shm mit OperationalError abbricht!
with sqlite3.connect(str(candidate_file.resolve())) as test_c:
res = test_c.execute("PRAGMA integrity_check;").fetchone() res = test_c.execute("PRAGMA integrity_check;").fetchone()
if not res or str(res[0]).lower() != "ok": if not res or str(res[0]).lower() != "ok":
return False return False
@ -190,15 +197,15 @@ class Database:
return False, "invalid_file" return False, "invalid_file"
prev_path = cls._active_user_db_path.resolve() prev_path = cls._active_user_db_path.resolve()
if cand == prev_path and cls._connection is not None: # Immer Verbindung sauber schließen & frisch öffnen (auch wenn cand == prev_path),
cls._persist_self_location_in_db() # damit extern hineinkopierte Dateien garantiert neu eingelesen werden!
return True, str(cand)
cls.close() cls.close()
try: try:
cls._set_active_path_vars(cand) cls._set_active_path_vars(cand)
cls.init_db() cls.init_db()
cls._persist_self_location_in_db(previous_path=prev_path) cls._persist_self_location_in_db(
previous_path=prev_path if cand != prev_path else None
)
return True, str(cand) return True, str(cand)
except Exception as exc: except Exception as exc:
cls.close() cls.close()

View File

@ -4,6 +4,7 @@ from __future__ import annotations
import json import json
import os import os
import sqlite3
import sys import sys
from pathlib import Path from pathlib import Path
@ -18,7 +19,6 @@ class DbLocator:
""" """
Speichert außerhalb des Installationsordners (im OS-Nutzerprofil), wo die aktive Speichert außerhalb des Installationsordners (im OS-Nutzerprofil), wo die aktive
user_data.db liegt und welche Online-Serveradresse zuletzt verwendet wurde. user_data.db liegt und welche Online-Serveradresse zuletzt verwendet wurde.
Dadurch bleiben Updates & spätere Installer komplett unabhängig vom Programmordner.
""" """
@staticmethod @staticmethod
@ -63,33 +63,48 @@ class DbLocator:
except Exception: except Exception:
pass pass
@staticmethod
def _is_volatile_tmp_path(p: Path) -> bool:
s = str(p).replace("\\", "/")
return s == "/tmp" or s.startswith("/tmp/") or "/_MEI" in s
@staticmethod
def _db_has_profiles(db_file: Path) -> bool:
if not db_file.is_file():
return False
try:
with sqlite3.connect(str(db_file)) as c:
row = c.execute("SELECT COUNT(*) FROM profiles;").fetchone()
return bool(row and int(row[0]) > 0)
except Exception:
return False
@classmethod @classmethod
def resolve_initial_db_path(cls, default_fallback_dir: Path) -> Path: def resolve_initial_db_path(cls, default_fallback_dir: Path) -> Path:
"""
Ermittelt beim App-Start den aktiven Pfad zur user_data.db:
1. Gespeicherter Pfad aus db_locator.json (falls Verzeichnis erreichbar/beschreibbar).
2. Bestehende user_data.db im bisherigen Standardordner (Abwärtskompatibilität).
3. Sonst Standard-Nutzerdatenordner (für das Erst-Setup).
"""
cfg = cls.load_config() cfg = cls.load_config()
saved_raw = str(cfg.get("user_db_path", "")).strip() saved_raw = str(cfg.get("user_db_path", "")).strip()
if saved_raw: if saved_raw:
cand = Path(saved_raw).expanduser() cand = Path(saved_raw).expanduser()
try: try:
if cand.is_file(): resolved = cand.resolve()
return cand.resolve() # Leere /tmp-Datenbank aus früherem PyInstaller-Lauf ignorieren!
cand.parent.mkdir(parents=True, exist_ok=True) if cls._is_volatile_tmp_path(resolved) and not cls._db_has_profiles(resolved):
if os.access(cand.parent, os.W_OK): pass
return cand.resolve() elif resolved.is_file():
return resolved
elif not cls._is_volatile_tmp_path(resolved):
resolved.parent.mkdir(parents=True, exist_ok=True)
if os.access(resolved.parent, os.W_OK):
return resolved
except Exception: except Exception:
pass pass
legacy_file = (default_fallback_dir / USER_DB_FILENAME).resolve() legacy_file = (default_fallback_dir / USER_DB_FILENAME).resolve()
if legacy_file.is_file(): if not cls._is_volatile_tmp_path(legacy_file) and legacy_file.is_file():
cls.remember_db_path(legacy_file) cls.remember_db_path(legacy_file)
return legacy_file return legacy_file
if getattr(sys, "frozen", False): if getattr(sys, "frozen", False) or cls._is_volatile_tmp_path(legacy_file):
os_data_dir = cls._default_installed_data_dir() os_data_dir = cls._default_installed_data_dir()
return (os_data_dir / USER_DB_FILENAME).resolve() return (os_data_dir / USER_DB_FILENAME).resolve()

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# models/resource_manager.py
from pathlib import Path from pathlib import Path
from resources.code_res.game_constants import ( from resources.code_res.game_constants import (
CARD_BACK_PATTERN, CARD_BACK_PATTERN,
@ -26,10 +27,18 @@ class ResourceManager:
def active_cards_dir(self) -> Path: def active_cards_dir(self) -> Path:
return self.cards_base_dir / self.card_theme return self.cards_base_dir / self.card_theme
def get_card_path(self, filename: str) -> Path: def get_card_path(self, filename: str, theme: str | None = None) -> Path:
return self.active_cards_dir / filename folder = self.cards_base_dir / (theme or self.card_theme)
return folder / filename
def get_card_back_path(self, color: str = "Black") -> Path: def get_card_back_path(self, color: str = "Black", theme: str | None = None) -> Path:
folder = self.cards_base_dir / (theme or self.card_theme)
themed_back = folder / CARD_BACK_PATTERN.format(color=color)
if themed_back.is_file():
return themed_back
generic_back = folder / "card_back.png"
if generic_back.is_file():
return generic_back
return self.active_cards_dir / CARD_BACK_PATTERN.format(color=color) return self.active_cards_dir / CARD_BACK_PATTERN.format(color=color)
def get_ui_image_path(self, key_or_filename: str) -> Path: def get_ui_image_path(self, key_or_filename: str) -> Path:

View File

@ -119,6 +119,9 @@ GAME_ICON_MAP = {
"solitaire/tripeaks": "tripeaks_icon.ico", "solitaire/tripeaks": "tripeaks_icon.ico",
"romme": "romme_icon.ico", "romme": "romme_icon.ico",
"party/romme": "romme_icon.ico", "party/romme": "romme_icon.ico",
"party/zehner_raus": "10er_raus_icon.ico",
"party/schafkopfen": "schafkopfen_icon.ico",
"party/watten": "watten_icon.ico",
} }
FONTS_REL_DIR = "resources/fonts" FONTS_REL_DIR = "resources/fonts"
@ -152,6 +155,9 @@ GAME_FOLDERS = (
"solitaire/freecell", "solitaire/freecell",
"solitaire/klondike", "solitaire/klondike",
"solitaire/spider_solitaire", "solitaire/spider_solitaire",
"solitaire/pyramid",
"solitaire/tripeaks",
"party/zehner_raus",
) )
FOLDER_CATEGORY_MAP = { FOLDER_CATEGORY_MAP = {
@ -160,6 +166,9 @@ FOLDER_CATEGORY_MAP = {
"solitaire/freecell": CAT_SOLO, "solitaire/freecell": CAT_SOLO,
"solitaire/klondike": CAT_SOLO, "solitaire/klondike": CAT_SOLO,
"solitaire/spider_solitaire": CAT_SOLO, "solitaire/spider_solitaire": CAT_SOLO,
"solitaire/pyramid": CAT_SOLO,
"solitaire/tripeaks": CAT_SOLO,
"party/zehner_raus": CAT_PARTY_OFFLINE,
} }
# --- Statistik-Kategorien & Spiel-Zuordnung (keine "Gesamt"-Statistik!) --- # --- Statistik-Kategorien & Spiel-Zuordnung (keine "Gesamt"-Statistik!) ---
@ -181,6 +190,9 @@ STAT_GAME_GROUPS = (
("solitaire/klondike", "game_title_klondike"), ("solitaire/klondike", "game_title_klondike"),
("solitaire/freecell", "game_title_freecell"), ("solitaire/freecell", "game_title_freecell"),
("solitaire/spider_solitaire", "game_title_spider_solitaire"), ("solitaire/spider_solitaire", "game_title_spider_solitaire"),
("solitaire/pyramid", "game_title_pyramid"),
("solitaire/tripeaks", "game_title_tripeaks"),
("party/zehner_raus", "game_title_zehner_raus"),
) )
STAT_FOLDER_CATEGORY_MAP = { STAT_FOLDER_CATEGORY_MAP = {
@ -191,9 +203,10 @@ STAT_FOLDER_CATEGORY_MAP = {
"solitaire/spider_solitaire": STAT_CAT_SOLITAIRE, "solitaire/spider_solitaire": STAT_CAT_SOLITAIRE,
"solitaire/pyramid": STAT_CAT_SOLITAIRE, "solitaire/pyramid": STAT_CAT_SOLITAIRE,
"solitaire/tripeaks": STAT_CAT_SOLITAIRE, "solitaire/tripeaks": STAT_CAT_SOLITAIRE,
"party/zehner_raus": STAT_CAT_BAVARIAN,
} }
# --- Karten-Definitionen --- # --- Karten-Definitionen (Französisches Blatt) ---
SUITS = ("C", "D", "H", "S") SUITS = ("C", "D", "H", "S")
RED_SUITS = ("D", "H") RED_SUITS = ("D", "H")
RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A") RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")
@ -218,6 +231,11 @@ JOKER_FILES = {
"2": "Joker2.png", "2": "Joker2.png",
} }
# --- Bayerisches Blatt (36 Karten: Eichel, Blatt/Gras, Herz, Schellen) ---
BAVARIAN_CARD_THEME = "bavarian"
BAVARIAN_SUITS = ("E", "B", "H", "S")
BAVARIAN_RANKS = ("6", "7", "8", "9", "10", "U", "O", "K", "A")
# --- Audio & Sound-Zuordnung --- # --- Audio & Sound-Zuordnung ---
MENU_MUSIC_FILE = "Beyond_The_Iron_Gate.mp3" MENU_MUSIC_FILE = "Beyond_The_Iron_Gate.mp3"
INGAME_MUSIC_FILE = "The_Midnight_Hand.mp3" INGAME_MUSIC_FILE = "The_Midnight_Hand.mp3"
@ -248,6 +266,7 @@ DIVINE_AVG_GAMES_MULT = 10
DEVILS_DEAL_MIN_RANK_DE = "Stütze" DEVILS_DEAL_MIN_RANK_DE = "Stütze"
DEVILS_DEAL_GOLD_REWARD = 10 DEVILS_DEAL_GOLD_REWARD = 10
# Solitaire (mit Bestzeit & Durchschnittszeit)
STAT_FIELD_KEYS = ( STAT_FIELD_KEYS = (
("played", "stat_played"), ("played", "stat_played"),
("won", "stat_won"), ("won", "stat_won"),
@ -259,6 +278,16 @@ STAT_FIELD_KEYS = (
("avg_time", "stat_avg_time"), ("avg_time", "stat_avg_time"),
) )
# Glücks-, Bayerische & Gesellschaftsspiele (ohne Zeit-Statistiken)
STAT_FIELD_KEYS_NO_TIME = (
("played", "stat_played"),
("won", "stat_won"),
("lost", "stat_lost"),
("win_pct", "stat_win_pct"),
("current_streak", "stat_current_streak"),
("longest_streak", "stat_longest_streak"),
)
# --- Bots (0..5 Offline-Stufen, 6 = Gottheit / Online-Standard!) --- # --- Bots (0..5 Offline-Stufen, 6 = Gottheit / Online-Standard!) ---
BOT_DEITY_LEVEL = 6 BOT_DEITY_LEVEL = 6
BOT_LEVEL_COUNT = 7 BOT_LEVEL_COUNT = 7
@ -318,6 +347,17 @@ PK_VARIANTS = {
}, },
} }
# --- 10er raus (Pflicht: 4 Spieler = Du + 3 Bots) ---
ZR_NUM_PLAYERS = 4
ZR_BOT_COUNT = 3
ZR_BOT_TURN_DELAY_MS = 650
ZR_VARIANTS = {
"zehner_raus_std": {
"xp_mult": 1.15,
},
}
# --- Solitaire & Klondike --- # --- Solitaire & Klondike ---
SOLO_FORFEIT_XP_RATIO = 0.40 SOLO_FORFEIT_XP_RATIO = 0.40
@ -371,6 +411,36 @@ SPIDER_VARIANTS = {
}, },
} }
# --- Pyramid Solitaire (28er Pyramide + offener Talon & Waste, Summe = 13) ---
PYRAMID_REDEALS_BY_DIFF = {
0: 3, # Leicht: 3 Talon-Neudurchläufe
1: 2, # Normal: 2 Talon-Neudurchläufe
2: 1, # Schwer: 1 Talon-Neudurchlauf
3: 0, # Gottheit: 0 Neudurchläufe (1 einziger Durchgang!)
}
PYRAMID_VARIANTS = {
"pyramid_std": {
"xp_mult": 1.25,
"back_color": "Black",
},
}
# --- TriPeaks Solitaire (28er Drei-Gipfel + ±1 Wrap-Around Ass<->König) ---
TRIPEAKS_REDEALS_BY_DIFF = {
0: 2, # Leicht: 2 Talon-Neudurchläufe
1: 1, # Normal: 1 Talon-Neudurchlauf
2: 0, # Schwer: 0 Neudurchläufe (1 einziger Durchgang!)
3: 0, # Gottheit: 0 Neudurchläufe + enge Ketten & hohe Verzahnung
}
TRIPEAKS_VARIANTS = {
"tripeaks_std": {
"xp_mult": 1.20,
"back_color": "Black",
},
}
# --- UI Geometrie --- # --- UI Geometrie ---
DEFAULT_WINDOW_GEOM = "1150x800" DEFAULT_WINDOW_GEOM = "1150x800"
MIN_WINDOW_SIZE = (980, 700) MIN_WINDOW_SIZE = (980, 700)

Binary file not shown.

View File

@ -0,0 +1,81 @@
-- 08_zehner_raus.sql
-- 10er raus Varianten & Übersetzungen (DE/EN)
-- Spielvarianten-Registrierung
INSERT OR REPLACE INTO game_variants (id, folder_path, game_name, variant_key, display_name) VALUES
(601, 'party/zehner_raus', '10er raus', 'zehner_raus_std', '10er raus (Bayerisches Blatt)');
-- =========================================================================
-- 10ER RAUS (Bayerisches Blatt - 36 Karten, 4 Spieler)
-- =========================================================================
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
-- Spieltitel & Hauptmenü
('game_title_zehner_raus', 'DE', '10er raus'),
('game_title_zehner_raus', 'EN', 'Tens Out (10er raus)'),
('variant_zehner_raus_std', 'DE', 'Klassisch (36 Karten - 4 Spieler)'),
('variant_zehner_raus_std', 'EN', 'Classic (36 Cards - 4 Players)'),
-- Vorauswahl-Menü
('zr_menu_topbar', 'DE', '10er raus - Tischrunde vorbereiten'),
('zr_menu_topbar', 'EN', 'Tens Out - Table Setup'),
('zr_menu_subtitle', 'DE', 'Bayerisches Anlegespiel zu viert (36 Karten): Eröffne mit 10ern und lege nach oben bis zum Ass oder nach unten bis zur 6 an. Wer zuerst alle Karten ablegt, gewinnt!'),
('zr_menu_subtitle', 'EN', 'Bavarian 4-player shedding game (36 cards): Lead with 10s and build up to Ace or down to 6. First player to empty their hand wins!'),
('zr_rules_sec_title', 'DE', '1. Spielmodus & Regeln'),
('zr_rules_sec_title', 'EN', '1. Game Mode & Rules'),
('zr_bots_sec_title', 'DE', '2. Deine 3 Mitspieler am Tisch (Pflicht)'),
('zr_bots_sec_title', 'EN', '2. Your 3 Table Opponents (Mandatory)'),
('zr_rule_summary', 'DE', 'Pflichtrunde mit 4 Spielern (je 9 Karten) | Zugzwang bei passender Karte | Kein Gold-Einsatz'),
('zr_rule_summary', 'EN', 'Mandatory 4-player table (9 cards each) | Must play if able | No gold stakes'),
('zr_seat_lbl', 'DE', 'Platz {0}:'),
('zr_seat_lbl', 'EN', 'Seat {0}:'),
('zr_start_btn', 'DE', 'Runde starten'),
('zr_start_btn', 'EN', 'Start Round'),
-- Bayerische Farben
('bav_suit_E', 'DE', 'Eichel'),
('bav_suit_E', 'EN', 'Acorns (Eichel)'),
('bav_suit_B', 'DE', 'Blatt'),
('bav_suit_B', 'EN', 'Leaves (Blatt)'),
('bav_suit_H', 'DE', 'Herz'),
('bav_suit_H', 'EN', 'Hearts (Herz)'),
('bav_suit_S', 'DE', 'Schellen'),
('bav_suit_S', 'EN', 'Bells (Schellen)'),
-- Tisch, HUD & Aktionen
('zr_hud_round_info', 'DE', 'Am Zug: {0}|~Deine Hand: {1} Karten|~Züge: {2}'),
('zr_hud_round_info', 'EN', 'Turn: {0}|~Your Hand: {1} cards|~Turns: {2}'),
('zr_status_your_turn_play', 'DE', 'Du bist am Zug ({0} passende Karte(n) - Klicke eine leuchtende Karte an)'),
('zr_status_your_turn_play', 'EN', 'Your turn ({0} playable card(s) - click a highlighted card)'),
('zr_status_your_turn_pass', 'DE', 'Keine passende Karte auf der Hand - du musst weitergeben!'),
('zr_status_your_turn_pass', 'EN', 'No playable card in hand - you must pass!'),
('zr_btn_pass', 'DE', 'Weiter (Keine passt)'),
('zr_btn_pass', 'EN', 'Pass (No match)'),
('zr_tip_pass', 'DE', 'Nur verfügbar, wenn keine einzige deiner Handkarten angelegt werden kann.'),
('zr_tip_pass', 'EN', 'Only available when none of your hand cards can be played.'),
('zr_bot_cards_left', 'DE', '{0} Karten übrig'),
('zr_bot_cards_left', 'EN', '{0} cards left'),
('zr_bot_one_card_left', 'DE', 'Letzte Karte!'),
('zr_bot_one_card_left', 'EN', 'Last card!'),
('zr_act_played', 'DE', 'Legt {0} {1}'),
('zr_act_played', 'EN', 'Plays {0} {1}'),
('zr_act_passed', 'DE', 'Schiebt weiter'),
('zr_act_passed', 'EN', 'Passes'),
('zr_lane_waiting_10', 'DE', '10 fehlt'),
('zr_lane_waiting_10', 'EN', 'Need 10'),
('zr_lane_complete', 'DE', 'Komplett (6 - A)'),
('zr_lane_complete', 'EN', 'Complete (6 - A)'),
('zr_player_hand_lbl', 'DE', 'Deine Hand ({0} Karten) - Leuchtende Karten können angelegt werden'),
('zr_player_hand_lbl', 'EN', 'Your Hand ({0} cards) - Highlighted cards can be played'),
-- Ergebnis-Modal
('zr_popup_you_won', 'DE', 'Sieg! Du hast zuerst alle Karten abgelegt!'),
('zr_popup_you_won', 'EN', 'Victory! You emptied your hand first!'),
('zr_popup_bot_won', 'DE', 'Niederlage - {0} war zuerst fertig!'),
('zr_popup_bot_won', 'EN', 'Defeat - {0} emptied their hand first!'),
('zr_popup_remaining_hdr', 'DE', 'Verbliebene Handkarten am Rundenende'),
('zr_popup_remaining_hdr', 'EN', 'Remaining Hand Cards at Round End'),
('zr_popup_cards_zero', 'DE', '0 Karten (Sieger)'),
('zr_popup_cards_zero', 'EN', '0 cards (Winner)'),
('zr_popup_cards_rem', 'DE', '{0} Restkarten'),
('zr_popup_cards_rem', 'EN', '{0} cards left');

View File

@ -0,0 +1,33 @@
-- 09_pyramid.sql
-- Pyramid Solitaire Varianten & Übersetzungen (DE/EN)
INSERT OR REPLACE INTO game_variants (id, folder_path, game_name, variant_key, display_name) VALUES
(504, 'solitaire/pyramid', 'Pyramid Solitaire', 'pyramid_std', 'Pyramid - Classic 13');
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('game_title_pyramid', 'DE', 'Pyramid'),
('game_title_pyramid', 'EN', 'Pyramid'),
('variant_pyramid_std', 'DE', 'Klassisch (Summe 13)'),
('variant_pyramid_std', 'EN', 'Classic (Sum to 13)'),
('py_menu_topbar', 'DE', 'Pyramid Solitaire - Modus & Schwierigkeit'),
('py_menu_topbar', 'EN', 'Pyramid Solitaire - Mode & Difficulty'),
('py_menu_subtitle', 'DE', 'Räume alle 28 Karten der 7-stufigen Pyramide ab: Kombiniere freie Kartenpaare mit Summe 13 (Könige zählen 13 und werden einzeln abgelegt) - jedes Deck ist vorab auf Lösbarkeit geprüft!'),
('py_menu_subtitle', 'EN', 'Clear all 28 cards of the 7-tier pyramid: Pair exposed cards summing to 13 (Kings equal 13 and clear solo) - every deal is mathematically verified solvable!'),
('py_variant_info_lbl', 'DE', 'Spielvariante:'),
('py_variant_info_lbl', 'EN', 'Game Variant:'),
('py_desc_pyramid_std', 'DE', 'Offener Talon & Ablage kombinierbar | Durchläufe je Stufe: 3 / 2 / 1 / 0 | Basis-XP: x1.25'),
('py_desc_pyramid_std', 'EN', 'Open Stock & Waste pairable | Redeals by tier: 3 / 2 / 1 / 0 | Base XP: x1.25'),
('py_controls_hint', 'DE', 'Maus: 2 freie Karten (auch Talon + Ablage!) bis Summe 13 anklicken oder ziehen | Könige (13): Einzelklick | Button „Nächste Karte“ blättert weiter'),
('py_controls_hint', 'EN', 'Mouse: Click or drag 2 exposed cards (including Stock + Waste!) summing to 13 | Kings (13): Single click | "Next Card" button advances stock'),
('py_hud_extra', 'DE', ' | Pyramide: {0}/28 | Durchläufe: {1}/{2}'),
('py_hud_extra', 'EN', ' | Pyramid: {0}/28 | Redeals: {1}/{2}'),
('py_lbl_stock', 'DE', 'Stapel ({0})'),
('py_lbl_stock', 'EN', 'Stock ({0})'),
('py_lbl_waste', 'DE', 'Ablage ({0})'),
('py_lbl_waste', 'EN', 'Waste ({0})'),
('py_btn_next_card', 'DE', 'Nächste Karte ({0})'),
('py_btn_next_card', 'EN', 'Next Card ({0})'),
('py_btn_redeal', 'DE', 'Neu mischen ({0})'),
('py_btn_redeal', 'EN', 'Recycle ({0})'),
('py_sum_mismatch_msg', 'DE', '{0} ({1}) + {2} ({3}) = {4} (benötigt 13!)'),
('py_sum_mismatch_msg', 'EN', '{0} ({1}) + {2} ({3}) = {4} (must equal 13!)');

View File

@ -0,0 +1,31 @@
-- 10_tripeaks.sql
-- TriPeaks Solitaire Varianten & Übersetzungen (DE/EN)
INSERT OR REPLACE INTO game_variants (id, folder_path, game_name, variant_key, display_name) VALUES
(505, 'solitaire/tripeaks', 'TriPeaks Solitaire', 'tripeaks_std', 'TriPeaks - Classic Wrap');
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('game_title_tripeaks', 'DE', 'TriPeaks'),
('game_title_tripeaks', 'EN', 'TriPeaks'),
('variant_tripeaks_std', 'DE', 'Klassisch (±1 mit Ass/König)'),
('variant_tripeaks_std', 'EN', 'Classic (±1 Wrap A/K)'),
('tp_menu_topbar', 'DE', 'TriPeaks Solitaire - Modus & Schwierigkeit'),
('tp_menu_topbar', 'EN', 'TriPeaks Solitaire - Mode & Difficulty'),
('tp_menu_subtitle', 'DE', 'Erklimme alle drei Gipfel (28 Karten): Lege freie Karten ab, die um 1 höher oder niedriger als die Ablagekarte sind (Ass & König schließen den Kreis) - jedes Deck ist vorab auf Lösbarkeit geprüft!'),
('tp_menu_subtitle', 'EN', 'Conquer all three peaks (28 cards): Play exposed cards 1 rank higher or lower than the waste card (Ace & King wrap around) - every deal is mathematically verified solvable!'),
('tp_variant_info_lbl', 'DE', 'Spielvariante:'),
('tp_variant_info_lbl', 'EN', 'Game Variant:'),
('tp_desc_tripeaks_std', 'DE', '±1 Ketten-Kombo (inkl. Ass <-> König) | Durchläufe je Stufe: 2 / 1 / 0 / 0 | Basis-XP: x1.20'),
('tp_desc_tripeaks_std', 'EN', '±1 Streak Combo (incl. Ace <-> King) | Redeals by tier: 2 / 1 / 0 / 0 | Base XP: x1.20'),
('tp_controls_hint', 'DE', 'Maus: Freie Karte (±1 zur Ablage) anklicken oder ziehen | Klick auf Stapel / Leertaste: Neue Karte aufdecken | Lange Ketten bringen Kombo-Punkte!'),
('tp_controls_hint', 'EN', 'Mouse: Click or drag exposed card (±1 to waste) | Click Stock / Space: Draw next card | Long chains award streak bonus points!'),
('tp_hud_extra', 'DE', ' | Serie: {0}x | Gipfel: {1}/3 | Durchläufe: {2}/{3}'),
('tp_hud_extra', 'EN', ' | Streak: {0}x | Peaks: {1}/3 | Redeals: {2}/{3}'),
('tp_lbl_draw', 'DE', 'Stapel ({0})'),
('tp_lbl_draw', 'EN', 'Stock ({0})'),
('tp_lbl_redeal', 'DE', 'Neu mischen ({0})'),
('tp_lbl_redeal', 'EN', 'Recycle ({0})'),
('tp_lbl_waste', 'DE', 'Ablage (±1)'),
('tp_lbl_waste', 'EN', 'Waste (±1)'),
('tp_adj_mismatch_msg', 'DE', '{0} passt nicht auf {1} (nur ±1 erlaubt, Ass <-> König schließt den Kreis!)'),
('tp_adj_mismatch_msg', 'EN', '{0} does not match {1} (must be ±1; Ace <-> King wraps around!)');

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 559 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 527 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 546 KiB

After

Width:  |  Height:  |  Size: 553 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 745 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 467 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 726 KiB

View File

@ -338,20 +338,34 @@ class AssetManager:
self._raw_card_cache[key] = pil self._raw_card_cache[key] = pil
return self._raw_card_cache[key] return self._raw_card_cache[key]
def get_card_photo(self, card_filename: str, size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: def get_card_photo(
key = ("card", self.res.card_theme, card_filename, size) self, card_filename: str, size=PLAYING_CARD_SIZE, theme: str | None = None
) -> ImageTk.PhotoImage | None:
eff_theme = theme or self.res.card_theme
key = ("card", eff_theme, card_filename, size)
if key not in self._tk_cache: if key not in self._tk_cache:
pil = self._get_raw_card_pil(self.res.get_card_path(card_filename)) pil = self._get_raw_card_pil(
self.res.get_card_path(card_filename, theme=eff_theme)
)
if pil: if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) self._tk_cache[key] = ImageTk.PhotoImage(
pil.resize(size, Image.Resampling.BILINEAR)
)
return self._tk_cache.get(key) return self._tk_cache.get(key)
def get_card_back_photo(self, color: str = "Black", size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: def get_card_back_photo(
key = ("card_back", self.res.card_theme, color, size) self, color: str = "Black", size=PLAYING_CARD_SIZE, theme: str | None = None
) -> ImageTk.PhotoImage | None:
eff_theme = theme or self.res.card_theme
key = ("card_back", eff_theme, color, size)
if key not in self._tk_cache: if key not in self._tk_cache:
pil = self._get_raw_card_pil(self.res.get_card_back_path(color)) pil = self._get_raw_card_pil(
self.res.get_card_back_path(color, theme=eff_theme)
)
if pil: if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) self._tk_cache[key] = ImageTk.PhotoImage(
pil.resize(size, Image.Resampling.BILINEAR)
)
return self._tk_cache.get(key) return self._tk_cache.get(key)
def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]) -> ImageTk.PhotoImage | None: def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]) -> ImageTk.PhotoImage | None:

View File

@ -169,10 +169,37 @@ class LoginView:
chosen = filedialog.askdirectory( chosen = filedialog.askdirectory(
parent=self.root, initialdir=str(self._first_db_dir), title=t("db_move_dialog_title") parent=self.root, initialdir=str(self._first_db_dir), title=t("db_move_dialog_title")
) )
if chosen: if not chosen or isinstance(chosen, tuple):
self._first_db_dir = Path(chosen).resolve() return
picked_dir = Path(str(chosen)).expanduser().resolve()
existing_candidate = picked_dir / USER_DB_FILENAME
# Liegt im gewählten Ordner bereits eine gültige user_data.db -> sofort laden!
if existing_candidate.is_file():
ok, msg = self.ctrl.load_user_data_from_file(str(existing_candidate))
if ok:
return
if self._cv and self._cv.winfo_exists(): if self._cv and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height())) self._status_msg, self._status_is_error = msg, True
self._first_db_dir = picked_dir
if self._cv and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
def _load_existing_db_from_login(self):
start_dir = self._first_db_dir if self._first_db_dir.is_dir() else Database.get_user_db_dir()
picked = filedialog.askopenfilename(
parent=self.root,
initialdir=str(start_dir),
title=t("db_load_dialog_title"),
filetypes=[("SQLite Database", "*.db *.sqlite *.sqlite3"), ("All Files", "*")],
)
if not picked or isinstance(picked, tuple):
return
ok, msg = self.ctrl.load_user_data_from_file(str(picked))
if not ok and self._cv and self._cv.winfo_exists():
self._status_msg, self._status_is_error = msg, True
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
def _load_existing_db_from_login(self): def _load_existing_db_from_login(self):
picked = filedialog.askopenfilename( picked = filedialog.askopenfilename(

View File

@ -15,6 +15,7 @@ from resources.code_res.game_constants import (
FONT_SIZE_HEADING, FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN, FONT_SIZE_SMALL_MIN,
STAT_FIELD_KEYS, STAT_FIELD_KEYS,
STAT_FIELD_KEYS_NO_TIME,
SUBTLE_BORDER, SUBTLE_BORDER,
UI_ACCENT_AMETHYST, UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD, UI_ACCENT_GOLD,
@ -23,7 +24,7 @@ from resources.code_res.i18n import t
class StatsDetailRenderer: class StatsDetailRenderer:
"""Rendert die Detail-Statistikansicht eines einzelnen Kartenspiels.""" """Rendert die Detail-Statistikansicht (Solitaire: 4x2 mit Zeit | Glück/Bayerisch/Party: 3x2 ohne Zeit)."""
@staticmethod @staticmethod
def draw_detail( def draw_detail(
@ -41,6 +42,7 @@ class StatsDetailRenderer:
photo_refs: list, photo_refs: list,
w: int, w: int,
h: int, h: int,
show_time: bool = False,
) -> None: ) -> None:
compact = (h < 780) compact = (h < 780)
pad_x = max(72, int(w * 0.08)) pad_x = max(72, int(w * 0.08))
@ -117,7 +119,7 @@ class StatsDetailRenderer:
cur_y += hdr_h + (14 if compact else 18) cur_y += hdr_h + (14 if compact else 18)
# 2. 8-Kacheln-Statistik-Board # 2. Statistik-Board (Solitaire: 4x2 mit Zeit | alle anderen: 3x2 ohne Zeit)
bottom_safe = max(46, int(h * 0.075)) bottom_safe = max(46, int(h * 0.075))
board_h = max(248, min(360, h - cur_y - bottom_safe)) board_h = max(248, min(360, h - cur_y - bottom_safe))
board_cy = cur_y + board_h // 2 board_cy = cur_y + board_h // 2
@ -137,10 +139,12 @@ class StatsDetailRenderer:
photo_refs.append(sub_ph) photo_refs.append(sub_ph)
cv.create_image(left_x + 28, cur_y + 30, image=sub_ph, anchor="w", tags="fg") cv.create_image(left_x + 28, cur_y + 30, image=sub_ph, anchor="w", tags="fg")
active_fields = STAT_FIELD_KEYS if show_time else STAT_FIELD_KEYS_NO_TIME
cols = 4 if show_time else 3
rows = 2
grid_top = cur_y + 58 grid_top = cur_y + 58
grid_h = board_h - 78 grid_h = board_h - 78
cols, rows = 4, 2 gap_x, gap_y = (14 if show_time else 18), 12
gap_x, gap_y = 14, 12
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
cell_h = max(68, (grid_h - (rows - 1) * gap_y) // rows) cell_h = max(68, (grid_h - (rows - 1) * gap_y) // rows)
@ -148,7 +152,7 @@ class StatsDetailRenderer:
if cell_frame: if cell_frame:
photo_refs.append(cell_frame) photo_refs.append(cell_frame)
for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS): for idx, (field_key, label_i18n_key) in enumerate(active_fields):
r, c = divmod(idx, cols) r, c = divmod(idx, cols)
cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2 cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2
cy = grid_top + r * (cell_h + gap_y) + cell_h // 2 cy = grid_top + r * (cell_h + gap_y) + cell_h // 2

View File

@ -41,6 +41,10 @@ ENDPOINT_ALIASES: dict[str, str | None] = {
"solitaire/spider_solitaire": "solitaire/spider_solitaire", "solitaire/spider_solitaire": "solitaire/spider_solitaire",
"pyramid": "solitaire/pyramid", "pyramid": "solitaire/pyramid",
"solitaire/pyramid": "solitaire/pyramid", "solitaire/pyramid": "solitaire/pyramid",
"zehner_raus": "party/zehner_raus",
"party/zehner_raus": "party/zehner_raus",
"tripeaks": "solitaire/tripeaks",
"solitaire/tripeaks": "solitaire/tripeaks",
} }
@ -357,8 +361,10 @@ class UnifiedStatsView(tk.Canvas):
self._open_game_from_hub, self._photo_refs, w, h, self._open_game_from_hub, self._photo_refs, w, h,
) )
else: else:
show_time_fields = (self._active_folder or "").startswith("solitaire/")
StatsDetailRenderer.draw_detail( StatsDetailRenderer.draw_detail(
self, self.ctx.assets, self._game_title, self._rank_line, self._xp_ratio, self, self.ctx.assets, self._game_title, self._rank_line, self._xp_ratio,
self._board_heading, self._stats_data, self._back_btn, self._hub_or_settings_btn, self._board_heading, self._stats_data, self._back_btn, self._hub_or_settings_btn,
self._var_btns, self._acc_btns, self._photo_refs, w, h, self._var_btns, self._acc_btns, self._photo_refs, w, h,
show_time=show_time_fields,
) )