Compare commits
6 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
a81c8f02de | |
|
|
31b28652db | |
|
|
8acff1058a | |
|
|
c5e303db9f | |
|
|
9492b92e80 | |
|
|
42bf545b35 |
|
|
@ -0,0 +1,96 @@
|
|||
function DisplayTree {
|
||||
param (
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Path,
|
||||
[string]$Indent = "",
|
||||
[bool]$IsRoot = $false,
|
||||
[switch]$Essentials,
|
||||
[string[]]$ExcludeDirs = @(
|
||||
# Node / Build
|
||||
"node_modules", "build", "dist",
|
||||
# Git
|
||||
".git",
|
||||
# Python virtual envs, pip & package caches
|
||||
".env*", "env", "venv*", ".venv*",
|
||||
"__pycache__", "site-packages", "Lib", "Include", "Scripts",
|
||||
"*.egg-info", "*.dist-info", ".eggs", "wheels", "pip-wheel-metadata",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".nox"
|
||||
),
|
||||
[string[]]$ExcludeFiles = @(
|
||||
# Git files
|
||||
".gitignore", ".gitattributes", ".gitmodules", ".gitkeep",
|
||||
# Python init & compiled bytecode
|
||||
"__init__.py", "*.pyc", "*.pyo", "*.pyd"
|
||||
)
|
||||
)
|
||||
|
||||
# Apply extra exclusions once at the root level when --essentials is active
|
||||
if ($IsRoot -and $Essentials) {
|
||||
$ExcludeDirs += "build_scripts"
|
||||
$ExcludeFiles += @(
|
||||
# Readme files
|
||||
"readme*",
|
||||
# Image formats
|
||||
"*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp", "*.svg", "*.ico",
|
||||
"*.webp", "*.tiff", "*.tif", "*.heic", "*.avif", "*.raw", "*.psd",
|
||||
# Music / Audio formats
|
||||
"*.mp3", "*.wav", "*.flac", "*.aac", "*.ogg", "*.oga", "*.wma",
|
||||
"*.m4a", "*.opus", "*.aiff", "*.alac", "*.mid", "*.midi",
|
||||
# Fonts, Databases & PowerShell scripts
|
||||
"*.ttf", "*.db", "*.ps1"
|
||||
)
|
||||
}
|
||||
|
||||
$outputLines = New-Object System.Collections.Generic.List[string]
|
||||
|
||||
# Recurse into directories (skipping any match in $ExcludeDirs)
|
||||
Get-ChildItem -LiteralPath $Path -Directory -Force -ErrorAction SilentlyContinue | Where-Object {
|
||||
$itemName = $_.Name
|
||||
-not ($ExcludeDirs | Where-Object { $itemName -like $_ })
|
||||
} | ForEach-Object {
|
||||
$subLines = DisplayTree -Path $_.FullName -Indent " $Indent" -Essentials:$Essentials -ExcludeDirs $ExcludeDirs -ExcludeFiles $ExcludeFiles
|
||||
|
||||
# In --essentials mode, hide folders that have zero matching files/subfolders left
|
||||
if (-not $Essentials -or $subLines.Count -gt 0) {
|
||||
$outputLines.Add("$Indent|--- $($_.Name)")
|
||||
foreach ($line in $subLines) {
|
||||
$outputLines.Add($line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Collect files (skipping any match in $ExcludeFiles)
|
||||
Get-ChildItem -LiteralPath $Path -File -Force -ErrorAction SilentlyContinue | Where-Object {
|
||||
$itemName = $_.Name
|
||||
-not ($ExcludeFiles | Where-Object { $itemName -like $_ })
|
||||
} | ForEach-Object {
|
||||
$lineInfo = ""
|
||||
|
||||
if ($Essentials -and $_.Extension -eq ".py") {
|
||||
$rowCount = [System.IO.File]::ReadAllLines($_.FullName).Length
|
||||
$lineInfo = " ($rowCount lines)"
|
||||
}
|
||||
|
||||
$outputLines.Add("$Indent|--- $($_.Name)$lineInfo")
|
||||
}
|
||||
|
||||
# Print at root; return list on recursive calls
|
||||
if ($IsRoot) {
|
||||
$rootName = (Get-Item -LiteralPath $Path -Force).Name
|
||||
Write-Host $rootName
|
||||
foreach ($line in $outputLines) {
|
||||
Write-Host $line
|
||||
}
|
||||
} else {
|
||||
return ,$outputLines
|
||||
}
|
||||
}
|
||||
|
||||
# Parse CLI arguments passed to .\DisplayTree.ps1
|
||||
$useEssentials = ($args -contains "--essentials") -or ($args -contains "-essentials")
|
||||
$targetPath = ($args | Where-Object { $_ -notlike "-*" } | Select-Object -First 1)
|
||||
if (-not $targetPath) {
|
||||
$targetPath = ".\"
|
||||
}
|
||||
|
||||
DisplayTree -Path $targetPath -IsRoot $true -Essentials:$useEssentials
|
||||
|
|
@ -71,6 +71,12 @@ if "%DO_WIN%"=="0" if "%DO_UNIX%"=="0" if "%DO_OSX%"=="0" (
|
|||
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 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!)
|
||||
REM ----------------------------------------------------
|
||||
|
|
@ -136,82 +142,14 @@ REM ====================================================
|
|||
if "%DO_WIN%"=="1" (
|
||||
echo.
|
||||
echo ---^> [WIN] Baue Windows Single-File .exe...
|
||||
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 (
|
||||
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 exist "%PROJECT_ROOT%\dist\windows" rmdir /s /q "%PROJECT_ROOT%\dist\windows"
|
||||
call :BUILD_WIN_TARGET
|
||||
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 "WIN_OK=0"
|
||||
set "ANY_FAILED=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 ====================================================
|
||||
|
|
@ -220,7 +158,14 @@ REM ====================================================
|
|||
if "%DO_UNIX%"=="1" (
|
||||
echo.
|
||||
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
|
||||
if errorlevel 1 (
|
||||
set "UNIX_OK=0"
|
||||
set "ANY_FAILED=1"
|
||||
) else (
|
||||
set "UNIX_OK=1"
|
||||
)
|
||||
)
|
||||
|
||||
REM ====================================================
|
||||
|
|
@ -229,34 +174,47 @@ REM ====================================================
|
|||
if "%DO_OSX%"=="1" (
|
||||
echo.
|
||||
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
|
||||
if errorlevel 1 (
|
||||
set "OSX_OK=0"
|
||||
set "ANY_FAILED=1"
|
||||
) else (
|
||||
set "OSX_OK=1"
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ====================================================
|
||||
echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^):
|
||||
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
|
||||
) else (
|
||||
echo [WIN] FEHLGESCHLAGEN
|
||||
echo [WIN] FEHLGESCHLAGEN!
|
||||
)
|
||||
)
|
||||
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^)
|
||||
) else (
|
||||
echo [UNIX] FEHLGESCHLAGEN
|
||||
echo [UNIX] FEHLGESCHLAGEN! ^(VM "%UNIX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||
)
|
||||
)
|
||||
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^)
|
||||
) else (
|
||||
echo [OSX] FEHLGESCHLAGEN
|
||||
echo [OSX] FEHLGESCHLAGEN! ^(VM "%OSX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||
)
|
||||
)
|
||||
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
|
||||
endlocal
|
||||
exit /b 0
|
||||
|
|
@ -265,6 +223,84 @@ exit /b 0
|
|||
REM ====================================================
|
||||
REM HILFSROUTINEN
|
||||
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
|
||||
set "REBUILD_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" (
|
||||
set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py"
|
||||
)
|
||||
if not "!REBUILD_PY!"=="" 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"
|
||||
if not "!REBUILD_PY!"=="" (
|
||||
if exist "%PROJECT_ROOT%\build_scripts\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"
|
||||
) 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
|
||||
|
||||
|
|
@ -322,16 +365,25 @@ if "!VBOX_MANAGE!"=="" if exist "D:\Program Files\Oracle\VirtualBox\VBoxManage.e
|
|||
)
|
||||
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
|
||||
call :FIND_VBOX
|
||||
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
|
||||
)
|
||||
|
||||
"!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden!
|
||||
call :PRINT_AVAILABLE_VMS
|
||||
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"
|
||||
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%" .
|
||||
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
|
||||
set "SCP_ERR=!ERRORLEVEL!"
|
||||
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...
|
||||
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 (
|
||||
echo [ERROR] Linux-Build in der VM fehlgeschlagen!
|
||||
|
|
@ -385,9 +441,7 @@ if errorlevel 1 (
|
|||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux"
|
||||
mkdir "%PROJECT_ROOT%\dist\linux"
|
||||
|
||||
mkdir "%PROJECT_ROOT%\dist\linux" 2>nul
|
||||
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"
|
||||
if errorlevel 1 (
|
||||
|
|
@ -395,6 +449,10 @@ if errorlevel 1 (
|
|||
exit /b 1
|
||||
)
|
||||
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" (
|
||||
echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter...
|
||||
|
|
@ -406,13 +464,14 @@ exit /b 0
|
|||
:RUN_OSX_VM_BUILD
|
||||
call :FIND_VBOX
|
||||
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
|
||||
)
|
||||
|
||||
"!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden!
|
||||
call :PRINT_AVAILABLE_VMS
|
||||
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"
|
||||
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%" .
|
||||
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
|
||||
set "SCP_OSX_ERR=!ERRORLEVEL!"
|
||||
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...
|
||||
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 (
|
||||
echo [ERROR] macOS-Build in der VM fehlgeschlagen!
|
||||
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos"
|
||||
mkdir "%PROJECT_ROOT%\dist\macos"
|
||||
|
||||
mkdir "%PROJECT_ROOT%\dist\macos" 2>nul
|
||||
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 (
|
||||
echo [ERROR] Download des macOS-Artefakts fehlgeschlagen!
|
||||
exit /b 1
|
||||
)
|
||||
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" (
|
||||
echo [OSX-VM] Fahre macOS-VM wieder sauber herunter...
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(
|
||||
filevers=(1, 0, 0, 0),
|
||||
prodvers=(1, 0, 0, 0),
|
||||
filevers=(0, 6, 0, 0),
|
||||
prodvers=(0, 6, 0, 0),
|
||||
mask=0x3f,
|
||||
flags=0x0,
|
||||
OS=0x40004,
|
||||
|
|
@ -16,12 +16,12 @@ VSVersionInfo(
|
|||
[
|
||||
StringStruct('CompanyName', 'Kuro'),
|
||||
StringStruct('FileDescription', 'The Goth Cardgame Collection'),
|
||||
StringStruct('FileVersion', '1.0.0.0'),
|
||||
StringStruct('FileVersion', '0.6.0.0'),
|
||||
StringStruct('InternalName', 'TheGothCardgameCollection'),
|
||||
StringStruct('LegalCopyright', 'Copyright (C) 2026 Kuro'),
|
||||
StringStruct('OriginalFilename', 'TheGothCardgameCollection.exe'),
|
||||
StringStruct('ProductName', 'The Goth Cardgame Collection'),
|
||||
StringStruct('ProductVersion', '1.0.0.0')
|
||||
StringStruct('ProductVersion', '0.6.0-beta')
|
||||
]
|
||||
)
|
||||
]),
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -2,17 +2,16 @@
|
|||
# controller/app_context.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.database import Database
|
||||
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
|
||||
from view.unified_stats_view import UnifiedStatsView
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.goth_topbar import GothTopbar, format_compact_user_badge
|
||||
from models.db.database import Database
|
||||
from view.stats.unified_stats_view import UnifiedStatsView
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.bars.goth_topbar import GothTopbar, format_compact_user_badge
|
||||
|
||||
__all__ = ["AppContext", "GothTopbar", "UnifiedStatsView", "format_compact_user_badge"]
|
||||
|
||||
|
||||
class AppContext:
|
||||
"""Schlanker Spiel-Kontext; Topbar und Statistik laufen zentral über eigene Widgets."""
|
||||
"""Schlanker Spiel-Kontext; Topbar, Einstellungen und Statistik laufen zentral."""
|
||||
|
||||
def __init__(self, controller, game_folder: str):
|
||||
self._ctrl = controller
|
||||
|
|
@ -39,11 +38,9 @@ class AppContext:
|
|||
|
||||
def open_settings(self, on_lang_refresh=None):
|
||||
GothDropdown.close_any_open_popup()
|
||||
AudioSettingsDialog.open(
|
||||
self.root,
|
||||
self.assets,
|
||||
self.sounds,
|
||||
on_toggle_lang=lambda: self.toggle_language(on_lang_refresh),
|
||||
self._ctrl.show_settings(
|
||||
in_game_overlay=True,
|
||||
on_ingame_lang_refresh=on_lang_refresh,
|
||||
)
|
||||
|
||||
def open_audio_settings(self):
|
||||
|
|
@ -54,7 +51,6 @@ class AppContext:
|
|||
endpoint = self.game_folder if game_endpoint is None else game_endpoint
|
||||
UnifiedStatsView.open(self, game_endpoint=endpoint, on_back=on_back)
|
||||
|
||||
# Alias für etwaige bestehende Aufrufe
|
||||
open_global_stats = open_stats
|
||||
|
||||
def toggle_language(self, refresh_callback=None):
|
||||
|
|
|
|||
|
|
@ -1,12 +1,19 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# controller/app_controller.py
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from controller.app_context import AppContext
|
||||
from controller.game_loader import GameLoader
|
||||
from models.database import Database
|
||||
from games.solitaire.base.session.solitaire_tap_prefs import invalidate_tap_prefs_cache
|
||||
from models.db.database import Database
|
||||
from models.db.db_locator import DbLocator
|
||||
from models.online_session import OnlineSessionClient
|
||||
from models.sound_manager import SoundManager
|
||||
import resources.code_res.i18n as i18n
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.buttons.image_button import set_button_hover_help_enabled
|
||||
|
||||
|
||||
class AppController:
|
||||
|
|
@ -17,16 +24,58 @@ class AppController:
|
|||
i18n.set_lang(Database.load_setting("language", "DE"))
|
||||
self.loader = GameLoader(root_dir)
|
||||
self.sounds = SoundManager(root_dir / "resources" / "sounds")
|
||||
self.active_profile = None
|
||||
self.online_session = OnlineSessionClient()
|
||||
self.is_online_mode: bool = False
|
||||
self.active_profile: dict | None = None
|
||||
self.view = None
|
||||
|
||||
def bind_view(self, view):
|
||||
self.view = view
|
||||
self.view._app_controller = self
|
||||
|
||||
def can_modify_user_db(self) -> bool:
|
||||
"""Sperrt das Laden/Umziehen der lokalen DB im Online-Modus oder während Devil's Deal."""
|
||||
if self.is_online_mode:
|
||||
return False
|
||||
if self.active_profile and self.has_active_devils_lock():
|
||||
return False
|
||||
return True
|
||||
|
||||
def _reload_runtime_preferences_from_db(self):
|
||||
"""Synchronisiert Sprache, Audio & Schalter-Settings nach einem Datenbank-Wechsel."""
|
||||
lang = Database.load_setting("language", "DE")
|
||||
i18n.set_lang(lang)
|
||||
invalidate_tap_prefs_cache()
|
||||
|
||||
hover_raw = Database.load_setting("ui_button_hover_help", "")
|
||||
if hover_raw != "":
|
||||
set_button_hover_help_enabled(
|
||||
str(hover_raw).strip().lower() in ("1", "true", "yes", "on"),
|
||||
persist=False,
|
||||
)
|
||||
|
||||
amb_raw = Database.load_setting("ambiance_volume", "")
|
||||
if amb_raw != "":
|
||||
try:
|
||||
self.sounds.set_ambiance_volume(float(amb_raw), persist=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sfx_raw = Database.load_setting("menu_volume", "")
|
||||
if sfx_raw != "":
|
||||
try:
|
||||
self.sounds.set_menu_volume(float(sfx_raw), persist=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if self.view is not None:
|
||||
self.view.title(t("app_title"))
|
||||
|
||||
def toggle_language(self, custom_refresh=None):
|
||||
new_lang = i18n.next_lang()
|
||||
Database.save_setting("language", new_lang)
|
||||
self.view.title(t("app_title"))
|
||||
if self.view is not None:
|
||||
self.view.title(t("app_title"))
|
||||
if custom_refresh is not None:
|
||||
custom_refresh()
|
||||
elif self.active_profile:
|
||||
|
|
@ -34,34 +83,134 @@ class AppController:
|
|||
else:
|
||||
self.start()
|
||||
|
||||
def start(self):
|
||||
def start(self, status_msg: str = "", is_error: bool = False, login_mode: str = "local"):
|
||||
self.sounds.play_menu_music()
|
||||
profiles = Database.get_profiles()
|
||||
last_prof = Database.load_setting("last_profile_name", "")
|
||||
self.view.show_login(profiles, preselect_name=last_prof)
|
||||
self.view.show_login(
|
||||
profiles,
|
||||
preselect_name=last_prof,
|
||||
status_msg=status_msg,
|
||||
is_error=is_error,
|
||||
login_mode=login_mode,
|
||||
)
|
||||
|
||||
def do_login(self, name: str):
|
||||
if not name:
|
||||
return
|
||||
self.online_session.disconnect()
|
||||
self.is_online_mode = False
|
||||
Database.save_setting("last_profile_name", name)
|
||||
self.active_profile = Database.get_or_create_profile(name)
|
||||
self.show_main_menu()
|
||||
|
||||
def do_create_profile(self, name: str):
|
||||
if not name:
|
||||
def do_create_profile(self, name: str, first_user_db_dir: str | None = None):
|
||||
clean_name = name.strip()
|
||||
if not clean_name:
|
||||
return
|
||||
Database.save_setting("last_profile_name", name)
|
||||
self.active_profile = Database.get_or_create_profile(name)
|
||||
self.online_session.disconnect()
|
||||
self.is_online_mode = False
|
||||
|
||||
if first_user_db_dir and len(Database.get_profiles()) == 0:
|
||||
try:
|
||||
Database.relocate_for_first_user(Path(first_user_db_dir))
|
||||
except Exception as exc:
|
||||
self.start(
|
||||
status_msg=t("db_err_move_failed", str(exc)),
|
||||
is_error=True,
|
||||
login_mode="local",
|
||||
)
|
||||
return
|
||||
|
||||
Database.save_setting("last_profile_name", clean_name)
|
||||
self.active_profile = Database.get_or_create_profile(clean_name)
|
||||
self.show_main_menu()
|
||||
|
||||
def do_online_login(
|
||||
self,
|
||||
addr_mode: str,
|
||||
raw_url: str,
|
||||
raw_ip: str,
|
||||
raw_port: str,
|
||||
username: str,
|
||||
password: str,
|
||||
) -> tuple[bool, str]:
|
||||
clean_user = username.strip()
|
||||
DbLocator.save_online_prefs(addr_mode, raw_url, raw_ip, raw_port, clean_user)
|
||||
|
||||
ok, err_msg = self.online_session.authenticate(
|
||||
addr_mode=addr_mode,
|
||||
raw_url=raw_url,
|
||||
raw_ip=raw_ip,
|
||||
raw_port=raw_port,
|
||||
username=clean_user,
|
||||
password=password,
|
||||
)
|
||||
if not ok:
|
||||
return False, err_msg
|
||||
|
||||
self.is_online_mode = True
|
||||
local_mirror = dict(Database.get_or_create_profile(clean_user))
|
||||
local_mirror["is_online"] = True
|
||||
local_mirror["online_endpoint"] = self.online_session.endpoint_label
|
||||
self.active_profile = local_mirror
|
||||
self.show_main_menu()
|
||||
return True, ""
|
||||
|
||||
def load_user_data_from_file(self, db_file_path: str) -> tuple[bool, str]:
|
||||
if not self.can_modify_user_db():
|
||||
return False, t("db_err_locked_devils")
|
||||
|
||||
ok, info = Database.switch_user_database(Path(db_file_path))
|
||||
if not ok:
|
||||
msg = t("db_err_invalid_file") if info == "invalid_file" else t("db_err_move_failed", info)
|
||||
return False, msg
|
||||
|
||||
self._reload_runtime_preferences_from_db()
|
||||
self.online_session.disconnect()
|
||||
self.is_online_mode = False
|
||||
self.active_profile = None
|
||||
|
||||
profiles = Database.get_profiles()
|
||||
last_prof = Database.load_setting("last_profile_name", "")
|
||||
ok_msg = t("db_load_ok", info)
|
||||
if self.view is not None:
|
||||
self.view.show_login(profiles, preselect_name=last_prof, status_msg=ok_msg, is_error=False)
|
||||
return True, ok_msg
|
||||
|
||||
def move_user_data_to_folder(self, target_dir_path: str) -> tuple[bool, str]:
|
||||
if not self.can_modify_user_db():
|
||||
return False, t("db_err_locked_devils")
|
||||
|
||||
ok, info = Database.move_user_database(Path(target_dir_path))
|
||||
if not ok:
|
||||
return False, t("db_err_move_failed", info)
|
||||
|
||||
if self.active_profile and not self.is_online_mode:
|
||||
refreshed = Database.get_profile_by_id(self.active_profile["id"])
|
||||
if refreshed:
|
||||
self.active_profile = refreshed
|
||||
return True, t("db_move_ok", info)
|
||||
|
||||
def logout_to_login(self):
|
||||
self.sounds.play_menu_music()
|
||||
last_prof = self.active_profile["name"] if self.active_profile else Database.load_setting("last_profile_name", "")
|
||||
last_prof = (
|
||||
self.active_profile["name"]
|
||||
if (self.active_profile and not self.is_online_mode)
|
||||
else Database.load_setting("last_profile_name", "")
|
||||
)
|
||||
was_online = self.is_online_mode
|
||||
self.online_session.disconnect()
|
||||
self.is_online_mode = False
|
||||
self.active_profile = None
|
||||
self.view.show_login(Database.get_profiles(), preselect_name=last_prof)
|
||||
self.view.show_login(
|
||||
Database.get_profiles(),
|
||||
preselect_name=last_prof,
|
||||
login_mode="online" if was_online else "local",
|
||||
)
|
||||
|
||||
def get_locked_devils_game_folder(self) -> str | None:
|
||||
if not self.active_profile:
|
||||
if not self.active_profile or self.is_online_mode:
|
||||
return None
|
||||
pid = self.active_profile["id"]
|
||||
if Database.get_active_devils_bj_account(pid) is not None:
|
||||
|
|
@ -85,26 +234,69 @@ class AppController:
|
|||
self.launch_game(g)
|
||||
return
|
||||
|
||||
def show_main_menu(self):
|
||||
def show_main_menu(self, category: str | None = None):
|
||||
self.sounds.play_menu_music()
|
||||
if self.active_profile:
|
||||
pid = self.active_profile["id"]
|
||||
self.active_profile = Database.get_profile_by_id(pid)
|
||||
fresh = Database.get_profile_by_id(pid)
|
||||
if fresh:
|
||||
fresh = dict(fresh)
|
||||
fresh["overall_progress"] = Database.get_profile_overall_progress(pid)
|
||||
if self.is_online_mode:
|
||||
fresh["is_online"] = True
|
||||
fresh["online_endpoint"] = self.online_session.endpoint_label
|
||||
self.active_profile = fresh
|
||||
|
||||
if self.has_active_devils_lock():
|
||||
self.view.show_main_menu(self.active_profile, [], devils_resume_only=True)
|
||||
else:
|
||||
games = self.loader.discover_games()
|
||||
for g in games:
|
||||
g["progress"] = Database.get_game_progress(pid, g["folder"])
|
||||
self.view.show_main_menu(self.active_profile, games, devils_resume_only=False)
|
||||
self.view.main_menu_view.show(
|
||||
self.active_profile, games, devils_resume_only=False, category=category
|
||||
)
|
||||
|
||||
def show_statistics(self):
|
||||
if self.has_active_devils_lock():
|
||||
if self.has_active_devils_lock() or not self.active_profile:
|
||||
return
|
||||
self.sounds.play_menu_music()
|
||||
if self.active_profile:
|
||||
self.active_profile = Database.get_profile_by_id(self.active_profile["id"])
|
||||
self.view.show_statistics(self.active_profile)
|
||||
fresh = Database.get_profile_by_id(self.active_profile["id"])
|
||||
if fresh:
|
||||
if self.is_online_mode:
|
||||
fresh = dict(fresh)
|
||||
fresh["is_online"] = True
|
||||
fresh["online_endpoint"] = self.online_session.endpoint_label
|
||||
self.active_profile = fresh
|
||||
ctx = AppContext(self, game_folder="")
|
||||
from view.stats.unified_stats_view import UnifiedStatsView
|
||||
UnifiedStatsView.open(ctx, game_endpoint=None, on_back=None)
|
||||
|
||||
def show_settings(
|
||||
self,
|
||||
on_back=None,
|
||||
in_game_overlay: bool = False,
|
||||
on_ingame_lang_refresh=None,
|
||||
feedback_txt: str = "",
|
||||
feedback_err: bool = False,
|
||||
):
|
||||
if not in_game_overlay:
|
||||
self.sounds.play_menu_music()
|
||||
if self.view is not None:
|
||||
self.view.show_settings(
|
||||
on_back=on_back,
|
||||
in_game_overlay=in_game_overlay,
|
||||
on_ingame_lang_refresh=on_ingame_lang_refresh,
|
||||
feedback_txt=feedback_txt,
|
||||
feedback_err=feedback_err,
|
||||
)
|
||||
|
||||
def show_profile(self, on_back=None):
|
||||
if self.has_active_devils_lock() or not self.active_profile:
|
||||
return
|
||||
self.sounds.play_menu_music()
|
||||
if self.view is not None:
|
||||
self.view.show_profile(on_back=on_back)
|
||||
|
||||
def launch_game(self, game_entry: dict):
|
||||
self.view.clear_window(apply_global_bg=True)
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -3,8 +3,8 @@
|
|||
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||
from games.blackjack.models.player_hand import PlayerHand
|
||||
from models.card import Card
|
||||
from models.deck import Deck
|
||||
from models.cards.card import Card
|
||||
from models.cards.deck import Deck
|
||||
from resources.code_res.game_constants import BJ_DEALER_STAND, BJ_RESHUFFLE_RATIO, BJ_TARGET_SCORE
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import random
|
||||
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
from resources.code_res.game_constants import (
|
||||
ACE_RANK, BJ_STARTING_GOLD, BOT_DEITY_LEVEL, FACE_RANKS, SEVEN_RANK
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/models/bot_seat.py
|
||||
from dataclasses import dataclass, field
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
from resources.code_res.game_constants import BJ_STARTING_GOLD
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/models/hand_evaluator.py
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
from resources.code_res.game_constants import ACE_RANK, BJ_TARGET_SCORE, SEVEN_RANK
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/models/player_hand.py
|
||||
from dataclasses import dataclass, field
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# games/blackjack/start.py
|
||||
from games.blackjack.views.blackjack_menu_view import BlackjackMenuView
|
||||
from games.blackjack.views.blackjack_table_view import BlackjackTableView
|
||||
from models.database import Database
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import CAT_LUCK
|
||||
|
||||
GAME_TITLE_KEY = "game_title_blackjack"
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,348 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/views/blackjack_arena_renderer.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||
from games.blackjack.models.player_hand import PlayerHand
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD,
|
||||
ACCENT_GOTH,
|
||||
BJ_BOT_CARD_SIZE,
|
||||
BJ_SPLIT_CARD_SIZE,
|
||||
ERROR_FG,
|
||||
FG_COLOR,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
PLAYING_CARD_SIZE,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
BJ_DEALER_CARD_SIZE = (86, 125)
|
||||
BJ_COMPACT_BOT_ROW_H = 112
|
||||
|
||||
BJ_SEAT_LAYOUT_BY_COUNT = {
|
||||
1: (2,),
|
||||
2: (1, 2),
|
||||
3: (1, 2, 3),
|
||||
4: (0, 1, 2, 3),
|
||||
}
|
||||
|
||||
|
||||
class BlackjackArenaRenderer:
|
||||
"""Zeichnet Dealer, Pot, Kultisten (Ecken auf Desktop | Top-Leiste auf Kompakt) und Spielerhände."""
|
||||
|
||||
@staticmethod
|
||||
def hand_state_suffix(hand: PlayerHand) -> str:
|
||||
if hand.busted:
|
||||
return t("bj_state_busted")
|
||||
if hand.folded:
|
||||
return t("bj_state_folded")
|
||||
if hand.doubled or hand.cards_locked:
|
||||
return t("bj_state_locked")
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def draw_dealer_and_pot(
|
||||
view,
|
||||
table_rect: tuple[int, int, int, int],
|
||||
player_top_y: int,
|
||||
reveal_dealer: bool,
|
||||
) -> None:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
t_cx = (tx1 + tx2) // 2
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
|
||||
if compact:
|
||||
top_reserve = (BJ_COMPACT_BOT_ROW_H + 10) if view.bots else 8
|
||||
felt_top = ty1 + top_reserve
|
||||
felt_bot = player_top_y - 8
|
||||
avail_felt_h = max(140, felt_bot - felt_top)
|
||||
d_scale = min(1.0, max(0.76, (avail_felt_h - 54) / max(1, BJ_DEALER_CARD_SIZE[1])))
|
||||
dc_sz = (int(round(BJ_DEALER_CARD_SIZE[0] * d_scale)), int(round(BJ_DEALER_CARD_SIZE[1] * d_scale)))
|
||||
dc_h = dc_sz[1]
|
||||
d_cards_cy = felt_top + dc_h // 2 + max(4, (avail_felt_h - dc_h - 48) // 3)
|
||||
else:
|
||||
t_h = max(260, ty2 - ty1)
|
||||
felt_top = ty1 + max(36, int(t_h * 0.15))
|
||||
felt_bot = min(ty2 - max(28, int(t_h * 0.12)), player_top_y - 12)
|
||||
dc_sz = BJ_DEALER_CARD_SIZE
|
||||
dc_h = dc_sz[1]
|
||||
avail_felt_h = max(170, felt_bot - felt_top)
|
||||
d_cards_cy = felt_top + min(dc_h // 2 + 12, int(avail_felt_h * 0.34))
|
||||
|
||||
d_photos = []
|
||||
for c_idx, card in enumerate(view.engine.dealer_hand):
|
||||
photo = (
|
||||
view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=dc_sz)
|
||||
if c_idx == 1 and not reveal_dealer
|
||||
else view.ctx.assets.get_card_photo(card.image_filename, size=dc_sz)
|
||||
)
|
||||
if photo:
|
||||
view._photo_refs.append(photo)
|
||||
d_photos.append(photo)
|
||||
|
||||
if d_photos:
|
||||
view._draw_fanned_cards_on_canvas(
|
||||
t_cx, d_cards_cy, d_photos, dc_sz, visible_step=34 if compact else 38, max_width=320
|
||||
)
|
||||
|
||||
pot_txt = t("bj_pot_banner", view.engine.pot).split("|")[0].strip()
|
||||
pot_cy = min(
|
||||
felt_bot - 20,
|
||||
max(d_cards_cy + dc_h // 2 + (26 if compact else 34), (d_cards_cy + dc_h // 2 + felt_bot) // 2),
|
||||
)
|
||||
pot_size = max(15 if compact else 16, FONT_SIZE_BODY + (0 if compact else 1))
|
||||
pot_ph = view._make_goth_photo(pot_txt, size_px=pot_size, color=FONT_COLOR_TITLE_MAIN)
|
||||
if pot_ph is not None:
|
||||
bw, bh = max(210, pot_ph.width() + 56), max(36, pot_ph.height() + 16)
|
||||
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
|
||||
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
|
||||
else:
|
||||
view._draw_framed_panel(t_cx, pot_cy, 220, 38, frame_style="gold")
|
||||
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_size, ACCENT_GOLD)
|
||||
|
||||
@classmethod
|
||||
def draw_bots_at_corners(
|
||||
cls,
|
||||
view,
|
||||
cw: int,
|
||||
ch: int,
|
||||
pad_x: int,
|
||||
pad_top: int,
|
||||
pad_bot: int,
|
||||
table_rect: tuple[int, int, int, int],
|
||||
reveal_opponents: bool,
|
||||
) -> None:
|
||||
if not view.bots:
|
||||
return
|
||||
if getattr(view, "is_compact_arena", False):
|
||||
cls._draw_bots_top_strip(view, cw, pad_x, pad_top, reveal_opponents)
|
||||
return
|
||||
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
bc_w, bc_h = BJ_BOT_CARD_SIZE
|
||||
card_scale = 0.90 if ch < 560 else 1.0
|
||||
cur_card_sz = (max(52, int(bc_w * card_scale)), max(76, int(bc_h * card_scale)))
|
||||
base_box_w = max(198, cur_card_sz[0] + 114)
|
||||
box_h = cur_card_sz[1] + 90
|
||||
|
||||
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
|
||||
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
|
||||
if bot_cy - top_cy < box_h + 14:
|
||||
mid_y = (top_cy + bot_cy) // 2
|
||||
top_cy, bot_cy = mid_y - (box_h + 14) // 2, mid_y + (box_h + 14) // 2
|
||||
|
||||
slot_indices = BJ_SEAT_LAYOUT_BY_COUNT.get(len(view.bots), (0, 1, 2, 3))
|
||||
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
|
||||
|
||||
for bot_i, bot in enumerate(view.bots):
|
||||
coord_idx = slot_indices[bot_i]
|
||||
is_left_side = coord_idx in (0, 1)
|
||||
by = bot_cy if coord_idx in (0, 3) else top_cy
|
||||
|
||||
is_turn = (bot_i == view.active_bot_idx)
|
||||
is_out = (bot.folded or bot.busted)
|
||||
disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name
|
||||
name_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
|
||||
gold_txt = t("bj_bot_gold_lbl", bot.gold)
|
||||
info_txt = cls._bot_info_text(bot, reveal_opponents)
|
||||
info_col = ERROR_FG if is_out else FG_COLOR
|
||||
|
||||
name_ph = view._make_goth_photo(disp_name, name_sz, name_col, max_width=220)
|
||||
gold_ph = view._make_goth_photo(gold_txt, sub_sz, ACCENT_GOLD)
|
||||
info_ph = view._make_goth_photo(info_txt, sub_sz, info_col, max_width=220)
|
||||
|
||||
widest_txt = max((ph.width() for ph in (name_ph, gold_ph, info_ph) if ph), default=140)
|
||||
box_w = max(base_box_w, min(268, widest_txt + 54))
|
||||
bx = (
|
||||
max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
|
||||
if is_left_side else min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
|
||||
)
|
||||
|
||||
view._draw_framed_panel(
|
||||
bx, by, box_w, box_h,
|
||||
frame_style="gold" if is_turn else "purple",
|
||||
status_border=ERROR_FG if is_out else None,
|
||||
)
|
||||
top_y, bot_y = by - box_h // 2, by + box_h // 2
|
||||
view._place_goth_photo_or_fallback(bx, top_y + 23, name_ph, disp_name, name_sz, name_col)
|
||||
view._place_goth_photo_or_fallback(bx, top_y + 42, gold_ph, gold_txt, sub_sz, ACCENT_GOLD)
|
||||
|
||||
show_faces = reveal_opponents or bot.busted
|
||||
bot_photos = [
|
||||
ph for card in bot.hand
|
||||
if (ph := (
|
||||
view.ctx.assets.get_card_photo(card.image_filename, size=cur_card_sz)
|
||||
if show_faces else view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=cur_card_sz)
|
||||
))
|
||||
]
|
||||
view._photo_refs.extend(bot_photos)
|
||||
if bot_photos:
|
||||
view._draw_fanned_cards_on_canvas(bx, by + 6, bot_photos, cur_card_sz, visible_step=25, max_width=box_w - 36)
|
||||
view._place_goth_photo_or_fallback(bx, bot_y - 21, info_ph, info_txt, sub_sz, info_col)
|
||||
|
||||
@classmethod
|
||||
def _draw_bots_top_strip(cls, view, cw: int, pad_x: int, pad_top: int, reveal_opponents: bool) -> None:
|
||||
"""Zeichnet 1..4 Kultisten im Kompaktmodus nebeneinander in einer oberen Reihe."""
|
||||
n = len(view.bots)
|
||||
gap = 6
|
||||
avail_w = max(320, cw - 2 * pad_x)
|
||||
box_w = min(204, (avail_w - (n - 1) * gap) // max(1, n))
|
||||
box_h = BJ_COMPACT_BOT_ROW_H
|
||||
start_x = (cw - (n * box_w + (n - 1) * gap)) // 2 + box_w // 2
|
||||
by = pad_top + box_h // 2 + 2
|
||||
|
||||
mini_sz = (36, 52)
|
||||
name_sz = max(12, FONT_SIZE_SMALL_MIN)
|
||||
sub_sz = max(11, FONT_SIZE_SMALL_MIN - 1)
|
||||
max_tw = max(72, box_w - 18)
|
||||
|
||||
for bot_i, bot in enumerate(view.bots):
|
||||
bx = start_x + bot_i * (box_w + gap)
|
||||
is_turn = (bot_i == view.active_bot_idx)
|
||||
is_out = (bot.folded or bot.busted)
|
||||
|
||||
view._draw_framed_panel(
|
||||
bx, by, box_w, box_h,
|
||||
frame_style="gold" if is_turn else "purple",
|
||||
status_border=ERROR_FG if is_out else None,
|
||||
)
|
||||
|
||||
disp_name = f"{bot.name} ({bot.gold}g)"
|
||||
name_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
|
||||
info_txt = cls._bot_info_text(bot, reveal_opponents)
|
||||
info_col = ERROR_FG if is_out else FG_COLOR
|
||||
|
||||
name_ph = view._make_goth_photo(disp_name, name_sz, name_col, max_width=max_tw)
|
||||
info_ph = view._make_goth_photo(info_txt, sub_sz, info_col, max_width=max_tw)
|
||||
view._place_goth_photo_or_fallback(bx, by - box_h // 2 + 16, name_ph, disp_name, name_sz, name_col)
|
||||
|
||||
show_faces = reveal_opponents or bot.busted
|
||||
bot_photos = [
|
||||
ph for card in bot.hand
|
||||
if (ph := (
|
||||
view.ctx.assets.get_card_photo(card.image_filename, size=mini_sz)
|
||||
if show_faces else view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=mini_sz)
|
||||
))
|
||||
]
|
||||
view._photo_refs.extend(bot_photos)
|
||||
if bot_photos:
|
||||
view._draw_fanned_cards_on_canvas(bx, by + 2, bot_photos, mini_sz, visible_step=16, max_width=box_w - 20)
|
||||
|
||||
view._place_goth_photo_or_fallback(bx, by + box_h // 2 - 14, info_ph, info_txt, sub_sz, info_col)
|
||||
|
||||
@staticmethod
|
||||
def _bot_info_text(bot, reveal_opponents: bool) -> str:
|
||||
if reveal_opponents and bot.hand:
|
||||
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||
if bot.folded:
|
||||
return t("bj_rank_folded", b_val)
|
||||
if bot.busted:
|
||||
return t("bj_rank_busted", b_val)
|
||||
return t("bj_bot_showdown_val", b_val, bot.bet_in_pot)
|
||||
if bot.status_text:
|
||||
return bot.status_text
|
||||
if bot.hand:
|
||||
return t("bj_bot_cards_hidden", len(bot.hand), bot.bet_in_pot)
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def draw_player_hands(cls, view, cw: int, player_zone_top: int, player_zone_bot: int) -> None:
|
||||
hands = view.engine.player_hands
|
||||
if not hands:
|
||||
return
|
||||
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
avail_h = max(136 if compact else 140, player_zone_bot - player_zone_top)
|
||||
zone_cy = (player_zone_top + player_zone_bot) // 2
|
||||
|
||||
if len(hands) == 1:
|
||||
h = hands[0]
|
||||
base_w, base_h = PLAYING_CARD_SIZE
|
||||
scale = max(84, min(base_h, avail_h - 48)) / max(1, base_h)
|
||||
card_sz = (max(58, int(round(base_w * scale))), int(round(base_h * scale)))
|
||||
|
||||
p_photos = [
|
||||
ph for card in h.cards
|
||||
if (ph := view.ctx.assets.get_card_photo(card.image_filename, size=card_sz))
|
||||
]
|
||||
view._photo_refs.extend(p_photos)
|
||||
|
||||
p_val, p_soft = HandEvaluator.evaluate(h.cards)
|
||||
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
|
||||
lbl_txt = t("bj_player_total", p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
|
||||
|
||||
is_player_turn = (view.engine.state == "ACTION_LOOP" and view.active_bot_idx == -1)
|
||||
is_out = (h.busted or h.folded)
|
||||
lbl_col = ERROR_FG if is_out else FONT_COLOR_TITLE_MAIN
|
||||
lbl_sz = max(13 if compact else 14, FONT_SIZE_BODY - 1)
|
||||
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col, max_width=cw - 56)
|
||||
|
||||
step = 34 if compact else 36
|
||||
fan_w = card_sz[0] + max(0, len(p_photos) - 1) * step
|
||||
txt_w = lbl_ph.width() if lbl_ph is not None else 220
|
||||
box_w = max(280, min(cw - 20 if compact else 560, max(fan_w + 72, txt_w + 56)))
|
||||
box_h = min(avail_h, card_sz[1] + 48)
|
||||
|
||||
view._draw_framed_panel(
|
||||
cw // 2, zone_cy, box_w, box_h,
|
||||
frame_style="gold" if is_player_turn and not is_out else "purple",
|
||||
status_border=ERROR_FG if is_out else None,
|
||||
)
|
||||
if p_photos:
|
||||
view._draw_fanned_cards_on_canvas(
|
||||
cw // 2, zone_cy - 10, p_photos, card_sz, visible_step=step, max_width=box_w - 36
|
||||
)
|
||||
view._place_goth_photo_or_fallback(cw // 2, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||
return
|
||||
|
||||
# Split-Hände nebeneinander (auf 658px Breite sauber eingepasst)
|
||||
base_w, base_h = BJ_SPLIT_CARD_SIZE
|
||||
scale = max(76, min(base_h, avail_h - 46)) / max(1, base_h)
|
||||
card_sz = (max(52, int(round(base_w * scale))), int(round(base_h * scale)))
|
||||
box_h = min(avail_h, card_sz[1] + 46)
|
||||
lbl_sz = max(12 if compact else 13, FONT_SIZE_BODY - 2)
|
||||
|
||||
n_hands = len(hands)
|
||||
max_allowed_box_w = (cw - 24 - (n_hands - 1) * 10) // max(1, n_hands) if compact else 320
|
||||
prepared_splits = []
|
||||
max_box_w = min(228, max_allowed_box_w)
|
||||
|
||||
for idx, h in enumerate(hands):
|
||||
is_active = (
|
||||
view.engine.state == "ACTION_LOOP"
|
||||
and view.active_bot_idx == -1
|
||||
and idx == view.active_hand_idx
|
||||
)
|
||||
is_out = (h.busted or h.folded)
|
||||
p_val, p_soft = HandEvaluator.evaluate(h.cards)
|
||||
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
|
||||
lbl_txt = t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
|
||||
lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if is_out else FG_COLOR)
|
||||
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col, max_width=max_allowed_box_w - 24)
|
||||
txt_w = lbl_ph.width() if lbl_ph is not None else 160
|
||||
sp_fan_w = card_sz[0] + max(0, len(h.cards) - 1) * 24
|
||||
max_box_w = max(max_box_w, min(max_allowed_box_w, max(sp_fan_w + 48, txt_w + 40)))
|
||||
prepared_splits.append((h, is_active, is_out, lbl_txt, lbl_col, lbl_ph))
|
||||
|
||||
slot_gap = max_box_w + (10 if compact else 14)
|
||||
start_cx = cw // 2 - ((n_hands - 1) * slot_gap) // 2
|
||||
|
||||
for idx, (h, is_active, is_out, lbl_txt, lbl_col, lbl_ph) in enumerate(prepared_splits):
|
||||
h_cx = start_cx + idx * slot_gap
|
||||
view._draw_framed_panel(
|
||||
h_cx, zone_cy, max_box_w, box_h,
|
||||
frame_style="gold" if is_active else "purple",
|
||||
status_border=ERROR_FG if is_out else None,
|
||||
)
|
||||
sp_photos = [
|
||||
ph for card in h.cards
|
||||
if (ph := view.ctx.assets.get_card_photo(card.image_filename, size=card_sz))
|
||||
]
|
||||
view._photo_refs.extend(sp_photos)
|
||||
if sp_photos:
|
||||
view._draw_fanned_cards_on_canvas(
|
||||
h_cx, zone_cy - 9, sp_photos, card_sz, visible_step=24, max_width=max_box_w - 28
|
||||
)
|
||||
view._place_goth_photo_or_fallback(h_cx, zone_cy + box_h // 2 - 17, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||
|
|
@ -2,515 +2,76 @@
|
|||
# games/blackjack/views/blackjack_menu_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import tkinter as tk
|
||||
|
||||
from games.blackjack.views.blackjack_stats_view import BlackjackStatsView
|
||||
from games.blackjack.views.blackjack_table_view import BlackjackTableView
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
BJ_INITIAL_ANTE,
|
||||
BJ_MAX_BOTS,
|
||||
BJ_STARTING_GOLD,
|
||||
BJ_VARIANTS,
|
||||
DEVILS_DEAL_GOLD_REWARD,
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
FONT_COLOR_BODY_MUTED,
|
||||
FONT_COLOR_DISABLED,
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_COLOR_STATUS_LOSS,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
GOLD_MAX_ACCOUNTS,
|
||||
GOLD_MIN_TABLE_ENTRY,
|
||||
XP_TO_GOLD_AMOUNT,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.bot_setup_widget import BotSetupWidget
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.goth_entry import GothEntry
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.shared_bases.luck_pouch_menu_base import LuckPouchMenuBase
|
||||
|
||||
GAME_FOLDER_ID = "blackjack"
|
||||
|
||||
|
||||
class BlackjackMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self.bot_widget: BotSetupWidget | None = None
|
||||
self._photo_refs: list = []
|
||||
class BlackjackMenuView(LuckPouchMenuBase):
|
||||
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||
LAST_ACC_SETTING_PREFIX = "last_bj_account"
|
||||
STARTING_GOLD = BJ_STARTING_GOLD
|
||||
MAX_BOTS = BJ_MAX_BOTS
|
||||
REQUIRES_MIN_ONE_BOT = False
|
||||
DEVILS_DEFAULT_VARIANT = "bj_classic"
|
||||
|
||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
||||
pid = self.ctx.profile["id"]
|
||||
KEY_TOPBAR = "bj_menu_topbar"
|
||||
KEY_HEADER_GOLD = "bj_header_gold"
|
||||
KEY_SEC1_TITLE = "bj_sec1_title"
|
||||
KEY_BOTS_TITLE = "bj_bots_sec_title"
|
||||
KEY_SEC3_TITLE = "bj_sec3_title"
|
||||
KEY_GOLD_DISPLAY = "bj_gold_display_lbl"
|
||||
KEY_DEFAULT_ACC_NAME = "bj_default_acc_name"
|
||||
KEY_ERR_DUPLICATE = "bj_err_duplicate_name"
|
||||
|
||||
devils_acc = Database.get_active_devils_bj_account(pid)
|
||||
if devils_acc is not None:
|
||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
||||
if saved is not None:
|
||||
BlackjackTableView(
|
||||
self.ctx,
|
||||
variant_key=saved["variant_key"],
|
||||
bj_account_id=devils_acc["id"],
|
||||
bot_configs=[],
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
resume_state_json=saved["state_json"],
|
||||
)
|
||||
return
|
||||
def _get_active_devils_account(self, pid: int):
|
||||
return Database.get_active_devils_bj_account(pid)
|
||||
|
||||
self.ctx.sounds.play_menu_music()
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self._photo_refs.clear()
|
||||
bj_prog = self.ctx.refresh_game_progress()
|
||||
def _get_accounts(self, pid: int):
|
||||
return Database.get_blackjack_accounts(pid)
|
||||
|
||||
dyn_xp_cost = bj_prog["xp_exchange_cost"]
|
||||
is_divine = bj_prog["is_divine_punishment"]
|
||||
at_floor = bj_prog["at_divine_floor"]
|
||||
devils_deal_open = bj_prog["devils_deal_unlocked"]
|
||||
def _get_account(self, acc_id: int):
|
||||
return Database.get_blackjack_account(acc_id)
|
||||
|
||||
setting_key = f"last_bj_account_{pid}"
|
||||
accounts = Database.get_blackjack_accounts(pid)
|
||||
has_accounts = len(accounts) > 0
|
||||
def _create_account(self, pid: int, name: str):
|
||||
return Database.create_blackjack_account(pid, name)
|
||||
|
||||
if preselect_id is None and has_accounts:
|
||||
saved_id_str = Database.load_setting(setting_key, "")
|
||||
if saved_id_str.isdigit():
|
||||
preselect_id = int(saved_id_str)
|
||||
def _delete_account(self, acc_id: int):
|
||||
Database.delete_blackjack_account(acc_id)
|
||||
|
||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
||||
acc_names = list(acc_by_name.keys())
|
||||
def _exchange_xp(self, pid: int, acc_id: int):
|
||||
return Database.exchange_xp_for_bj_gold(pid, acc_id)
|
||||
|
||||
active_acc = None
|
||||
if has_accounts:
|
||||
active_acc = accounts[0]
|
||||
if preselect_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == preselect_id:
|
||||
active_acc = a
|
||||
break
|
||||
Database.save_setting(setting_key, str(active_acc["id"]))
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
return BJ_VARIANTS
|
||||
|
||||
selected_name_var = tk.StringVar(
|
||||
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
|
||||
)
|
||||
state_msg = {"text": status_msg, "ok": status_is_ok}
|
||||
def _min_entry_for_variant(self, _v_key: str, _cfg: dict) -> int:
|
||||
return GOLD_MIN_TABLE_ENTRY
|
||||
|
||||
def get_current_acc() -> dict | None:
|
||||
return acc_by_name.get(selected_name_var.get())
|
||||
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
|
||||
return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
|
||||
|
||||
def open_bj_stats():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
BlackjackStatsView(
|
||||
self.ctx,
|
||||
on_back_to_bj_menu=lambda aid: self.show(preselect_id=aid),
|
||||
).show(selected_acc_id=cur["id"])
|
||||
def _format_limit_info(self, dyn_xp_cost: int) -> str:
|
||||
return t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
|
||||
def refresh_on_lang_switch():
|
||||
cur = get_current_acc()
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
self.show(preselect_id=cur["id"] if cur else None)
|
||||
|
||||
topbar_gold_txt = (
|
||||
t("bj_header_gold", active_acc["account_name"], active_acc["gold"])
|
||||
if active_acc else ""
|
||||
)
|
||||
topbar = self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("bj_menu_topbar"),
|
||||
on_game_menu=None,
|
||||
on_stats=open_bj_stats,
|
||||
stats_enabled=has_accounts,
|
||||
extra_right_text=topbar_gold_txt,
|
||||
on_lang_refresh=refresh_on_lang_switch,
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
# --- Widgets Spalte 1: Kontoverwaltung ---
|
||||
table_buttons: list[ImageButton] = []
|
||||
|
||||
def on_account_switched(_val=None):
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
fresh = Database.get_blackjack_account(cur["id"])
|
||||
Database.save_setting(setting_key, str(fresh["id"]))
|
||||
topbar.extra_label.configure(text=t("bj_header_gold", fresh["account_name"], fresh["gold"]))
|
||||
playable = fresh["gold"] >= GOLD_MIN_TABLE_ENTRY
|
||||
for tb in table_buttons:
|
||||
tb.set_enabled(playable)
|
||||
state_msg["text"] = ""
|
||||
if cv.winfo_exists() and cv.winfo_width() >= 200:
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
|
||||
acc_dd = GothDropdown(
|
||||
cv,
|
||||
self.ctx.assets,
|
||||
values=acc_names if has_accounts else [t("bj_no_account_item")],
|
||||
textvariable=selected_name_var,
|
||||
on_change=on_account_switched,
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=215,
|
||||
height=36,
|
||||
enabled=has_accounts,
|
||||
)
|
||||
|
||||
def exchange_xp_action():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, msg = Database.exchange_xp_for_bj_gold(pid, cur["id"])
|
||||
if ok and is_divine:
|
||||
self.ctx.sounds.play("lose")
|
||||
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
|
||||
|
||||
can_afford_xp = is_divine or (bj_prog["total_points"] >= dyn_xp_cost)
|
||||
can_exchange = has_accounts and (not at_floor) and can_afford_xp
|
||||
ex_btn_txt = (
|
||||
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
exchange_btn = ImageButton(
|
||||
cv, ex_btn_txt, btn_norm, btn_purp,
|
||||
exchange_xp_action, sound_mgr=self.ctx.sounds,
|
||||
width=180, height=36, enabled=can_exchange, style="amethyst",
|
||||
)
|
||||
|
||||
def delete_selected_account():
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
Database.delete_blackjack_account(cur["id"])
|
||||
self.show()
|
||||
|
||||
delete_btn = ImageButton(
|
||||
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
|
||||
delete_selected_account, sound_mgr=self.ctx.sounds,
|
||||
width=136, height=32, enabled=has_accounts, style="amethyst",
|
||||
)
|
||||
|
||||
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
|
||||
next_idx = len(accounts) + 1
|
||||
new_acc_var = tk.StringVar(
|
||||
value=t("bj_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
|
||||
)
|
||||
new_entry = GothEntry(
|
||||
cv, self.ctx.assets, width=215, height=36,
|
||||
textvariable=new_acc_var, enabled=can_create_more,
|
||||
)
|
||||
|
||||
def create_new_account():
|
||||
if not can_create_more:
|
||||
return
|
||||
name = new_entry.get().strip()
|
||||
if not name:
|
||||
state_msg["text"] = t("bj_err_empty_name")
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
try:
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
created = Database.create_blackjack_account(pid, name)
|
||||
Database.save_setting(setting_key, str(created["id"]))
|
||||
self.show(preselect_id=created["id"])
|
||||
except (sqlite3.IntegrityError, RuntimeError) as exc:
|
||||
state_msg["text"] = t("bj_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc)
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
|
||||
if can_create_more:
|
||||
new_entry.bind_return(lambda _e: create_new_account())
|
||||
|
||||
create_style = "fire" if not has_accounts else "amethyst"
|
||||
create_btn = ImageButton(
|
||||
cv, t("bj_create_acc_btn", BJ_STARTING_GOLD),
|
||||
btn_fire if not has_accounts else btn_norm,
|
||||
btn_fire if not has_accounts else btn_purp,
|
||||
create_new_account, sound_mgr=self.ctx.sounds,
|
||||
width=180, height=36, enabled=can_create_more, style=create_style,
|
||||
)
|
||||
|
||||
# Optional Devil's Deal Controls
|
||||
sac_dd = None
|
||||
devil_btn = None
|
||||
min_sac_lvl = Progression.get_devils_deal_min_level()
|
||||
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID) if (devils_deal_open and has_accounts) else []
|
||||
if sac_candidates:
|
||||
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
|
||||
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
|
||||
sac_dd = GothDropdown(
|
||||
cv, self.ctx.assets, values=list(sac_map.keys()),
|
||||
textvariable=sac_var, sound_mgr=self.ctx.sounds, width=250, height=34,
|
||||
)
|
||||
|
||||
def seal_devils_deal():
|
||||
cur = get_current_acc()
|
||||
victim_id = sac_map.get(sac_var.get())
|
||||
if cur is None or victim_id is None:
|
||||
return
|
||||
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
|
||||
if ok:
|
||||
self.ctx.sounds.play("end_battle")
|
||||
BlackjackTableView(
|
||||
self.ctx,
|
||||
variant_key="bj_classic",
|
||||
bj_account_id=cur["id"],
|
||||
bot_configs=active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
|
||||
devil_btn = ImageButton(
|
||||
cv, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
|
||||
btn_fire, btn_fire, seal_devils_deal,
|
||||
sound_mgr=None, width=180, height=34, style="fire",
|
||||
)
|
||||
|
||||
# --- Spalte 2: Gegner-Setup ---
|
||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||
self.bot_widget = BotSetupWidget(cv, saved_bots, max_bots=BJ_MAX_BOTS, enabled=has_accounts)
|
||||
|
||||
# --- Sektion 3: Varianten-Buttons ---
|
||||
def enter_table(v_key: str):
|
||||
cur = get_current_acc()
|
||||
if not cur:
|
||||
return
|
||||
acc = Database.get_blackjack_account(cur["id"])
|
||||
if not acc:
|
||||
return
|
||||
Database.save_setting(setting_key, str(acc["id"]))
|
||||
active_bots, configs_to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
|
||||
|
||||
cur_bj_prog = self.ctx.refresh_game_progress()
|
||||
if acc["gold"] < GOLD_MIN_TABLE_ENTRY:
|
||||
state_msg["text"] = t(
|
||||
"bj_err_not_enough_gold_entry",
|
||||
acc["account_name"], GOLD_MIN_TABLE_ENTRY, acc["gold"],
|
||||
cur_bj_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT,
|
||||
)
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
|
||||
BlackjackTableView(
|
||||
self.ctx, v_key, acc["id"], active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
|
||||
can_enter_now = bool(active_acc and active_acc["gold"] >= GOLD_MIN_TABLE_ENTRY)
|
||||
variant_items = list(BJ_VARIANTS.items())
|
||||
for v_key, _cfg in variant_items:
|
||||
t_btn = ImageButton(
|
||||
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
|
||||
lambda k=v_key: enter_table(k),
|
||||
sound_mgr=self.ctx.sounds, width=168, height=38,
|
||||
enabled=can_enter_now, style="fire",
|
||||
)
|
||||
table_buttons.append(t_btn)
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
compact = (h < 700)
|
||||
pad_x = max(44, int(w * 0.045))
|
||||
usable_w = min(1240, w - 2 * pad_x)
|
||||
x0 = (w - usable_w) // 2
|
||||
col_gap = 20
|
||||
col_w = (usable_w - col_gap) // 2
|
||||
left_x = x0
|
||||
right_x = x0 + col_w + col_gap
|
||||
|
||||
top_sec_y = 14 if compact else 22
|
||||
upper_h = 282 if compact else 302
|
||||
|
||||
# Überschriften Spalte 1 & 2
|
||||
s1_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, BJ_STARTING_GOLD),
|
||||
FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, max_width=col_w - 10, align="left",
|
||||
)
|
||||
s2_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_bots_sec_title"),
|
||||
FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED,
|
||||
max_width=col_w - 10, align="left",
|
||||
)
|
||||
self._photo_refs.extend([s1_ph, s2_ph])
|
||||
cv.create_image(left_x + 8, top_sec_y + 12, image=s1_ph, anchor="w", tags="fg")
|
||||
cv.create_image(right_x + 8, top_sec_y + 12, image=s2_ph, anchor="w", tags="fg")
|
||||
|
||||
box_top = top_sec_y + 34
|
||||
box_cy = box_top + upper_h // 2
|
||||
|
||||
# Rahmen links (box_big) & rechts (box_purple)
|
||||
l_frame = self.ctx.assets.get_box_photo("box_big", (col_w, upper_h))
|
||||
r_frame = self.ctx.assets.get_box_photo("box_purple", (col_w, upper_h))
|
||||
if l_frame:
|
||||
self._photo_refs.append(l_frame)
|
||||
cv.create_image(left_x + col_w // 2, box_cy, image=l_frame, anchor="center", tags="fg")
|
||||
if r_frame:
|
||||
self._photo_refs.append(r_frame)
|
||||
cv.create_image(right_x + col_w // 2, box_cy, image=r_frame, anchor="center", tags="fg")
|
||||
|
||||
# Spalte 1 Inhalt
|
||||
in_pad = 22
|
||||
lbl_col_w = 118
|
||||
btn_w = 180
|
||||
mid_field_w = max(140, col_w - 2 * in_pad - lbl_col_w - btn_w - 16)
|
||||
|
||||
if acc_dd._width != mid_field_w:
|
||||
acc_dd._width = mid_field_w
|
||||
acc_dd.configure(width=mid_field_w)
|
||||
acc_dd._render_closed()
|
||||
|
||||
r1_y = box_top + 40
|
||||
l_act = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_active_acc_lbl"), FONT_SIZE_BODY,
|
||||
FONT_COLOR_BODY_DEFAULT if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
self._photo_refs.append(l_act)
|
||||
cv.create_image(left_x + in_pad, r1_y, image=l_act, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + in_pad + lbl_col_w, r1_y, window=acc_dd, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, r1_y, window=exchange_btn, anchor="e", tags="fg")
|
||||
|
||||
# Gold-Banner (box_gold_double)
|
||||
gb_y = r1_y + 54
|
||||
gb_w = col_w - 2 * in_pad
|
||||
gb_frame = self.ctx.assets.get_box_photo("box_gold_double", (gb_w, 50))
|
||||
if gb_frame:
|
||||
self._photo_refs.append(gb_frame)
|
||||
cv.create_image(left_x + col_w // 2, gb_y, image=gb_frame, anchor="center", tags="fg")
|
||||
|
||||
cur_acc_obj = get_current_acc()
|
||||
fresh_gold = Database.get_blackjack_account(cur_acc_obj["id"])["gold"] if cur_acc_obj else 0
|
||||
gold_str = t("bj_gold_display_lbl", fresh_gold) if cur_acc_obj else t("bj_gold_display_none")
|
||||
g_ph = self.ctx.assets.get_goth_text_photo(
|
||||
gold_str, FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_TITLE_MAIN if cur_acc_obj else FONT_COLOR_BODY_MUTED, align="left",
|
||||
)
|
||||
self._photo_refs.append(g_ph)
|
||||
cv.create_image(left_x + in_pad + 18, gb_y, image=g_ph, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad - 14, gb_y, window=delete_btn, anchor="e", tags="fg")
|
||||
|
||||
# Neues Konto Zeile
|
||||
r3_y = gb_y + 54
|
||||
l_new = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_new_acc_lbl"), FONT_SIZE_BODY,
|
||||
FONT_COLOR_TITLE_MAIN if not has_accounts else (FONT_COLOR_BODY_DEFAULT if can_create_more else FONT_COLOR_DISABLED),
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(l_new)
|
||||
cv.create_image(left_x + in_pad, r3_y, image=l_new, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + in_pad + lbl_col_w, r3_y, window=new_entry, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, r3_y, window=create_btn, anchor="e", tags="fg")
|
||||
|
||||
# Info / Devil's Deal Fußbereich in Spalte 1
|
||||
info_y = r3_y + 42
|
||||
if devils_deal_open and has_accounts:
|
||||
warn_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
|
||||
FONT_SIZE_SMALL_MIN, FONT_COLOR_STATUS_LOSS, max_width=gb_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(warn_ph)
|
||||
cv.create_image(left_x + in_pad, info_y, image=warn_ph, anchor="nw", tags="fg")
|
||||
if sac_dd is not None and devil_btn is not None:
|
||||
dy = box_top + upper_h - 30
|
||||
cv.create_window(left_x + in_pad, dy, window=sac_dd, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, dy, window=devil_btn, anchor="e", tags="fg")
|
||||
else:
|
||||
none_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_devils_deal_none", min_sac_lvl), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||
)
|
||||
self._photo_refs.append(none_ph)
|
||||
cv.create_image(left_x + in_pad, box_top + upper_h - 28, image=none_ph, anchor="w", tags="fg")
|
||||
else:
|
||||
info_txt = (
|
||||
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine
|
||||
else t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
inf_ph = self.ctx.assets.get_goth_text_photo(
|
||||
info_txt, FONT_SIZE_SMALL_MIN,
|
||||
FONT_COLOR_STATUS_LOSS if is_divine else FONT_COLOR_BODY_MUTED,
|
||||
max_width=gb_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(inf_ph)
|
||||
cv.create_image(left_x + in_pad, info_y + 4, image=inf_ph, anchor="nw", tags="fg")
|
||||
|
||||
# Spalte 2: BotSetupWidget einbetten
|
||||
if self.bot_widget is not None:
|
||||
bw_w = col_w - 40
|
||||
bw_h = BJ_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 8
|
||||
cv.create_window(
|
||||
right_x + col_w // 2, box_cy,
|
||||
window=self.bot_widget, width=bw_w, height=bw_h, anchor="center", tags="fg"
|
||||
)
|
||||
|
||||
# Feedback-Zeile + Sektion 3 Überschrift
|
||||
sec3_hdr_y = box_top + upper_h + (22 if compact else 30)
|
||||
if state_msg["text"]:
|
||||
fb_ph = self.ctx.assets.get_goth_text_photo(
|
||||
state_msg["text"], FONT_SIZE_BODY,
|
||||
FONT_COLOR_STATUS_WIN if state_msg["ok"] else FONT_COLOR_STATUS_LOSS,
|
||||
max_width=usable_w // 2, align="right",
|
||||
)
|
||||
self._photo_refs.append(fb_ph)
|
||||
cv.create_image(x0 + usable_w - 6, sec3_hdr_y, image=fb_ph, anchor="e", tags="fg")
|
||||
|
||||
s3_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_sec3_title"), FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
self._photo_refs.append(s3_ph)
|
||||
cv.create_image(left_x + 8, sec3_hdr_y, image=s3_ph, anchor="w", tags="fg")
|
||||
|
||||
# 2 Varianten-Karten im box_gold_small Rahmen
|
||||
var_top = sec3_hdr_y + 22
|
||||
var_h = max(124, min(154, h - var_top - 22))
|
||||
var_cy = var_top + var_h // 2
|
||||
|
||||
v_frame = self.ctx.assets.get_box_photo("box_gold_small", (col_w, var_h))
|
||||
if v_frame:
|
||||
self._photo_refs.append(v_frame)
|
||||
|
||||
for idx, (v_key, cfg) in enumerate(variant_items):
|
||||
vx = left_x if idx == 0 else right_x
|
||||
if v_frame:
|
||||
cv.create_image(vx + col_w // 2, var_cy, image=v_frame, anchor="center", tags="fg")
|
||||
|
||||
vt_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(f"variant_{v_key}"), FONT_SIZE_HEADING - 2,
|
||||
FONT_COLOR_TITLE_MAIN if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
vd_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE),
|
||||
FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=col_w - 56, align="left",
|
||||
)
|
||||
self._photo_refs.extend([vt_ph, vd_ph])
|
||||
cv.create_image(vx + 28, var_top + 32, image=vt_ph, anchor="w", tags="fg")
|
||||
cv.create_image(vx + 28, var_top + 64, image=vd_ph, anchor="w", tags="fg")
|
||||
cv.create_window(vx + col_w - 28, var_top + var_h - 32, window=table_buttons[idx], 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()))
|
||||
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
|
||||
BlackjackTableView(
|
||||
self.ctx,
|
||||
variant_key=variant_key,
|
||||
bj_account_id=acc_id,
|
||||
bot_configs=bots,
|
||||
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
|
||||
resume_state_json=resume_json,
|
||||
)
|
||||
|
|
@ -0,0 +1,307 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/views/blackjack_showdown_presenter.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||
from models.cards.card import Card
|
||||
from models.db.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import GOLD_MIN_TABLE_ENTRY
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
|
||||
class BlackjackShowdownPresenter:
|
||||
"""Kapselt Showdown-Abrechnung, 7-7-7-Sofortsieg, XP-Vergabe und Popup-Aufbereitung."""
|
||||
|
||||
@staticmethod
|
||||
def count_all_table_cards(view) -> None:
|
||||
if len(view.engine.dealer_hand) >= 2:
|
||||
for c in view.engine.dealer_hand[1:]:
|
||||
view.bot_ai.observe_public_card(c)
|
||||
for h in view.engine.player_hands:
|
||||
for c in h.cards:
|
||||
view.bot_ai.observe_public_card(c)
|
||||
for b in view.bots:
|
||||
for c in b.hand:
|
||||
view.bot_ai.observe_public_card(c)
|
||||
|
||||
@staticmethod
|
||||
def resolve_devils_lock(view, outcome_type: str) -> None:
|
||||
if not view.devils_locked:
|
||||
view._clear_persisted_state()
|
||||
return
|
||||
updated_acc = Database.get_blackjack_account(view.bj_account["id"])
|
||||
if not (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY):
|
||||
Database.set_bj_devils_deal_active(view.bj_account["id"], False)
|
||||
view.devils_locked = False
|
||||
view._clear_persisted_state()
|
||||
|
||||
@staticmethod
|
||||
def award_xp_and_record(view, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]:
|
||||
duration = max(0.5, time.time() - view.round_start_time)
|
||||
prog_before = view.ctx.refresh_game_progress()
|
||||
opp_levels = [b.ai_level for b in view.bots]
|
||||
|
||||
xp_gained = Progression.calculate_match_xp(
|
||||
player_level=prog_before["level"],
|
||||
opponent_levels=opp_levels,
|
||||
outcome_type=outcome_type,
|
||||
variant_mult=view.cfg["xp_mult"],
|
||||
)
|
||||
|
||||
if won_stat is None:
|
||||
Database.add_game_points(view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained)
|
||||
prog_after = view.ctx.refresh_game_progress()
|
||||
view.ctx.sounds.play("end_battle")
|
||||
new_lvl = prog_after["level"] if prog_after["level"] > prog_before["level"] else None
|
||||
return xp_gained, new_lvl
|
||||
|
||||
old_lvl, new_lvl = view.ctx.record_result(
|
||||
view.variant_key,
|
||||
won=won_stat,
|
||||
duration_sec=duration,
|
||||
points_gained=xp_gained,
|
||||
bj_account_id=view.bj_account["id"],
|
||||
)
|
||||
return xp_gained, (new_lvl if new_lvl > old_lvl else None)
|
||||
|
||||
@staticmethod
|
||||
def format_hand_rank_label(
|
||||
cards, is_split: bool = False, busted: bool = False, folded: bool = False
|
||||
) -> str:
|
||||
val, _ = HandEvaluator.evaluate(cards)
|
||||
if folded:
|
||||
return t("bj_rank_folded", val)
|
||||
if busted or val > 21:
|
||||
return t("bj_rank_busted", val)
|
||||
if HandEvaluator.is_triple_seven(cards):
|
||||
return t("bj_rank_777")
|
||||
if not is_split and HandEvaluator.is_natural_blackjack(cards):
|
||||
return t("bj_rank_natural_bj")
|
||||
if val == 21:
|
||||
return t("bj_rank_split_21") if is_split else t("bj_rank_multi_21", len(cards))
|
||||
return t("bj_rank_points", val, len(cards))
|
||||
|
||||
@staticmethod
|
||||
def collect_showdown_snapshot(view, instant_777_winner: str | None = None) -> list[dict]:
|
||||
snapshot: list[dict] = []
|
||||
d_cards = view.engine.dealer_hand
|
||||
d_val, _ = HandEvaluator.evaluate(d_cards)
|
||||
d_rank = view.engine._hand_rank(d_cards)
|
||||
snapshot.append({
|
||||
"role": "DEALER", "name": "", "hand_no": 0,
|
||||
"card_images": [c.image_filename for c in d_cards],
|
||||
"cards_raw": [[c.suit, c.rank] for c in d_cards],
|
||||
"is_split": False, "busted": d_val > 21, "folded": False,
|
||||
"rank_tuple": list(d_rank),
|
||||
})
|
||||
|
||||
multi_p = len(view.engine.player_hands) > 1
|
||||
for idx, h in enumerate(view.engine.player_hands):
|
||||
hr = view.engine._hand_rank(h.cards, is_split=h.is_split_hand) if h.is_active_in_pot else (0, 0)
|
||||
snapshot.append({
|
||||
"role": "PLAYER", "name": "", "hand_no": (idx + 1) if multi_p else 0,
|
||||
"card_images": [c.image_filename for c in h.cards],
|
||||
"cards_raw": [[c.suit, c.rank] for c in h.cards],
|
||||
"is_split": h.is_split_hand, "busted": h.busted, "folded": h.folded,
|
||||
"rank_tuple": list(hr),
|
||||
})
|
||||
|
||||
for b in view.bots:
|
||||
br = view.engine._hand_rank(b.hand) if b.is_active_in_pot else (0, 0)
|
||||
snapshot.append({
|
||||
"role": "BOT", "name": b.name, "hand_no": 0,
|
||||
"card_images": [c.image_filename for c in b.hand],
|
||||
"cards_raw": [[c.suit, c.rank] for c in b.hand],
|
||||
"is_split": False, "busted": b.busted, "folded": b.folded,
|
||||
"rank_tuple": list(br),
|
||||
})
|
||||
|
||||
if instant_777_winner is not None:
|
||||
for s in snapshot:
|
||||
s["is_winner"] = bool(
|
||||
(instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21])
|
||||
or (s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21])
|
||||
)
|
||||
return snapshot
|
||||
|
||||
contenders = [s for s in snapshot[1:] if not s["busted"] and not s["folded"]]
|
||||
dealer_entry = snapshot[0]
|
||||
if not contenders:
|
||||
dealer_entry["is_winner"] = True
|
||||
for s in snapshot[1:]:
|
||||
s["is_winner"] = False
|
||||
return snapshot
|
||||
|
||||
best_contender = max(tuple(s["rank_tuple"]) for s in contenders)
|
||||
d_rnk = tuple(dealer_entry["rank_tuple"])
|
||||
dealer_entry["is_winner"] = (d_rnk >= best_contender)
|
||||
for s in snapshot[1:]:
|
||||
s["is_winner"] = (
|
||||
d_rnk <= best_contender
|
||||
and not s["busted"]
|
||||
and not s["folded"]
|
||||
and tuple(s["rank_tuple"]) == best_contender
|
||||
)
|
||||
return snapshot
|
||||
|
||||
@classmethod
|
||||
def trigger_instant_777(
|
||||
cls, view, winner_is_player: bool, winning_bot: BlackjackBotSeat | None
|
||||
) -> dict:
|
||||
view.engine.state = "SHOWDOWN"
|
||||
cls.count_all_table_cards(view)
|
||||
pot_total = view.engine.pot
|
||||
total_p_bet = view.engine.total_player_bet
|
||||
snap = cls.collect_showdown_snapshot(
|
||||
view, instant_777_winner="PLAYER" if winner_is_player else winning_bot.name
|
||||
)
|
||||
|
||||
if winner_is_player:
|
||||
payout = pot_total + (total_p_bet if not view.bots else 0)
|
||||
net = payout - total_p_bet
|
||||
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], payout)
|
||||
xp, leveled_to = cls.award_xp_and_record(view, "WIN_777", won_stat=True)
|
||||
cls.resolve_devils_lock(view, "WIN_777")
|
||||
return {
|
||||
"winner_type": "PLAYER", "winner_names": [], "instant_777": "PLAYER",
|
||||
"player_won": True, "player_net": net, "bank_gain": 0, "bot_gains": [],
|
||||
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||
}
|
||||
|
||||
winning_bot.gold += pot_total
|
||||
bot_net = pot_total - winning_bot.bet_in_pot
|
||||
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
||||
cls.resolve_devils_lock(view, "LOSE")
|
||||
return {
|
||||
"winner_type": "BOT", "winner_names": [winning_bot.name], "instant_777": winning_bot.name,
|
||||
"player_won": False, "player_net": -total_p_bet, "bank_gain": 0,
|
||||
"bot_gains": [(winning_bot.name, bot_net)] if bot_net > 0 else [],
|
||||
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def finalize_regular_showdown(cls, view) -> dict:
|
||||
cls.count_all_table_cards(view)
|
||||
res = view.engine.resolve_showdown(view.bots)
|
||||
snap = cls.collect_showdown_snapshot(view, instant_777_winner=None)
|
||||
|
||||
if res["player_payout"] > 0:
|
||||
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], res["player_payout"])
|
||||
|
||||
w_type = res["winner_type"]
|
||||
if w_type == "PLAYER":
|
||||
has_nat = any(
|
||||
h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards)
|
||||
for h in view.engine.player_hands
|
||||
)
|
||||
out_code, player_won_flag = ("WIN_BJ" if has_nat else "WIN"), True
|
||||
xp, leveled_to = cls.award_xp_and_record(view, out_code, won_stat=True)
|
||||
elif w_type == "TIE":
|
||||
out_code, player_won_flag = "TIE", None
|
||||
xp, leveled_to = cls.award_xp_and_record(view, "TIE", won_stat=None)
|
||||
else:
|
||||
out_code, player_won_flag = "LOSE", False
|
||||
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
||||
|
||||
cls.resolve_devils_lock(view, out_code)
|
||||
return {
|
||||
"winner_type": w_type, "winner_names": res["winner_names"], "instant_777": None,
|
||||
"player_won": player_won_flag, "player_net": res["player_net"],
|
||||
"bank_gain": res["bank_gain"], "bot_gains": res["bot_gains"],
|
||||
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def build_localized_popup_data(cls, view, payload: dict) -> dict:
|
||||
w_type = payload["winner_type"]
|
||||
headline = (
|
||||
t("bj_popup_bank_won") if w_type == "BANK"
|
||||
else (t("bj_popup_player_won") if w_type == "PLAYER"
|
||||
else (t("bj_popup_bot_won", ", ".join(payload["winner_names"])) if w_type == "BOT" else t("bj_popup_tie")))
|
||||
)
|
||||
|
||||
showdown_hands = []
|
||||
for s in payload.get("showdown_snapshot", []):
|
||||
cards_obj = [Card(sr[0], sr[1]) for sr in s.get("cards_raw", [])]
|
||||
owner_lbl = (
|
||||
t("bj_showdown_seat_dealer") if s["role"] == "DEALER"
|
||||
else ((t("bj_showdown_seat_you_hand", s["hand_no"]) if s.get("hand_no") else t("bj_showdown_seat_you"))
|
||||
if s["role"] == "PLAYER" else s["name"])
|
||||
)
|
||||
showdown_hands.append({
|
||||
"owner_label": owner_lbl, "is_dealer": (s["role"] == "DEALER"),
|
||||
"is_winner": s.get("is_winner", False), "busted": s.get("busted", False),
|
||||
"folded": s.get("folded", False), "card_images": s.get("card_images", []),
|
||||
"rank_label": cls.format_hand_rank_label(
|
||||
cards_obj, s.get("is_split", False), s.get("busted", False), s.get("folded", False)
|
||||
),
|
||||
"rank_tuple": tuple(s.get("rank_tuple", [0, 0])), "role": s["role"],
|
||||
})
|
||||
|
||||
other_gains = []
|
||||
if payload["bank_gain"] > 0:
|
||||
other_gains.append(t("bj_popup_bank_gain", payload["bank_gain"]))
|
||||
for b_name, b_gain in payload["bot_gains"]:
|
||||
if b_gain > 0:
|
||||
other_gains.append(t("bj_popup_bot_gain", b_name, b_gain))
|
||||
|
||||
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
|
||||
cur_gold = Database.get_blackjack_account(view.bj_account["id"])["gold"]
|
||||
|
||||
return {
|
||||
"headline": headline,
|
||||
"reason_text": cls._build_showdown_reason(payload, showdown_hands),
|
||||
"showdown_hands": showdown_hands,
|
||||
"player_won": payload["player_won"],
|
||||
"player_net": payload["player_net"],
|
||||
"other_gains": other_gains,
|
||||
"xp_gained": payload["xp_gained"],
|
||||
"new_level_title": lvl_str,
|
||||
"can_continue": cur_gold >= GOLD_MIN_TABLE_ENTRY,
|
||||
"can_leave_menu": not view.devils_locked,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _build_showdown_reason(payload: dict, showdown_hands: list[dict]) -> str:
|
||||
if not showdown_hands:
|
||||
return ""
|
||||
inst = payload.get("instant_777")
|
||||
if inst:
|
||||
return t("bj_reason_777_win", t("bj_showdown_seat_you") if inst == "PLAYER" else inst)
|
||||
|
||||
dealer = showdown_hands[0]
|
||||
if not [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]]:
|
||||
return t("bj_reason_all_out")
|
||||
|
||||
winners = [h for h in showdown_hands if h["is_winner"]]
|
||||
if not winners:
|
||||
return ""
|
||||
if dealer["is_winner"] and len(winners) > 1:
|
||||
return t("bj_reason_dealer_tie_push", dealer["rank_label"])
|
||||
|
||||
top_rank = winners[0]["rank_tuple"]
|
||||
winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"]))
|
||||
win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str
|
||||
losers_21 = [
|
||||
h for h in showdown_hands
|
||||
if not h["is_winner"] and not h["busted"] and not h["folded"] and h["rank_tuple"][1] == 21
|
||||
]
|
||||
if top_rank == (3, 21) and losers_21:
|
||||
return t("bj_reason_777_beats_21", win_label)
|
||||
if top_rank == (2, 21) and losers_21:
|
||||
return t("bj_reason_nat_beats_reg21", win_label)
|
||||
|
||||
non_dealer_winners = [w for w in winners if not w["is_dealer"]]
|
||||
if len(non_dealer_winners) > 1:
|
||||
return t("bj_reason_split_pot", non_dealer_winners[0]["rank_label"], winner_names_str)
|
||||
if dealer["busted"] and not dealer["is_winner"]:
|
||||
return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"])
|
||||
|
||||
others_alive = [h for h in showdown_hands if not h["is_winner"] and not h["busted"] and not h["folded"]]
|
||||
runner = max(others_alive, key=lambda x: x["rank_tuple"]) if others_alive else dealer
|
||||
return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], f"{runner['owner_label']}: {runner['rank_label']}")
|
||||
|
|
@ -1,132 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/views/blackjack_stats_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_SIZE_BODY,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from view.widgets.stats_board_widget import StatsBoardWidget
|
||||
|
||||
GAME_FOLDER_ID = "blackjack"
|
||||
|
||||
|
||||
class BlackjackStatsView:
|
||||
"""Rahmenlose Statistik-Ansicht für die einzelnen Blackjack-Goldbeutel."""
|
||||
|
||||
def __init__(self, context, on_back_to_bj_menu):
|
||||
self.ctx = context
|
||||
self.on_back_to_bj_menu = on_back_to_bj_menu
|
||||
self._photo_refs: list = []
|
||||
|
||||
def show(self, selected_acc_id: int | None = None):
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self._photo_refs.clear()
|
||||
|
||||
pid = self.ctx.profile["id"]
|
||||
accounts = Database.get_blackjack_accounts(pid)
|
||||
if not accounts:
|
||||
self.on_back_to_bj_menu(None)
|
||||
return
|
||||
|
||||
active_acc = accounts[0]
|
||||
if selected_acc_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == selected_acc_id:
|
||||
active_acc = a
|
||||
break
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("bj_stats_view_topbar"),
|
||||
on_game_menu=lambda: self.on_back_to_bj_menu(active_acc["id"]),
|
||||
extra_right_text=t("bj_header_gold", active_acc["account_name"], active_acc["gold"]),
|
||||
on_lang_refresh=lambda: self.show(active_acc["id"]),
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
acc_btns: list[tuple[ImageButton, int]] = []
|
||||
for acc in accounts:
|
||||
is_sel = (acc["id"] == active_acc["id"])
|
||||
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
|
||||
b = ImageButton(
|
||||
cv,
|
||||
btn_lbl,
|
||||
btn_fire if is_sel else btn_norm,
|
||||
btn_fire if is_sel else btn_purp,
|
||||
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=180,
|
||||
height=38,
|
||||
style="fire" if is_sel else "amethyst",
|
||||
)
|
||||
acc_btns.append((b, b.pixel_width))
|
||||
|
||||
bj_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
|
||||
bj_filter_map = {t("bj_filter_all_tables"): None}
|
||||
for v in bj_variants:
|
||||
bj_filter_map[v["translated_name"]] = v["id"]
|
||||
|
||||
board = StatsBoardWidget(
|
||||
cv,
|
||||
title=t("bj_stats_acc_title", active_acc["account_name"]),
|
||||
filter_map=bj_filter_map,
|
||||
fetch_callback=lambda vid: Database.get_bj_account_stats_overview(active_acc["id"], vid),
|
||||
)
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
pad_x = max(56, int(w * 0.065))
|
||||
content_w = min(1060, w - 2 * pad_x)
|
||||
left_edge = (w - content_w) // 2
|
||||
|
||||
sel_h = 114
|
||||
sel_top = max(24, int(h * 0.05))
|
||||
sel_cy = sel_top + sel_h // 2
|
||||
|
||||
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
|
||||
if sel_box:
|
||||
self._photo_refs.append(sel_box)
|
||||
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
|
||||
|
||||
lbl_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_stats_select_acc_lbl"),
|
||||
size_px=FONT_SIZE_BODY + 2,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(lbl_ph)
|
||||
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
|
||||
|
||||
cur_bx = left_edge + 26
|
||||
for b_wgt, bw in acc_btns:
|
||||
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
|
||||
cur_bx += bw + 10
|
||||
|
||||
board_top = sel_top + sel_h + 22
|
||||
board_h = max(238, min(270, h - board_top - 32))
|
||||
cv.create_window(
|
||||
w // 2,
|
||||
board_top + board_h // 2,
|
||||
window=board,
|
||||
width=content_w,
|
||||
height=board_h,
|
||||
anchor="center",
|
||||
tags="fg",
|
||||
)
|
||||
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
|
||||
|
||||
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(600, cv.winfo_height()))
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,244 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/blackjack/views/blackjack_turn_driver.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
||||
from games.blackjack.models.hand_evaluator import HandEvaluator
|
||||
from games.blackjack.views.blackjack_showdown_presenter import BlackjackShowdownPresenter
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import BJ_BOT_TURN_DELAY_MS
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
STEP_MITGEHEN = "MITGEHEN"
|
||||
STEP_ZIEHEN = "ZIEHEN"
|
||||
STEP_ERHOEHEN = "ERHOEHEN"
|
||||
|
||||
|
||||
class BlackjackTurnDriver:
|
||||
"""Steuert die Aktions-Buttons des Spielers und die KI-Zugschleife der Bots am Blackjack-Tisch."""
|
||||
|
||||
@staticmethod
|
||||
def render_tree_step(view) -> None:
|
||||
view.bj_account = Database.get_blackjack_account(view.bj_account["id"])
|
||||
wallet = view.bj_account["gold"]
|
||||
hand = view.engine.player_hands[view.active_hand_idx]
|
||||
|
||||
btn_norm = view.ctx.assets.raw_btn_default
|
||||
btn_purp = view.ctx.assets.raw_btn_purple
|
||||
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
|
||||
primary_btns: list[ImageButton] = []
|
||||
overflow_btns: list[ImageButton] = []
|
||||
|
||||
if view.turn_step == STEP_MITGEHEN:
|
||||
to_call = min(wallet, max(0, view.engine.highest_bet - hand.bet_in_pot))
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_tree_btn_call_yes", to_call),
|
||||
btn_fire, btn_fire, lambda: view._on_step1_call_yes(to_call),
|
||||
sound_mgr=view.ctx.sounds, width=162, height=30, style="fire",
|
||||
hover_text=lambda: t("bj_tip_call_yes"),
|
||||
)
|
||||
)
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_tree_btn_call_no_lose"),
|
||||
btn_norm, btn_purp, view._on_fold_hand,
|
||||
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
|
||||
hover_text=lambda: t("bj_tip_fold"),
|
||||
)
|
||||
)
|
||||
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||
return
|
||||
|
||||
if view.turn_step == STEP_ZIEHEN:
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_tree_btn_draw_yes"),
|
||||
btn_fire, btn_fire, view._on_step2_draw_yes,
|
||||
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
|
||||
hover_text=lambda: t("bj_tip_draw_yes"),
|
||||
)
|
||||
)
|
||||
if view.engine.can_double_down(view.active_hand_idx, wallet):
|
||||
dd_cost = view.engine.get_double_down_cost(view.active_hand_idx)
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_double_btn", dd_cost),
|
||||
btn_norm, btn_purp, view._on_step2_double_down,
|
||||
sound_mgr=view.ctx.sounds, width=132, height=30,
|
||||
style="amethyst", hover_text=lambda: t("bj_tip_double"),
|
||||
)
|
||||
)
|
||||
if view.engine.can_split_hand(view.active_hand_idx, wallet):
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_split_btn", view.engine.highest_bet),
|
||||
btn_norm, btn_purp, view._on_step2_split,
|
||||
sound_mgr=view.ctx.sounds, width=124, height=30,
|
||||
style="amethyst", hover_text=lambda: t("bj_tip_split"),
|
||||
)
|
||||
)
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_tree_btn_draw_no"),
|
||||
btn_norm, btn_purp, view._on_step2_draw_no,
|
||||
sound_mgr=None, width=134, height=30, style="amethyst",
|
||||
hover_text=lambda: t("bj_tip_draw_no"),
|
||||
)
|
||||
)
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_fold_btn"),
|
||||
btn_norm, btn_purp, view._on_fold_hand,
|
||||
sound_mgr=view.ctx.sounds, width=110, height=30, style="amethyst",
|
||||
hover_text=lambda: t("bj_tip_fold"),
|
||||
)
|
||||
)
|
||||
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||
return
|
||||
|
||||
if view.turn_step == STEP_ERHOEHEN:
|
||||
for chip in [c for c in view._get_current_level_chips() if wallet >= c]:
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, f"+{chip}g",
|
||||
btn_fire, btn_fire, lambda c=chip: view._on_step3_raise_yes(c),
|
||||
sound_mgr=view.ctx.sounds, width=76, height=30, style="fire",
|
||||
hover_text=lambda: t("bj_tip_raise_chip"),
|
||||
)
|
||||
)
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("bj_tree_btn_raise_no"),
|
||||
btn_norm, btn_purp, view._finish_current_hand_turn,
|
||||
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
|
||||
hover_text=lambda: t("bj_tip_raise_no"),
|
||||
)
|
||||
)
|
||||
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||
|
||||
@classmethod
|
||||
def start_bots_cycle(cls, view) -> None:
|
||||
view._set_bottom_buttons([])
|
||||
if not view.bots or not view.engine.any_contender_alive(view.bots):
|
||||
view._on_table_pass_completed()
|
||||
return
|
||||
view.active_bot_idx = 0
|
||||
view._persist_state()
|
||||
cls.step_next_bot(view)
|
||||
|
||||
@classmethod
|
||||
def step_next_bot(cls, view) -> None:
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
while view.active_bot_idx < len(view.bots):
|
||||
bot = view.bots[view.active_bot_idx]
|
||||
if bot.is_active_in_pot and (
|
||||
not view.settle_only_mode
|
||||
or (bot.gold > 0 and bot.bet_in_pot < view.engine.highest_bet)
|
||||
):
|
||||
break
|
||||
view.active_bot_idx += 1
|
||||
|
||||
if view.active_bot_idx >= len(view.bots):
|
||||
view.active_bot_idx = -1
|
||||
view._persist_state()
|
||||
view._on_table_pass_completed()
|
||||
return
|
||||
|
||||
bot = view.bots[view.active_bot_idx]
|
||||
view._persist_state()
|
||||
view._render_table(False, False)
|
||||
view._turn_job = view.ctx.root.after(
|
||||
BJ_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_action(view, b)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute_bot_action(cls, view, bot: BlackjackBotSeat) -> None:
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
upcard = view.engine.dealer_hand[0]
|
||||
dyn_chips = view._get_current_level_chips()
|
||||
rem_cards = view.engine.deck.remaining()
|
||||
to_call = min(bot.gold, max(0, view.engine.highest_bet - bot.bet_in_pot))
|
||||
|
||||
if to_call > 0:
|
||||
if not view.bot_ai.decide_step1_mitgehen(
|
||||
bot, view.engine.highest_bet, upcard, rem_cards
|
||||
):
|
||||
bot.folded = bot.cards_locked = True
|
||||
bot.status_text = t("bj_bot_action_fold")
|
||||
cls._finish_bot_step(view)
|
||||
return
|
||||
view.ctx.sounds.play("click")
|
||||
view.engine.bot_add_gold_to_pot(bot, to_call)
|
||||
if view.settle_only_mode:
|
||||
bot.status_text = t("bj_bot_action_call", to_call)
|
||||
cls._finish_bot_step(view)
|
||||
return
|
||||
|
||||
drew_card = False
|
||||
if not bot.cards_locked and not bot.doubled:
|
||||
if view.bot_ai.wants_double_down(
|
||||
bot, upcard, view.engine.highest_bet, rem_cards
|
||||
):
|
||||
dd_cost = (
|
||||
max(view.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot
|
||||
)
|
||||
paid = view.engine.bot_add_gold_to_pot(bot, dd_cost)
|
||||
view.ctx.sounds.play("click")
|
||||
view.engine.bot_draw_card(bot)
|
||||
bot.doubled = bot.cards_locked = True
|
||||
if HandEvaluator.is_triple_seven(bot.hand):
|
||||
view._conclude_with_payload(
|
||||
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
|
||||
)
|
||||
return
|
||||
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||
bot.status_text = (
|
||||
t("bj_bot_action_bust", b_val)
|
||||
if bot.busted
|
||||
else t("bj_bot_action_double", paid)
|
||||
)
|
||||
cls._finish_bot_step(view)
|
||||
return
|
||||
|
||||
if view.bot_ai.decide_step2_ziehen(bot, upcard, rem_cards):
|
||||
view.ctx.sounds.play("click")
|
||||
view.engine.bot_draw_card(bot)
|
||||
drew_card = True
|
||||
if HandEvaluator.is_triple_seven(bot.hand):
|
||||
view._conclude_with_payload(
|
||||
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
|
||||
)
|
||||
return
|
||||
if bot.busted:
|
||||
b_val, _ = HandEvaluator.evaluate(bot.hand)
|
||||
bot.status_text = t("bj_bot_action_bust", b_val)
|
||||
cls._finish_bot_step(view)
|
||||
return
|
||||
|
||||
raise_amt = view.bot_ai.decide_step3_erhoehen(
|
||||
bot, dyn_chips, rem_cards, upcard
|
||||
)
|
||||
if raise_amt > 0:
|
||||
view.ctx.sounds.play("click")
|
||||
view.engine.bot_add_gold_to_pot(bot, raise_amt)
|
||||
bot.status_text = t("bj_bot_action_bet", raise_amt)
|
||||
elif drew_card:
|
||||
bot.status_text = t("bj_bot_action_hit", len(bot.hand))
|
||||
elif to_call > 0:
|
||||
bot.status_text = t("bj_bot_action_call", to_call)
|
||||
else:
|
||||
bot.status_text = t("bj_bot_action_ready", len(bot.hand))
|
||||
cls._finish_bot_step(view)
|
||||
|
||||
@classmethod
|
||||
def _finish_bot_step(cls, view) -> None:
|
||||
view.active_bot_idx += 1
|
||||
view._persist_state()
|
||||
view._render_table(False, False)
|
||||
view._turn_job = view.ctx.root.after(
|
||||
BJ_BOT_TURN_DELAY_MS, lambda: cls.step_next_bot(view)
|
||||
)
|
||||
|
|
@ -2,53 +2,30 @@
|
|||
# games/blackjack/views/round_result_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from resources.code_res.game_constants import (
|
||||
BG_COLOR,
|
||||
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,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
SUBTLE_BORDER,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.modal_veil import ModalVeil
|
||||
from view.widgets.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
|
||||
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
|
||||
|
||||
|
||||
class BlackjackResultDialog(tk.Canvas):
|
||||
"""
|
||||
Rahmenloses Gothic-Showdown-Overlay für Blackjack (ohne eingebettetes GIF),
|
||||
immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
assets,
|
||||
sounds,
|
||||
result_data: dict,
|
||||
on_next_round,
|
||||
on_back_to_menu,
|
||||
):
|
||||
GothDropdown.close_any_open_popup()
|
||||
top_root = parent.winfo_toplevel()
|
||||
class BlackjackResultDialog(CasinoResultDialogBase):
|
||||
"""Gothic-Showdown-Overlay für Blackjack auf Basis von CasinoResultDialogBase."""
|
||||
|
||||
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
|
||||
hands_list = result_data.get("showdown_hands", [])
|
||||
cols = min(3, max(1, len(hands_list)))
|
||||
rows = (len(hands_list) + 2) // 3 if hands_list else 0
|
||||
|
||||
extra_lines = len(result_data.get("other_gains", []))
|
||||
|
||||
dlg_w = max(560, min(830, cols * 250 + 64))
|
||||
dlg_h = (
|
||||
58
|
||||
|
|
@ -58,65 +35,9 @@ class BlackjackResultDialog(tk.Canvas):
|
|||
+ (24 if result_data.get("new_level_title") else 0)
|
||||
+ 62
|
||||
)
|
||||
try:
|
||||
max_h = max(420, top_root.winfo_height() - 60)
|
||||
dlg_h = min(dlg_h, max_h)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
super().__init__(
|
||||
top_root,
|
||||
width=dlg_w,
|
||||
height=dlg_h,
|
||||
bg=BG_COLOR,
|
||||
bd=0,
|
||||
highlightthickness=0,
|
||||
)
|
||||
self.assets = assets
|
||||
self.sounds = sounds
|
||||
self.data = result_data
|
||||
self.on_next_round = on_next_round
|
||||
self.on_back_to_menu = on_back_to_menu
|
||||
|
||||
self._dlg_w = dlg_w
|
||||
self._dlg_h = dlg_h
|
||||
self._photo_refs: list = []
|
||||
|
||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self._build_scene()
|
||||
self._veil = ModalVeil(top_root, assets, modal_widget=self)
|
||||
|
||||
def _build_scene(self):
|
||||
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")
|
||||
|
||||
cur_y = 26
|
||||
|
||||
p_won = self.data.get("player_won")
|
||||
hl_col = (
|
||||
FONT_COLOR_TITLE_MAIN
|
||||
if p_won is True
|
||||
else (FONT_COLOR_BODY_MUTED if p_won is None else FONT_COLOR_STATUS_LOSS)
|
||||
)
|
||||
hl_ph = self.assets.get_goth_text_photo(
|
||||
self.data["headline"], FONT_SIZE_TITLE_LG - 4, hl_col, max_width=w - 60
|
||||
)
|
||||
self._photo_refs.append(hl_ph)
|
||||
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
|
||||
cur_y += hl_ph.height() + 8
|
||||
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||
|
||||
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||
reason_txt = self.data.get("reason_text", "")
|
||||
if reason_txt:
|
||||
r_ph = self.assets.get_goth_text_photo(
|
||||
|
|
@ -133,163 +54,77 @@ class BlackjackResultDialog(tk.Canvas):
|
|||
cur_y += rb_h + 8
|
||||
|
||||
hands_list = self.data.get("showdown_hands", [])
|
||||
if hands_list:
|
||||
sec_ph = self.assets.get_goth_text_photo(
|
||||
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||
)
|
||||
self._photo_refs.append(sec_ph)
|
||||
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
|
||||
cur_y += 22
|
||||
if not hands_list:
|
||||
return cur_y
|
||||
|
||||
max_cols = 3
|
||||
rows = (len(hands_list) + max_cols - 1) // max_cols
|
||||
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
|
||||
seat_h = 128 if rows > 1 else 136
|
||||
|
||||
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
|
||||
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
|
||||
if win_box:
|
||||
self._photo_refs.append(win_box)
|
||||
if std_box:
|
||||
self._photo_refs.append(std_box)
|
||||
|
||||
for idx, entry in enumerate(hands_list):
|
||||
r_i, c_i = divmod(idx, max_cols)
|
||||
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
|
||||
row_total_w = in_row * seat_w + (in_row - 1) * 10
|
||||
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
|
||||
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
|
||||
|
||||
is_win = entry.get("is_winner", False)
|
||||
is_dead = entry.get("busted", False) or entry.get("folded", False)
|
||||
|
||||
frame_ph = win_box if is_win else std_box
|
||||
if frame_ph:
|
||||
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||
|
||||
o_col = (
|
||||
FONT_COLOR_TITLE_MAIN
|
||||
if is_win
|
||||
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
|
||||
)
|
||||
o_ph = self.assets.get_goth_text_photo(
|
||||
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
|
||||
)
|
||||
self._photo_refs.append(o_ph)
|
||||
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
|
||||
|
||||
c_imgs = entry.get("card_images", [])
|
||||
c_photos = []
|
||||
for img_name in c_imgs:
|
||||
ph = self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)
|
||||
if ph:
|
||||
self._photo_refs.append(ph)
|
||||
c_photos.append(ph)
|
||||
|
||||
if c_photos:
|
||||
cw_c, ch_c = SHOWDOWN_MINI_CARD_SIZE
|
||||
n_c = len(c_photos)
|
||||
step = 24
|
||||
if n_c > 1 and (cw_c + (n_c - 1) * step) > (seat_w - 28):
|
||||
step = max(14, (seat_w - 28 - cw_c) // (n_c - 1))
|
||||
fan_w = cw_c + (n_c - 1) * step if n_c > 1 else cw_c
|
||||
start_cx = sx - fan_w // 2
|
||||
card_top = sy - ch_c // 2 + 2
|
||||
for ci, cph in enumerate(c_photos):
|
||||
self.create_image(start_cx + ci * step, card_top, image=cph, anchor="nw")
|
||||
|
||||
rk_col = (
|
||||
FONT_COLOR_STATUS_WIN
|
||||
if is_win
|
||||
else (FONT_COLOR_STATUS_LOSS if is_dead else FONT_COLOR_BODY_DEFAULT)
|
||||
)
|
||||
rk_ph = self.assets.get_goth_text_photo(
|
||||
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
|
||||
)
|
||||
self._photo_refs.append(rk_ph)
|
||||
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
|
||||
|
||||
cur_y += rows * (seat_h + 6) + 6
|
||||
|
||||
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
|
||||
cur_y += 10
|
||||
|
||||
p_net = self.data["player_net"]
|
||||
if p_net > 0:
|
||||
own_txt, own_col = t("bj_popup_your_gain", p_net), FONT_COLOR_STATUS_WIN
|
||||
elif p_net < 0:
|
||||
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), FONT_COLOR_STATUS_LOSS
|
||||
else:
|
||||
own_txt, own_col = t("bj_popup_your_even"), FONT_COLOR_BODY_DEFAULT
|
||||
|
||||
own_ph = self.assets.get_goth_text_photo(own_txt, FONT_SIZE_BODY + 2, own_col, max_width=w - 72)
|
||||
self._photo_refs.append(own_ph)
|
||||
self.create_image(cx, cur_y + own_ph.height() // 2, image=own_ph, anchor="center")
|
||||
cur_y += own_ph.height() + 2
|
||||
|
||||
other_gains = self.data.get("other_gains", [])
|
||||
if other_gains:
|
||||
joined_others = " • ".join(other_gains)
|
||||
oth_ph = self.assets.get_goth_text_photo(
|
||||
joined_others, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=w - 72
|
||||
)
|
||||
self._photo_refs.append(oth_ph)
|
||||
self.create_image(cx, cur_y + oth_ph.height() // 2, image=oth_ph, anchor="center")
|
||||
cur_y += oth_ph.height() + 2
|
||||
|
||||
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,
|
||||
FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB,
|
||||
max_width=w - 72,
|
||||
sec_ph = self.assets.get_goth_text_photo(
|
||||
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||
)
|
||||
self._photo_refs.append(xp_ph)
|
||||
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
|
||||
self._photo_refs.append(sec_ph)
|
||||
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
|
||||
cur_y += 22
|
||||
|
||||
btn_norm = self.assets.raw_btn_default
|
||||
btn_purp = self.assets.raw_btn_purple
|
||||
btn_fire = self.assets.raw_btn_fire or btn_purp
|
||||
max_cols = 3
|
||||
rows = (len(hands_list) + max_cols - 1) // max_cols
|
||||
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
|
||||
seat_h = 128 if rows > 1 else 136
|
||||
|
||||
btn_y = h - 34
|
||||
can_next = self.data.get("can_continue", True)
|
||||
can_menu = self.data.get("can_leave_menu", True)
|
||||
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
|
||||
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
|
||||
if win_box:
|
||||
self._photo_refs.append(win_box)
|
||||
if std_box:
|
||||
self._photo_refs.append(std_box)
|
||||
|
||||
if can_next and can_menu:
|
||||
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"
|
||||
for idx, entry in enumerate(hands_list):
|
||||
r_i, c_i = divmod(idx, max_cols)
|
||||
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
|
||||
row_total_w = in_row * seat_w + (in_row - 1) * 10
|
||||
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
|
||||
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
|
||||
|
||||
is_win = entry.get("is_winner", False)
|
||||
is_dead = entry.get("busted", False) or entry.get("folded", False)
|
||||
|
||||
frame_ph = win_box if is_win else std_box
|
||||
if frame_ph:
|
||||
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||
|
||||
o_col = (
|
||||
FONT_COLOR_TITLE_MAIN if is_win
|
||||
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
|
||||
)
|
||||
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"
|
||||
o_ph = self.assets.get_goth_text_photo(
|
||||
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
|
||||
)
|
||||
self.create_window(42, btn_y, window=b_next, anchor="w")
|
||||
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
|
||||
elif can_next:
|
||||
b_next = ImageButton(
|
||||
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
|
||||
self._handle_next, sound_mgr=self.sounds, width=215, height=38, style="fire"
|
||||
self._photo_refs.append(o_ph)
|
||||
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
|
||||
|
||||
c_photos = [
|
||||
ph for img_name in entry.get("card_images", [])
|
||||
if (ph := self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)) is not None
|
||||
]
|
||||
self._photo_refs.extend(c_photos)
|
||||
|
||||
if c_photos:
|
||||
cw_c, ch_c = SHOWDOWN_MINI_CARD_SIZE
|
||||
n_c = len(c_photos)
|
||||
step = 24
|
||||
if n_c > 1 and (cw_c + (n_c - 1) * step) > (seat_w - 28):
|
||||
step = max(14, (seat_w - 28 - cw_c) // (n_c - 1))
|
||||
fan_w = cw_c + (n_c - 1) * step if n_c > 1 else cw_c
|
||||
start_cx, card_top = sx - fan_w // 2, sy - ch_c // 2 + 2
|
||||
for ci, cph in enumerate(c_photos):
|
||||
self.create_image(start_cx + ci * step, card_top, image=cph, anchor="nw")
|
||||
|
||||
rk_col = (
|
||||
FONT_COLOR_STATUS_WIN if is_win
|
||||
else (FONT_COLOR_STATUS_LOSS if is_dead else FONT_COLOR_BODY_DEFAULT)
|
||||
)
|
||||
self.create_window(cx, btn_y, window=b_next, anchor="center")
|
||||
elif can_menu:
|
||||
b_menu = ImageButton(
|
||||
self, t("bj_popup_to_menu_btn"), btn_fire, btn_fire,
|
||||
self._handle_menu, sound_mgr=self.sounds, width=195, height=38, style="fire"
|
||||
rk_ph = self.assets.get_goth_text_photo(
|
||||
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
|
||||
)
|
||||
self.create_window(cx, btn_y, window=b_menu, anchor="center")
|
||||
self._photo_refs.append(rk_ph)
|
||||
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
|
||||
|
||||
def close_dialog(self):
|
||||
self._veil.release()
|
||||
self._photo_refs.clear()
|
||||
if self.winfo_exists():
|
||||
self.destroy()
|
||||
|
||||
def _handle_next(self):
|
||||
self.close_dialog()
|
||||
self.on_next_round()
|
||||
|
||||
def _handle_menu(self):
|
||||
self.close_dialog()
|
||||
self.on_back_to_menu()
|
||||
return cur_y + rows * (seat_h + 6) + 6
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/models/watten_ai.py
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
from games.party.watten.models.watten_engine import WattenEngine, WattenSeat
|
||||
from games.party.watten.models.watten_rules import (
|
||||
NATURAL_STRENGTH,
|
||||
WATTEN_RANKS_32,
|
||||
evaluate_trick_winner,
|
||||
is_guade,
|
||||
is_kritische,
|
||||
is_schlag,
|
||||
is_trump_card,
|
||||
trick_card_power,
|
||||
)
|
||||
from models.cards.bavarian_deck import BavarianCard
|
||||
from resources.code_res.game_constants import BAVARIAN_SUITS
|
||||
|
||||
|
||||
class WattenBotAI:
|
||||
"""2v2-Team-KI (Stufen 0..6) für Oberbayerisches Watten."""
|
||||
|
||||
@staticmethod
|
||||
def _hand_raw_strength(hand: list[BavarianCard]) -> float:
|
||||
pts = 0.0
|
||||
rank_counts: dict[str, int] = {}
|
||||
suit_counts: dict[str, int] = {}
|
||||
for c in hand:
|
||||
if is_kritische(c):
|
||||
pts += 3.2
|
||||
elif c.rank == "A":
|
||||
pts += 1.2
|
||||
rank_counts[c.rank] = rank_counts.get(c.rank, 0) + 1
|
||||
suit_counts[c.suit] = suit_counts.get(c.suit, 0) + 1
|
||||
pts += max(rank_counts.values(), default=0) * 1.1
|
||||
pts += max(suit_counts.values(), default=0) * 0.8
|
||||
return pts
|
||||
|
||||
@classmethod
|
||||
def should_ask_schoenere(
|
||||
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||
) -> bool:
|
||||
r = rng or random
|
||||
if bot.ai_level == 0:
|
||||
return r.random() < 0.20
|
||||
return cls._hand_raw_strength(bot.hand) < 4.3 and r.random() < 0.75
|
||||
|
||||
@classmethod
|
||||
def should_accept_schoenere(
|
||||
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||
) -> bool:
|
||||
r = rng or random
|
||||
if bot.ai_level == 0:
|
||||
return r.random() < 0.50
|
||||
# Geber stimmt nur zu, wenn seine eigene Hand ebenfalls schwach ist
|
||||
return cls._hand_raw_strength(bot.hand) < 5.0
|
||||
|
||||
@classmethod
|
||||
def choose_schlag(
|
||||
cls, bot: WattenSeat, rng: random.Random | None = None
|
||||
) -> str:
|
||||
r = rng or random
|
||||
if bot.ai_level == 0:
|
||||
return r.choice(WATTEN_RANKS_32)
|
||||
|
||||
scores: dict[str, float] = {rk: 0.0 for rk in WATTEN_RANKS_32}
|
||||
for card in bot.hand:
|
||||
if is_kritische(card):
|
||||
continue
|
||||
scores[card.rank] += 3.0
|
||||
# Hohe Beikarten derselben Farbe machen eine potenzielle Guade wahrscheinlicher
|
||||
same_suit = sum(1 for x in bot.hand if x.suit == card.suit)
|
||||
scores[card.rank] += same_suit * 0.35
|
||||
|
||||
ranked = sorted(
|
||||
WATTEN_RANKS_32,
|
||||
key=lambda rk: (scores[rk], r.random()),
|
||||
reverse=True,
|
||||
)
|
||||
if bot.ai_level <= 2 and r.random() < 0.25 and len(ranked) > 1:
|
||||
return ranked[1]
|
||||
return ranked[0]
|
||||
|
||||
@classmethod
|
||||
def choose_trumpf(
|
||||
cls,
|
||||
bot: WattenSeat,
|
||||
schlag_rank: str,
|
||||
rng: random.Random | None = None,
|
||||
) -> str:
|
||||
r = rng or random
|
||||
if bot.ai_level == 0:
|
||||
return r.choice(BAVARIAN_SUITS)
|
||||
|
||||
scores: dict[str, float] = {s: 0.0 for s in BAVARIAN_SUITS}
|
||||
for card in bot.hand:
|
||||
if is_kritische(card):
|
||||
continue
|
||||
if card.rank == schlag_rank:
|
||||
# Hält der Geber diese Karte selbst -> durch Wahl dieser Farbe hat er sofort die GUADE!
|
||||
scores[card.suit] += 4.8
|
||||
else:
|
||||
scores[card.suit] += 1.6 + NATURAL_STRENGTH[card.rank] * 0.15
|
||||
|
||||
ranked = sorted(
|
||||
BAVARIAN_SUITS,
|
||||
key=lambda s: (scores[s], r.random()),
|
||||
reverse=True,
|
||||
)
|
||||
return ranked[0]
|
||||
|
||||
@staticmethod
|
||||
def _post_ansage_hand_power(engine: WattenEngine, bot: WattenSeat) -> float:
|
||||
sr, ts = engine.schlag_rank, engine.trump_suit
|
||||
power = 0.0
|
||||
for c in bot.hand:
|
||||
if is_kritische(c):
|
||||
power += 2.2
|
||||
elif is_guade(c, sr, ts):
|
||||
power += 2.0
|
||||
elif is_schlag(c, sr, ts):
|
||||
power += 1.5
|
||||
elif ts and c.suit == ts:
|
||||
power += 0.95 + (0.25 if c.rank == "A" else 0.0)
|
||||
elif c.rank == "A":
|
||||
power += 0.55
|
||||
return power
|
||||
|
||||
@classmethod
|
||||
def should_ausschaffen(
|
||||
cls,
|
||||
engine: WattenEngine,
|
||||
bot: WattenSeat,
|
||||
rng: random.Random | None = None,
|
||||
) -> bool:
|
||||
if not engine.can_seat_ausschaffen(bot.seat_id):
|
||||
return False
|
||||
r = rng or random
|
||||
lvl = bot.ai_level
|
||||
if lvl == 0:
|
||||
return r.random() < 0.12
|
||||
|
||||
my_team = bot.team_id
|
||||
my_tricks = engine.team_tricks[my_team]
|
||||
opp_tricks = engine.team_tricks[1 - my_team]
|
||||
hand_pow = cls._post_ansage_hand_power(engine, bot)
|
||||
effective = hand_pow + my_tricks * 1.45 - opp_tricks * 1.15
|
||||
|
||||
# Gelegentlicher Wirtshaus-Bluff auf höheren KI-Stufen!
|
||||
if lvl >= 4 and my_tricks >= 1 and r.random() < 0.10:
|
||||
return True
|
||||
|
||||
threshold = 3.55 if engine.current_stake == 2 else 4.25
|
||||
return effective >= threshold and r.random() < (0.45 + lvl * 0.07)
|
||||
|
||||
@classmethod
|
||||
def should_hold_ausschaffen(
|
||||
cls,
|
||||
engine: WattenEngine,
|
||||
bot: WattenSeat,
|
||||
rng: random.Random | None = None,
|
||||
) -> bool:
|
||||
r = rng or random
|
||||
my_team = bot.team_id
|
||||
opp_team = 1 - my_team
|
||||
|
||||
# Wenn der Gegner durch Weglaufen ohnehin den Satz (>= 11) gewinnen würde -> IMMER halten!
|
||||
if engine.team_points[opp_team] + engine.current_stake >= 11:
|
||||
return True
|
||||
|
||||
partner_id = (bot.seat_id + 2) % 4
|
||||
# Fair: Bot kennt seine eigene Hand + bisherige Stiche (+ auf hohen Levels grobe Einschätzung)
|
||||
own_pow = cls._post_ansage_hand_power(engine, bot)
|
||||
my_tricks = engine.team_tricks[my_team]
|
||||
opp_tricks = engine.team_tricks[opp_team]
|
||||
|
||||
score = own_pow + my_tricks * 1.5 - opp_tricks * 1.0
|
||||
if bot.ai_level >= 5:
|
||||
# Leichte Heuristik ob Partner Ansager/Geber war
|
||||
if partner_id in (engine.ansager_seat, engine.dealer_seat):
|
||||
score += 0.55
|
||||
return score >= 2.25 or (r.random() < 0.22)
|
||||
|
||||
@classmethod
|
||||
def choose_card(
|
||||
cls,
|
||||
engine: WattenEngine,
|
||||
bot: WattenSeat,
|
||||
rng: random.Random | None = None,
|
||||
) -> BavarianCard:
|
||||
legal = engine.get_playable_cards(bot.seat_id)
|
||||
assert legal, "Bot muss mindestens 1 spielbare Karte haben"
|
||||
if len(legal) == 1:
|
||||
return legal[0]
|
||||
|
||||
r = rng or random
|
||||
lvl = bot.ai_level
|
||||
sr, ts = engine.schlag_rank or "O", engine.trump_suit or "H"
|
||||
|
||||
if lvl == 0 or (lvl <= 2 and r.random() < 0.25):
|
||||
return r.choice(legal)
|
||||
|
||||
trick = engine.current_trick
|
||||
# 1. Ausspiel (erster im Stich)
|
||||
if not trick:
|
||||
# Ansager im 1. Stich mit Guade/Schlag + weiteren Trümpfen -> Trümpfe ziehen!
|
||||
if engine.trick_index == 0 and bot.seat_id == engine.ansager_seat:
|
||||
pulls = [
|
||||
c for c in legal if is_guade(c, sr, ts) or is_schlag(c, sr, ts)
|
||||
]
|
||||
trumps_total = sum(1 for c in bot.hand if is_trump_card(c, sr, ts))
|
||||
if pulls and trumps_total >= 2:
|
||||
return pulls[0]
|
||||
|
||||
# Starke sichere Karte (Kritische / Ass) oder kleinste Fehlfarbe anspielen
|
||||
krits = [c for c in legal if is_kritische(c)]
|
||||
if krits and (engine.team_tricks[bot.team_id] == 2 or lvl >= 4):
|
||||
return krits[0]
|
||||
|
||||
aces = [c for c in legal if c.rank == "A" and not is_trump_card(c, sr, ts)]
|
||||
if aces:
|
||||
return aces[0]
|
||||
|
||||
return min(
|
||||
legal,
|
||||
key=lambda c: (
|
||||
1 if is_trump_card(c, sr, ts) else 0,
|
||||
NATURAL_STRENGTH[c.rank],
|
||||
),
|
||||
)
|
||||
|
||||
# 2. Zugeben / Stechen im laufenden Stich
|
||||
cur_winner = evaluate_trick_winner(trick, sr, ts)
|
||||
partner_winning = engine.team_of(cur_winner) == bot.team_id
|
||||
led_suit = trick[0][1].suit
|
||||
|
||||
# Hält der Partner den Stich bereits (besonders als Letzter am Stich oder mit hohem Trumpf) -> kleinste Karte abwerfen!
|
||||
cur_best_pow = max(
|
||||
trick_card_power(c, led_suit, i, sr, ts) for i, (_s, c) in enumerate(trick)
|
||||
)
|
||||
if partner_winning and (len(trick) == 3 or cur_best_pow[0] >= 96):
|
||||
return min(
|
||||
legal,
|
||||
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||
)
|
||||
|
||||
# Sonst: Günstigste Karte suchen, die den Stich aktuell erobert!
|
||||
winning_cards = [
|
||||
c
|
||||
for c in legal
|
||||
if trick_card_power(c, led_suit, len(trick), sr, ts) > cur_best_pow
|
||||
]
|
||||
if winning_cards:
|
||||
return min(
|
||||
winning_cards,
|
||||
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||
)
|
||||
|
||||
# Kann nicht überstechen -> wertloseste Karte abwerfen
|
||||
return min(
|
||||
legal,
|
||||
key=lambda c: trick_card_power(c, led_suit, len(trick), sr, ts),
|
||||
)
|
||||
|
|
@ -0,0 +1,344 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/models/watten_engine.py
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import random
|
||||
|
||||
from games.party.watten.models.watten_rules import (
|
||||
WATTEN_RANKS_32,
|
||||
evaluate_trick_winner,
|
||||
get_legal_cards_for_trick,
|
||||
is_trump_card,
|
||||
)
|
||||
from models.cards.bavarian_deck import BavarianCard, create_bavarian_deck
|
||||
from resources.code_res.game_constants import (
|
||||
BAVARIAN_SUITS,
|
||||
WT_GESPANNT_POINTS,
|
||||
WT_HAND_SIZE,
|
||||
WT_NUM_PLAYERS,
|
||||
WT_WIN_POINTS,
|
||||
)
|
||||
|
||||
# Phasen einer einzelnen Watten-Hand innerhalb des Satzes (bis 11 Punkte)
|
||||
PHASE_SCHOENERE_ASK = "schoenere_ask" # Vorhand darf "Schönere?" fragen oder Schlag ansagen
|
||||
PHASE_SCHOENERE_REPLY = "schoenere_reply" # Geber antwortet auf "Schönere?" (Ja = neu geben / Nein = Pflicht)
|
||||
PHASE_ANSAGE_SCHLAG = "ansage_schlag" # Vorhand (Ansager) bestimmt den Schlag (7..A)
|
||||
PHASE_ANSAGE_TRUMPF = "ansage_trumpf" # Geber bestimmt die Trumpffarbe (E/B/H/S)
|
||||
PHASE_TRICK_PLAY = "trick_play" # Ausspielen der bis zu 5 Stiche (oder Ausschaffen!)
|
||||
PHASE_AUSSCHAFFEN_REPLY = "ausschaffen_reply" # Gegner-Team entscheidet: Halten (+1) oder Gehen!
|
||||
PHASE_HAND_DONE = "hand_done" # Einzelhand beendet (3 Stiche erreicht oder Aufgabe)
|
||||
PHASE_MATCH_DONE = "match_done" # Gesamtsatz beendet (>= 11 Punkte erreicht)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WattenSeat:
|
||||
seat_id: int
|
||||
name: str
|
||||
team_id: int # Team 0 = Sitz 0 (Du) & Sitz 2 (Partner Nord); Team 1 = Sitz 1 (West) & Sitz 3 (Ost)
|
||||
is_human: bool = False
|
||||
ai_level: int = 2
|
||||
hand: list[BavarianCard] = field(default_factory=list)
|
||||
status_text: str = ""
|
||||
|
||||
|
||||
class WattenEngine:
|
||||
"""
|
||||
Oberbayerisches Watten (32 Karten, 2v2 über Kreuz bis 11 Gewinnpunkte):
|
||||
- Team 0: Sitz 0 (Spieler Süd) + Sitz 2 (Partner Nord)
|
||||
- Team 1: Sitz 1 (Gegner West) + Sitz 3 (Gegner Ost)
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.seats: list[WattenSeat] = []
|
||||
self.team_points: list[int] = [0, 0]
|
||||
self.team_tricks: list[int] = [0, 0]
|
||||
|
||||
self.dealer_seat: int = -1
|
||||
self.ansager_seat: int = 0
|
||||
self.turn_seat: int = 0
|
||||
|
||||
self.phase: str = PHASE_ANSAGE_SCHLAG
|
||||
self.schoenere_used: bool = False
|
||||
self.schlag_rank: str | None = None
|
||||
self.trump_suit: str | None = None
|
||||
|
||||
self.current_stake: int = 2
|
||||
self.proposed_stake: int = 3
|
||||
self.last_raising_team: int | None = None
|
||||
self.responder_seat: int = 0
|
||||
self._saved_turn_before_raise: int = 0
|
||||
|
||||
self.trick_index: int = 0
|
||||
self.current_trick: list[tuple[int, BavarianCard]] = []
|
||||
self.last_completed_trick: list[tuple[int, BavarianCard]] = []
|
||||
self.last_trick_winner: int | None = None
|
||||
|
||||
self.hand_winner_team: int | None = None
|
||||
self.hand_points_awarded: int = 0
|
||||
self.match_winner_team: int | None = None
|
||||
self.hands_played: int = 0
|
||||
|
||||
@staticmethod
|
||||
def team_of(seat_id: int) -> int:
|
||||
return seat_id % 2
|
||||
|
||||
@property
|
||||
def is_match_over(self) -> bool:
|
||||
return self.match_winner_team is not None
|
||||
|
||||
def is_team_gespannt(self, team_id: int) -> bool:
|
||||
return self.team_points[team_id] >= WT_GESPANNT_POINTS
|
||||
|
||||
def configure_seats(
|
||||
self, human_name: str, bot_configs: list[tuple[int, str]]
|
||||
) -> None:
|
||||
"""
|
||||
Sitz 0: Spieler (Team 0)
|
||||
Sitz 1: Gegner Links / West (Team 1) <- bot_configs[0]
|
||||
Sitz 2: Partner Oben / Nord (Team 0) <- bot_configs[1]
|
||||
Sitz 3: Gegner Rechts / Ost (Team 1) <- bot_configs[2]
|
||||
"""
|
||||
self.seats = [WattenSeat(seat_id=0, name=human_name, team_id=0, is_human=True)]
|
||||
for seat_id in range(1, WT_NUM_PLAYERS):
|
||||
cfg_idx = seat_id - 1
|
||||
lvl, b_name = (
|
||||
bot_configs[cfg_idx]
|
||||
if cfg_idx < len(bot_configs)
|
||||
else (2, f"Bot {seat_id}")
|
||||
)
|
||||
self.seats.append(
|
||||
WattenSeat(
|
||||
seat_id=seat_id,
|
||||
name=b_name,
|
||||
team_id=self.team_of(seat_id),
|
||||
is_human=False,
|
||||
ai_level=lvl,
|
||||
)
|
||||
)
|
||||
|
||||
def start_new_match(self, rng: random.Random | None = None) -> None:
|
||||
self.team_points = [0, 0]
|
||||
self.match_winner_team = None
|
||||
self.hands_played = 0
|
||||
self.dealer_seat = (rng or random).randrange(WT_NUM_PLAYERS)
|
||||
self.start_new_hand(rotate_dealer=False, rng=rng)
|
||||
|
||||
def start_new_hand(
|
||||
self, rotate_dealer: bool = True, rng: random.Random | None = None
|
||||
) -> None:
|
||||
if rotate_dealer or self.dealer_seat < 0:
|
||||
self.dealer_seat = (self.dealer_seat + 1) % WT_NUM_PLAYERS
|
||||
self.ansager_seat = (self.dealer_seat + 1) % WT_NUM_PLAYERS
|
||||
self.schoenere_used = False
|
||||
self._deal_cards_internal(rng)
|
||||
|
||||
def _deal_cards_internal(self, rng: random.Random | None = None) -> None:
|
||||
r = rng or random
|
||||
deck = create_bavarian_deck(include_six=False, shuffle=True, rng=r)
|
||||
suit_order = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
|
||||
|
||||
for idx, seat in enumerate(self.seats):
|
||||
chunk = deck[idx * WT_HAND_SIZE : (idx + 1) * WT_HAND_SIZE]
|
||||
chunk.sort(key=lambda c: (suit_order[c.suit], c.order_index))
|
||||
seat.hand = chunk
|
||||
seat.status_text = ""
|
||||
|
||||
self.team_tricks = [0, 0]
|
||||
self.schlag_rank = None
|
||||
self.trump_suit = None
|
||||
self.trick_index = 0
|
||||
self.current_trick = []
|
||||
self.last_completed_trick = []
|
||||
self.last_trick_winner = None
|
||||
self.hand_winner_team = None
|
||||
self.hand_points_awarded = 0
|
||||
|
||||
# Ist mindestens ein Team gespannt (>= 9), zählt jede Hand automatisch 3 Punkte!
|
||||
either_gespannt = self.is_team_gespannt(0) or self.is_team_gespannt(1)
|
||||
self.current_stake = 3 if either_gespannt else 2
|
||||
self.proposed_stake = self.current_stake + 1
|
||||
self.last_raising_team = None
|
||||
|
||||
self.turn_seat = self.ansager_seat
|
||||
# "Schönere?" ist erlaubt, solange keines der Teams gespannt ist und noch nicht neu gegeben wurde
|
||||
if not either_gespannt and not self.schoenere_used:
|
||||
self.phase = PHASE_SCHOENERE_ASK
|
||||
else:
|
||||
self.phase = PHASE_ANSAGE_SCHLAG
|
||||
|
||||
def sort_hands_for_ansage(self) -> None:
|
||||
"""Sortiert nach erfolgter Ansage alle Trümpfe übersichtlich nach links auf die Hand."""
|
||||
if not self.schlag_rank or not self.trump_suit:
|
||||
return
|
||||
suit_order = {s: i for i, s in enumerate(BAVARIAN_SUITS)}
|
||||
for seat in self.seats:
|
||||
seat.hand.sort(
|
||||
key=lambda c: (
|
||||
0 if is_trump_card(c, self.schlag_rank, self.trump_suit) else 1,
|
||||
suit_order[c.suit],
|
||||
c.order_index,
|
||||
)
|
||||
)
|
||||
|
||||
# --- 1. Schönere? & Ansagen (Schlag + Trumpf) ---
|
||||
def ask_schoenere(self, seat_id: int) -> bool:
|
||||
if self.phase != PHASE_SCHOENERE_ASK or seat_id != self.ansager_seat:
|
||||
return False
|
||||
self.phase = PHASE_SCHOENERE_REPLY
|
||||
self.turn_seat = self.dealer_seat
|
||||
return True
|
||||
|
||||
def skip_schoenere(self, seat_id: int) -> bool:
|
||||
if self.phase != PHASE_SCHOENERE_ASK or seat_id != self.ansager_seat:
|
||||
return False
|
||||
self.phase = PHASE_ANSAGE_SCHLAG
|
||||
self.turn_seat = self.ansager_seat
|
||||
return True
|
||||
|
||||
def reply_schoenere(
|
||||
self, seat_id: int, accept_redeal: bool, rng: random.Random | None = None
|
||||
) -> bool:
|
||||
if self.phase != PHASE_SCHOENERE_REPLY or seat_id != self.dealer_seat:
|
||||
return False
|
||||
self.schoenere_used = True
|
||||
if accept_redeal:
|
||||
self._deal_cards_internal(rng)
|
||||
else:
|
||||
self.phase = PHASE_ANSAGE_SCHLAG
|
||||
self.turn_seat = self.ansager_seat
|
||||
return True
|
||||
|
||||
def declare_schlag(self, seat_id: int, rank: str) -> bool:
|
||||
if self.phase not in (PHASE_SCHOENERE_ASK, PHASE_ANSAGE_SCHLAG):
|
||||
return False
|
||||
if seat_id != self.ansager_seat or rank not in WATTEN_RANKS_32:
|
||||
return False
|
||||
self.schlag_rank = rank
|
||||
self.phase = PHASE_ANSAGE_TRUMPF
|
||||
self.turn_seat = self.dealer_seat
|
||||
return True
|
||||
|
||||
def declare_trumpf(self, seat_id: int, suit: str) -> bool:
|
||||
if self.phase != PHASE_ANSAGE_TRUMPF or seat_id != self.dealer_seat:
|
||||
return False
|
||||
if suit not in BAVARIAN_SUITS:
|
||||
return False
|
||||
self.trump_suit = suit
|
||||
self.sort_hands_for_ansage()
|
||||
self.phase = PHASE_TRICK_PLAY
|
||||
self.turn_seat = self.ansager_seat
|
||||
return True
|
||||
|
||||
# --- 2. Ausschaffen (Erhöhen) & Halten / Gehen ---
|
||||
def can_seat_ausschaffen(self, seat_id: int) -> bool:
|
||||
if self.phase != PHASE_TRICK_PLAY or seat_id != self.turn_seat:
|
||||
return False
|
||||
my_team = self.team_of(seat_id)
|
||||
if self.is_team_gespannt(my_team):
|
||||
return False
|
||||
if self.last_raising_team == my_team:
|
||||
return False
|
||||
# Sinnvolle Obergrenze: sobald aktueller Einsatz ohnehin zum Match-Sieg beider Teams reicht
|
||||
opp_team = 1 - my_team
|
||||
if (
|
||||
self.team_points[my_team] + self.current_stake >= WT_WIN_POINTS
|
||||
and self.team_points[opp_team] + self.current_stake >= WT_WIN_POINTS
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
def initiate_ausschaffen(self, seat_id: int) -> bool:
|
||||
if not self.can_seat_ausschaffen(seat_id):
|
||||
return False
|
||||
my_team = self.team_of(seat_id)
|
||||
opp_team = 1 - my_team
|
||||
self._saved_turn_before_raise = self.turn_seat
|
||||
self.proposed_stake = self.current_stake + 1
|
||||
self.last_raising_team = my_team
|
||||
|
||||
# Wenn der menschliche Spieler im Gegner-Team sitzt (opp_team == 0), antwortet IMMER der Mensch!
|
||||
if opp_team == 0:
|
||||
self.responder_seat = 0
|
||||
else:
|
||||
# Sonst antwortet der nächste aktive Gegner im Uhrzeigersinn
|
||||
cand = (seat_id + 1) % WT_NUM_PLAYERS
|
||||
self.responder_seat = cand if self.team_of(cand) == opp_team else (cand + 2) % WT_NUM_PLAYERS
|
||||
|
||||
self.phase = PHASE_AUSSCHAFFEN_REPLY
|
||||
self.turn_seat = self.responder_seat
|
||||
return True
|
||||
|
||||
def respond_ausschaffen(self, seat_id: int, accept_hold: bool) -> bool:
|
||||
if self.phase != PHASE_AUSSCHAFFEN_REPLY or seat_id != self.responder_seat:
|
||||
return False
|
||||
if accept_hold:
|
||||
self.current_stake = self.proposed_stake
|
||||
self.phase = PHASE_TRICK_PLAY
|
||||
self.turn_seat = self._saved_turn_before_raise
|
||||
return True
|
||||
|
||||
# Gegner geht ("Aufgabe der Hand") -> ausschaffendes Team erhält den bisherigen Einsatz!
|
||||
winner_team = 1 - self.team_of(seat_id)
|
||||
self._award_hand_to_team(winner_team, self.current_stake)
|
||||
return True
|
||||
|
||||
# --- 3. Stich-Ausspiel ---
|
||||
def get_playable_cards(self, seat_id: int) -> list[BavarianCard]:
|
||||
if self.phase != PHASE_TRICK_PLAY or seat_id != self.turn_seat:
|
||||
return []
|
||||
assert self.schlag_rank is not None and self.trump_suit is not None
|
||||
return get_legal_cards_for_trick(
|
||||
self.seats[seat_id].hand,
|
||||
self.current_trick,
|
||||
self.trick_index,
|
||||
self.ansager_seat,
|
||||
self.schlag_rank,
|
||||
self.trump_suit,
|
||||
)
|
||||
|
||||
def play_card(self, seat_id: int, card: BavarianCard) -> str:
|
||||
"""
|
||||
Spielt eine Karte in den aktuellen Stich.
|
||||
Rückgabe: 'invalid' | 'played' | 'trick_completed' | 'hand_completed' | 'match_completed'
|
||||
"""
|
||||
legal = self.get_playable_cards(seat_id)
|
||||
if card not in legal:
|
||||
return "invalid"
|
||||
|
||||
self.seats[seat_id].hand.remove(card)
|
||||
self.current_trick.append((seat_id, card))
|
||||
|
||||
if len(self.current_trick) < WT_NUM_PLAYERS:
|
||||
self.turn_seat = (self.turn_seat + 1) % WT_NUM_PLAYERS
|
||||
return "played"
|
||||
|
||||
assert self.schlag_rank is not None and self.trump_suit is not None
|
||||
win_seat = evaluate_trick_winner(
|
||||
self.current_trick, self.schlag_rank, self.trump_suit
|
||||
)
|
||||
win_team = self.team_of(win_seat)
|
||||
self.team_tricks[win_team] += 1
|
||||
self.last_completed_trick = list(self.current_trick)
|
||||
self.last_trick_winner = win_seat
|
||||
self.current_trick = []
|
||||
self.trick_index += 1
|
||||
|
||||
# Wer zuerst 3 Stiche hat, gewinnt die Hand sofort!
|
||||
if self.team_tricks[win_team] >= 3:
|
||||
self._award_hand_to_team(win_team, self.current_stake)
|
||||
return "match_completed" if self.is_match_over else "hand_completed"
|
||||
|
||||
self.turn_seat = win_seat
|
||||
return "trick_completed"
|
||||
|
||||
def _award_hand_to_team(self, winner_team: int, pts: int) -> None:
|
||||
self.hand_winner_team = winner_team
|
||||
self.hand_points_awarded = pts
|
||||
self.team_points[winner_team] += pts
|
||||
self.hands_played += 1
|
||||
if self.team_points[winner_team] >= WT_WIN_POINTS:
|
||||
self.match_winner_team = winner_team
|
||||
self.phase = PHASE_MATCH_DONE
|
||||
else:
|
||||
self.phase = PHASE_HAND_DONE
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/models/watten_rules.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.cards.bavarian_deck import BavarianCard
|
||||
|
||||
# Natürliche Rangstärke beim Watten innerhalb einer Farbe: 7 < 8 < 9 < 10 < U < O < K < A
|
||||
WATTEN_RANKS_32: tuple[str, ...] = ("7", "8", "9", "10", "U", "O", "K", "A")
|
||||
NATURAL_STRENGTH: dict[str, int] = {
|
||||
rank: idx for idx, rank in enumerate(WATTEN_RANKS_32)
|
||||
}
|
||||
|
||||
# Die 3 Kritischen (unveränderliche höchste Trümpfe in jedem Spiel!)
|
||||
KRIT_MAX = BavarianCard("H", "K") # 1. Herz-König ("Max")
|
||||
KRIT_BELLI = BavarianCard("S", "7") # 2. Schellen-7 ("Belli")
|
||||
KRIT_SPITZ = BavarianCard("E", "7") # 3. Eichel-7 ("Spitz")
|
||||
KRITISCHE = (KRIT_MAX, KRIT_BELLI, KRIT_SPITZ)
|
||||
|
||||
|
||||
def is_kritische(card: BavarianCard) -> bool:
|
||||
return card in KRITISCHE
|
||||
|
||||
|
||||
def is_guade(card: BavarianCard, schlag_rank: str | None, trump_suit: str | None) -> bool:
|
||||
"""Die 'Guade' (Rechte) vereint Schlag-Rang + Trumpffarbe (sofern sie keine Kritische ist)."""
|
||||
if not schlag_rank or not trump_suit or is_kritische(card):
|
||||
return False
|
||||
return card.rank == schlag_rank and card.suit == trump_suit
|
||||
|
||||
|
||||
def is_schlag(card: BavarianCard, schlag_rank: str | None, trump_suit: str | None) -> bool:
|
||||
"""Einer der 'Blinden' (Hauptschläge) = angesagter Rang in Nicht-Trumpffarbe (ohne Kritische)."""
|
||||
if not schlag_rank or is_kritische(card) or is_guade(card, schlag_rank, trump_suit):
|
||||
return False
|
||||
return card.rank == schlag_rank
|
||||
|
||||
|
||||
def is_trump_card(
|
||||
card: BavarianCard, schlag_rank: str | None, trump_suit: str | None
|
||||
) -> bool:
|
||||
"""Beim Watten zählen Kritische, Guade, alle Schläge UND die Trumpffarbe als Trumpf!"""
|
||||
if is_kritische(card):
|
||||
return True
|
||||
if schlag_rank and card.rank == schlag_rank:
|
||||
return True
|
||||
if trump_suit and card.suit == trump_suit:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def card_role_badge_key(
|
||||
card: BavarianCard, schlag_rank: str | None, trump_suit: str | None
|
||||
) -> str | None:
|
||||
"""Liefert ein optionales Kurz-Label für UI-Hervorhebungen (Max, Belli, Spitz, Guade, Schlag, Trumpf)."""
|
||||
if card == KRIT_MAX:
|
||||
return "wt_role_max"
|
||||
if card == KRIT_BELLI:
|
||||
return "wt_role_belli"
|
||||
if card == KRIT_SPITZ:
|
||||
return "wt_role_spitz"
|
||||
if is_guade(card, schlag_rank, trump_suit):
|
||||
return "wt_role_guade"
|
||||
if is_schlag(card, schlag_rank, trump_suit):
|
||||
return "wt_role_schlag"
|
||||
if trump_suit and card.suit == trump_suit:
|
||||
return "wt_role_trump"
|
||||
return None
|
||||
|
||||
|
||||
def trick_card_power(
|
||||
card: BavarianCard,
|
||||
led_suit: str,
|
||||
play_order: int,
|
||||
schlag_rank: str,
|
||||
trump_suit: str,
|
||||
) -> tuple[int, int]:
|
||||
"""
|
||||
Berechnet die exakte Stich-Stärke (Kategorie, Feinwert).
|
||||
Bei gleichrangigen 'Blinden' (Hauptschlägen) gewinnt die ZUERST gespielte Karte (-play_order)!
|
||||
"""
|
||||
if card == KRIT_MAX:
|
||||
return (100, 0)
|
||||
if card == KRIT_BELLI:
|
||||
return (99, 0)
|
||||
if card == KRIT_SPITZ:
|
||||
return (98, 0)
|
||||
if is_guade(card, schlag_rank, trump_suit):
|
||||
return (97, 0)
|
||||
if is_schlag(card, schlag_rank, trump_suit):
|
||||
return (96, -play_order)
|
||||
if card.suit == trump_suit:
|
||||
return (80, NATURAL_STRENGTH[card.rank])
|
||||
if card.suit == led_suit:
|
||||
return (40, NATURAL_STRENGTH[card.rank])
|
||||
return (0, -play_order)
|
||||
|
||||
|
||||
def evaluate_trick_winner(
|
||||
trick: list[tuple[int, BavarianCard]],
|
||||
schlag_rank: str,
|
||||
trump_suit: str,
|
||||
) -> int:
|
||||
"""Gibt die seat_id (0..3) des Stich-Gewinners zurück."""
|
||||
assert trick, "Stich darf nicht leer sein"
|
||||
led_suit = trick[0][1].suit
|
||||
best_seat = trick[0][0]
|
||||
best_score = (-1, -99)
|
||||
for order_idx, (seat_id, card) in enumerate(trick):
|
||||
sc = trick_card_power(card, led_suit, order_idx, schlag_rank, trump_suit)
|
||||
if sc > best_score:
|
||||
best_score = sc
|
||||
best_seat = seat_id
|
||||
return best_seat
|
||||
|
||||
|
||||
def get_legal_cards_for_trick(
|
||||
hand: list[BavarianCard],
|
||||
trick: list[tuple[int, BavarianCard]],
|
||||
trick_index: int,
|
||||
ansager_seat: int,
|
||||
schlag_rank: str,
|
||||
trump_suit: str,
|
||||
) -> list[BavarianCard]:
|
||||
"""
|
||||
Beim Watten herrscht KEIN allgemeiner Farbzwang!
|
||||
Einzige Pflicht-Ausnahme (Oberbayerische Hauptschlag-Regel):
|
||||
Spielt der Ansager im 1. Stich (trick_index == 0) die Guade oder einen Schlag an,
|
||||
muss jeder Spieler, der Trumpf hält, Trumpf zugeben – AUSSER er besitzt als einzige
|
||||
Trümpfe nur Kritische oder die Guade (diese dürfen geschont werden).
|
||||
"""
|
||||
if not hand or not trick or trick_index != 0:
|
||||
return list(hand)
|
||||
|
||||
lead_seat, lead_card = trick[0]
|
||||
led_hauptschlag = (lead_seat == ansager_seat) and (
|
||||
is_guade(lead_card, schlag_rank, trump_suit)
|
||||
or is_schlag(lead_card, schlag_rank, trump_suit)
|
||||
)
|
||||
if not led_hauptschlag:
|
||||
return list(hand)
|
||||
|
||||
all_trumps = [c for c in hand if is_trump_card(c, schlag_rank, trump_suit)]
|
||||
if not all_trumps:
|
||||
return list(hand)
|
||||
|
||||
# Hat der Spieler mindestens einen normalen Trumpf oder normalen Schlag -> strenge Trumpfpflicht!
|
||||
non_protected_trumps = [
|
||||
c
|
||||
for c in all_trumps
|
||||
if not is_kritische(c) and not is_guade(c, schlag_rank, trump_suit)
|
||||
]
|
||||
if non_protected_trumps:
|
||||
return all_trumps
|
||||
|
||||
# Hält er ausschließlich Kritische / Guade als Trumpf -> er darf sie schonen (freie Kartenwahl)!
|
||||
return list(hand)
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/models/watten_tutorials.py
|
||||
from __future__ import annotations
|
||||
|
||||
from view.tutorial.tutorial_models import TutorialStep, TutorialUnit
|
||||
|
||||
|
||||
def build_watten_tutorial_units() -> list[TutorialUnit]:
|
||||
"""Liefert die 4 geführten Praxis-Lektionen für Oberbayerisches Watten."""
|
||||
unit_1 = TutorialUnit(
|
||||
unit_id="u1_basics_kritische",
|
||||
title_key="wt_tut_u1_title",
|
||||
subtitle_key="wt_tut_u1_sub",
|
||||
badge_text="I",
|
||||
steps=[
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u1_s1_title",
|
||||
body_key="wt_tut_u1_s1_body",
|
||||
mode="info",
|
||||
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
|
||||
team_points=(0, 0),
|
||||
current_stake=2,
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u1_s2_title",
|
||||
body_key="wt_tut_u1_s2_body",
|
||||
mode="card",
|
||||
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
|
||||
highlight_cards=[("H", "K"), ("S", "7"), ("E", "7")],
|
||||
allowed_cards=[("H", "K")],
|
||||
wrong_hint_key="wt_tut_u1_s2_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u1_s3_title",
|
||||
body_key="wt_tut_u1_s3_body",
|
||||
mode="card",
|
||||
my_hand=[("E", "A"), ("B", "10"), ("S", "7"), ("E", "7"), ("H", "9")],
|
||||
trick_cards=[(1, "E", "7")],
|
||||
allowed_cards=[("S", "7")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
wrong_hint_key="wt_tut_u1_s3_wrong",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
unit_2 = TutorialUnit(
|
||||
unit_id="u2_schlag_trumpf_guade",
|
||||
title_key="wt_tut_u2_title",
|
||||
subtitle_key="wt_tut_u2_sub",
|
||||
badge_text="II",
|
||||
steps=[
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u2_s1_title",
|
||||
body_key="wt_tut_u2_s1_body",
|
||||
mode="choice",
|
||||
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||
highlight_cards=[("B", "O"), ("E", "O")],
|
||||
choices=[
|
||||
("ask_o", "wt_tut_choice_ober", True),
|
||||
("ask_8", "wt_tut_choice_acht", False),
|
||||
],
|
||||
wrong_hint_key="wt_tut_u2_s1_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u2_s2_title",
|
||||
body_key="wt_tut_u2_s2_body",
|
||||
mode="card",
|
||||
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||
highlight_cards=[("B", "O")],
|
||||
allowed_cards=[("B", "O")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
wrong_hint_key="wt_tut_u2_s2_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u2_s3_title",
|
||||
body_key="wt_tut_u2_s3_body",
|
||||
mode="info",
|
||||
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
|
||||
highlight_cards=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
unit_3 = TutorialUnit(
|
||||
unit_id="u3_first_round_trumps",
|
||||
title_key="wt_tut_u3_title",
|
||||
subtitle_key="wt_tut_u3_sub",
|
||||
badge_text="III",
|
||||
steps=[
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u3_s1_title",
|
||||
body_key="wt_tut_u3_s1_body",
|
||||
mode="card",
|
||||
my_hand=[("E", "8"), ("E", "9"), ("H", "A"), ("B", "U"), ("S", "10")],
|
||||
trick_cards=[(1, "E", "A"), (2, "H", "10"), (3, "E", "K")],
|
||||
allowed_cards=[("B", "U")],
|
||||
schlag_rank="10",
|
||||
trump_suit="B",
|
||||
wrong_hint_key="wt_tut_u3_s1_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u3_s2_title",
|
||||
body_key="wt_tut_u3_s2_body",
|
||||
mode="card",
|
||||
my_hand=[("H", "8"), ("H", "9"), ("B", "8"), ("S", "A"), ("E", "K")],
|
||||
trick_cards=[(1, "H", "O")],
|
||||
allowed_cards=[("B", "8")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
wrong_hint_key="wt_tut_u3_s2_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u3_s3_title",
|
||||
body_key="wt_tut_u3_s3_body",
|
||||
mode="card",
|
||||
my_hand=[("H", "K"), ("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
|
||||
trick_cards=[(1, "S", "O")],
|
||||
allowed_cards=[("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
|
||||
highlight_cards=[("E", "8")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
wrong_hint_key="wt_tut_u3_s3_wrong",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
unit_4 = TutorialUnit(
|
||||
unit_id="u4_ausschaffen_gespannt",
|
||||
title_key="wt_tut_u4_title",
|
||||
subtitle_key="wt_tut_u4_sub",
|
||||
badge_text="IV",
|
||||
steps=[
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u4_s1_title",
|
||||
body_key="wt_tut_u4_s1_body",
|
||||
mode="choice",
|
||||
my_hand=[("H", "K"), ("S", "7"), ("B", "O"), ("B", "A"), ("E", "A")],
|
||||
highlight_cards=[("H", "K"), ("S", "7"), ("B", "O")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
team_points=(4, 4),
|
||||
current_stake=2,
|
||||
choices=[
|
||||
("raise", "wt_btn_ausschaffen_ tutorial", True),
|
||||
("quiet", "wt_tut_choice_stay_2", False),
|
||||
],
|
||||
wrong_hint_key="wt_tut_u4_s1_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u4_s2_title",
|
||||
body_key="wt_tut_u4_s2_body",
|
||||
mode="choice",
|
||||
my_hand=[("E", "8"), ("E", "9"), ("S", "8"), ("H", "7"), ("H", "9")],
|
||||
schlag_rank="K",
|
||||
trump_suit="B",
|
||||
team_points=(6, 4),
|
||||
current_stake=2,
|
||||
choices=[
|
||||
("fold", "wt_btn_fold_hand", True),
|
||||
("hold", "wt_tut_choice_hold_bad", False),
|
||||
],
|
||||
wrong_hint_key="wt_tut_u4_s2_wrong",
|
||||
),
|
||||
TutorialStep(
|
||||
title_key="wt_tut_u4_s3_title",
|
||||
body_key="wt_tut_u4_s3_body",
|
||||
mode="info",
|
||||
my_hand=[("H", "K"), ("B", "A"), ("E", "10"), ("S", "O"), ("H", "A")],
|
||||
schlag_rank="O",
|
||||
trump_suit="B",
|
||||
team_points=(9, 7),
|
||||
current_stake=3,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
return [unit_1, unit_2, unit_3, unit_4]
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/start.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.party.watten.views.watten_menu_view import WattenMenuView
|
||||
from resources.code_res.game_constants import CAT_PARTY_OFFLINE
|
||||
|
||||
GAME_FOLDER_ID = "party/watten"
|
||||
GAME_TITLE_KEY = "game_title_watten"
|
||||
GAME_CATEGORY = CAT_PARTY_OFFLINE
|
||||
|
||||
|
||||
def start_game(context) -> None:
|
||||
WattenMenuView(context).show()
|
||||
|
|
@ -0,0 +1,331 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/views/watten_arena_renderer.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.party.watten.models.watten_engine import PHASE_TRICK_PLAY
|
||||
from games.party.watten.models.watten_rules import card_role_badge_key
|
||||
from models.cards.bavarian_deck import BavarianCard
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD,
|
||||
ACCENT_GOTH,
|
||||
BAVARIAN_CARD_THEME,
|
||||
BORDER_COLOR,
|
||||
ERROR_FG,
|
||||
FG_COLOR,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
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
|
||||
|
||||
WT_BOT_BACK_SIZE = (40, 58)
|
||||
WT_TRICK_CARD_SIZE = (84, 122)
|
||||
WT_MAX_HAND_CARD_H = 182
|
||||
WT_HAND_TOP_EXTEND_PX = 20
|
||||
|
||||
|
||||
class WattenArenaRenderer:
|
||||
"""Rendert Watten (Desktop-Kreuztisch vs. Kompakt/Mobile mit 3er-Leiste oben & Status-Strip)."""
|
||||
|
||||
@staticmethod
|
||||
def draw_other_seats(
|
||||
view,
|
||||
cw: int,
|
||||
pad_x: int,
|
||||
pad_top: int,
|
||||
table_rect: tuple[int, int, int, int],
|
||||
) -> tuple[int, int, int]:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
eng = view.engine
|
||||
if len(eng.seats) < 4:
|
||||
return ty1 + 20, tx1 + 20, tx2 - 20
|
||||
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
if compact:
|
||||
gap = 6
|
||||
avail_w = max(320, cw - 2 * pad_x)
|
||||
box_w = min(214, (avail_w - 2 * gap) // 3)
|
||||
box_h = 82
|
||||
start_x = (cw - (3 * box_w + 2 * gap)) // 2 + box_w // 2
|
||||
top_cy = pad_top + box_h // 2 + 2
|
||||
seat_specs = [
|
||||
(eng.seats[1], start_x, top_cy, False),
|
||||
(eng.seats[2], start_x + (box_w + gap), top_cy, True),
|
||||
(eng.seats[3], start_x + 2 * (box_w + gap), top_cy, False),
|
||||
]
|
||||
back_sz = (30, 44)
|
||||
else:
|
||||
box_w, box_h = 232, 92
|
||||
mid_side_y = (ty1 + ty2) // 2 - 14
|
||||
top_cy = max(pad_top + box_h // 2 - 4, 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))
|
||||
seat_specs = [
|
||||
(eng.seats[1], left_cx, mid_side_y, False),
|
||||
(eng.seats[2], cw // 2, top_cy, True),
|
||||
(eng.seats[3], right_cx, mid_side_y, False),
|
||||
]
|
||||
back_sz = WT_BOT_BACK_SIZE
|
||||
|
||||
back_ph = view.ctx.assets.get_card_back_photo(size=back_sz, theme=BAVARIAN_CARD_THEME)
|
||||
if back_ph is not None:
|
||||
view._photo_refs.append(back_ph)
|
||||
|
||||
name_sz = max(12 if compact else 14, FONT_SIZE_SMALL_MIN if compact else FONT_SIZE_BODY - 1)
|
||||
sub_sz = max(11 if compact else 12, FONT_SIZE_SMALL_MIN - (1 if compact else 0))
|
||||
|
||||
for seat, bx, by, is_partner in seat_specs:
|
||||
is_turn = not eng.is_match_over and eng.turn_seat == seat.seat_id
|
||||
n_cards = len(seat.hand)
|
||||
|
||||
role_tags: list[str] = []
|
||||
if seat.seat_id == eng.dealer_seat:
|
||||
role_tags.append(t("wt_tag_dealer"))
|
||||
elif seat.seat_id == eng.ansager_seat:
|
||||
role_tags.append(t("wt_tag_ansager"))
|
||||
if is_partner:
|
||||
role_tags.insert(0, t("wt_tag_partner"))
|
||||
role_line = " • ".join(role_tags) if role_tags else t("wt_tag_opponent")
|
||||
|
||||
view._draw_framed_panel(
|
||||
bx, by, box_w, box_h,
|
||||
frame_style="gold" if is_turn else "purple",
|
||||
status_border=FONT_COLOR_STATUS_WIN if is_partner else None,
|
||||
)
|
||||
|
||||
if back_ph is not None and n_cards > 0 and (not compact or box_w >= 176):
|
||||
step_b = 6 if compact else 8
|
||||
bx0 = bx - box_w // 2 + (10 if compact else 12)
|
||||
by0 = by - back_sz[1] // 2
|
||||
for bi in range(n_cards):
|
||||
view.arena_canvas.create_image(
|
||||
bx0 + bi * step_b, by0, image=back_ph, anchor="nw", tags="fg"
|
||||
)
|
||||
txt_cx = bx + (20 if compact else 28)
|
||||
max_tw = box_w - (68 if compact else 92)
|
||||
else:
|
||||
txt_cx = bx
|
||||
max_tw = box_w - 18
|
||||
|
||||
n_col = ACCENT_GOLD if is_turn else (FONT_COLOR_STATUS_WIN if is_partner else ACCENT_GOTH)
|
||||
act_txt = seat.status_text or "-"
|
||||
|
||||
n_ph = view._make_goth_photo(seat.name, name_sz, n_col, max_tw)
|
||||
r_ph = view._make_goth_photo(role_line, max(10, sub_sz - 1), MUTED_FG, max_tw)
|
||||
a_ph = view._make_goth_photo(act_txt, sub_sz, FG_COLOR, max_tw)
|
||||
|
||||
dy = 21 if compact else 23
|
||||
view._place_goth_photo_or_fallback(txt_cx, by - dy, n_ph, seat.name, name_sz, n_col)
|
||||
view._place_goth_photo_or_fallback(txt_cx, by - 1, r_ph, role_line, max(10, sub_sz - 1), MUTED_FG)
|
||||
view._place_goth_photo_or_fallback(txt_cx, by + dy - 1, a_ph, act_txt, sub_sz, FG_COLOR)
|
||||
|
||||
if compact:
|
||||
return (top_cy + box_h // 2, 0, cw)
|
||||
return (
|
||||
top_cy + box_h // 2,
|
||||
seat_specs[0][1] + box_w // 2,
|
||||
seat_specs[2][1] - box_w // 2,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def draw_center_trick_area(
|
||||
view,
|
||||
cw: int,
|
||||
table_rect: tuple[int, int, int, int],
|
||||
bot_bounds: tuple[int, int, int],
|
||||
player_top_y: int,
|
||||
) -> None:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
top_obs_y, left_obs_x, right_obs_x = bot_bounds
|
||||
eng = view.engine
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
|
||||
schlag_txt = t(f"bav_rank_{eng.schlag_rank}") if eng.schlag_rank else "?"
|
||||
trump_txt = t(f"bav_suit_{eng.trump_suit}") if eng.trump_suit else "?"
|
||||
gesp_0, gesp_1 = eng.is_team_gespannt(0), eng.is_team_gespannt(1)
|
||||
|
||||
if compact:
|
||||
# Kompakte zweizeilige Info-Leiste direkt unter den 3 oberen Sitzen
|
||||
strip_w = min(cw - 16, 620)
|
||||
strip_h = 54
|
||||
strip_cy = top_obs_y + 8 + strip_h // 2
|
||||
view._draw_framed_panel(
|
||||
cw // 2, strip_cy, strip_w, strip_h,
|
||||
frame_style="gold" if (gesp_0 or gesp_1) else "purple",
|
||||
)
|
||||
top_line = (
|
||||
f"{t('wt_lbl_schlag')}: {schlag_txt} • "
|
||||
f"{t('wt_lbl_trumpf')}: {trump_txt} • "
|
||||
f"{t('wt_lbl_tricks_pair', eng.team_tricks[0], eng.team_tricks[1])}"
|
||||
)
|
||||
warn_tail = f" • {t('wt_lbl_gespannt_warn')}" if (gesp_0 or gesp_1) else ""
|
||||
bot_line = f"{t('wt_lbl_match_pts', eng.team_points[0], eng.team_points[1])} • {t('wt_lbl_cur_stake', eng.current_stake)}{warn_tail}"
|
||||
|
||||
p1 = view._make_goth_photo(top_line, FONT_SIZE_SMALL_MIN, FONT_COLOR_TITLE_MAIN, strip_w - 28)
|
||||
p2 = view._make_goth_photo(
|
||||
bot_line, FONT_SIZE_SMALL_MIN - 1,
|
||||
ERROR_FG if (gesp_0 or gesp_1) else ACCENT_GOLD, strip_w - 28,
|
||||
)
|
||||
view._place_goth_photo_or_fallback(cw // 2, strip_cy - 11, p1, top_line, FONT_SIZE_SMALL_MIN, FONT_COLOR_TITLE_MAIN)
|
||||
view._place_goth_photo_or_fallback(cw // 2, strip_cy + 12, p2, bot_line, FONT_SIZE_SMALL_MIN - 1, ACCENT_GOLD)
|
||||
|
||||
trick_top = strip_cy + strip_h // 2 + 8
|
||||
trick_bot = player_top_y - 12
|
||||
center_cy = (trick_top + trick_bot) // 2
|
||||
avail_trick_h = max(120, trick_bot - trick_top)
|
||||
t_scale = min(1.0, max(0.76, (avail_trick_h - 52) / max(1, WT_TRICK_CARD_SIZE[1])))
|
||||
trick_sz = (int(round(WT_TRICK_CARD_SIZE[0] * t_scale)), int(round(WT_TRICK_CARD_SIZE[1] * t_scale)))
|
||||
else:
|
||||
felt_top = max(ty1 + 12, top_obs_y + 10)
|
||||
felt_bot = min(ty2 - 12, player_top_y - WT_HAND_TOP_EXTEND_PX - 10)
|
||||
center_cy = (felt_top + felt_bot) // 2 + 12
|
||||
trick_sz = WT_TRICK_CARD_SIZE
|
||||
|
||||
info_x = max(left_obs_x + 112, tx1 + 148)
|
||||
info_y = felt_top + 42
|
||||
view._draw_framed_panel(info_x, info_y, 206, 78, frame_style="purple")
|
||||
for dy, txt, col in (
|
||||
(-21, f"{t('wt_lbl_schlag')}: {schlag_txt}", ACCENT_GOLD),
|
||||
(0, f"{t('wt_lbl_trumpf')}: {trump_txt}", FONT_COLOR_TITLE_MAIN),
|
||||
(21, t("wt_lbl_tricks_pair", eng.team_tricks[0], eng.team_tricks[1]),
|
||||
FONT_COLOR_STATUS_WIN if eng.team_tricks[0] >= eng.team_tricks[1] else FG_COLOR),
|
||||
):
|
||||
ph = view._make_goth_photo(txt, FONT_SIZE_SMALL_MIN, col, 186)
|
||||
view._place_goth_photo_or_fallback(info_x, info_y + dy, ph, txt, FONT_SIZE_SMALL_MIN, col)
|
||||
|
||||
score_x = min(right_obs_x - 112, tx2 - 148)
|
||||
score_y = felt_top + 42
|
||||
view._draw_framed_panel(
|
||||
score_x, score_y, 206, 78, frame_style="gold" if (gesp_0 or gesp_1) else "purple"
|
||||
)
|
||||
for dy, txt, col in (
|
||||
(-21, t("wt_lbl_match_pts", eng.team_points[0], eng.team_points[1]), FONT_COLOR_TITLE_MAIN),
|
||||
(0, t("wt_lbl_cur_stake", eng.current_stake), ACCENT_GOLD),
|
||||
(21, t("wt_lbl_gespannt_warn") if (gesp_0 or gesp_1) else t("wt_lbl_target_11"),
|
||||
ERROR_FG if (gesp_0 or gesp_1) else MUTED_FG),
|
||||
):
|
||||
ph = view._make_goth_photo(txt, FONT_SIZE_SMALL_MIN, col, 186)
|
||||
view._place_goth_photo_or_fallback(score_x, score_y + dy, ph, txt, FONT_SIZE_SMALL_MIN, col)
|
||||
|
||||
center_cx = cw // 2
|
||||
tw, th = trick_sz
|
||||
dx_off = int(tw * 0.98)
|
||||
dy_off = int(th * 0.24)
|
||||
slot_offsets = {0: (0, dy_off), 1: (-dx_off, 0), 2: (0, -dy_off), 3: (dx_off, 0)}
|
||||
|
||||
active_cards = view._visible_completed_trick if view._visible_completed_trick else eng.current_trick
|
||||
if not active_cards:
|
||||
view.arena_canvas.create_oval(
|
||||
center_cx - 56, center_cy - 38, center_cx + 56, center_cy + 38,
|
||||
outline=SUBTLE_BORDER, width=2, dash=(4, 4), tags="fg",
|
||||
)
|
||||
return
|
||||
|
||||
win_seat = eng.last_trick_winner if view._visible_completed_trick else None
|
||||
for seat_id, card in active_cards:
|
||||
dx, dy = slot_offsets.get(seat_id, (0, 0))
|
||||
cx, cy = center_cx + dx, center_cy + dy
|
||||
ph = view.ctx.assets.get_card_photo(card.image_filename, size=trick_sz, theme=BAVARIAN_CARD_THEME)
|
||||
if ph is not None:
|
||||
view._photo_refs.append(ph)
|
||||
view.arena_canvas.create_image(cx, cy, image=ph, anchor="center", tags="fg")
|
||||
border_c = ACCENT_GOLD if seat_id == win_seat else BORDER_COLOR
|
||||
view.arena_canvas.create_rectangle(
|
||||
cx - tw // 2 - 2, cy - th // 2 - 2, cx + tw // 2 + 2, cy + th // 2 + 2,
|
||||
outline=border_c, width=3 if seat_id == win_seat else 1, 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]]:
|
||||
eng = view.engine
|
||||
human = eng.seats[0]
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
ext = 8 if compact else WT_HAND_TOP_EXTEND_PX
|
||||
eff_top = max(210, player_zone_top - ext)
|
||||
avail_h = max(146 if compact else 168, player_zone_bot - eff_top)
|
||||
zone_cy = (eff_top + player_zone_bot) // 2
|
||||
|
||||
base_w, base_h = PLAYING_CARD_SIZE
|
||||
n_cards = len(human.hand)
|
||||
max_hand_w = max(300, cw - (48 if compact else 120))
|
||||
card_w_by_w = (max_hand_w - max(0, n_cards - 1) * 10) // max(1, max(5, n_cards))
|
||||
target_h = max(104 if compact else 116, min(WT_MAX_HAND_CARD_H, avail_h - 42))
|
||||
card_w = max(68 if compact else 78, min(card_w_by_w, int(round(base_w * (target_h / max(1, base_h))))))
|
||||
card_h = int(round(card_w * (base_h / max(1, base_w))))
|
||||
card_sz = (card_w, card_h)
|
||||
|
||||
is_my_play_turn = (
|
||||
eng.phase == PHASE_TRICK_PLAY
|
||||
and eng.turn_seat == 0
|
||||
and not view._visible_completed_trick
|
||||
)
|
||||
playable_set = set(eng.get_playable_cards(0)) if is_my_play_turn else set()
|
||||
|
||||
step = card_w + (10 if compact else 14)
|
||||
span_w = card_w + max(0, n_cards - 1) * step if n_cards else card_w
|
||||
|
||||
my_role = (
|
||||
f" ({t('wt_tag_dealer')})" if eng.dealer_seat == 0
|
||||
else (f" ({t('wt_tag_ansager')})" if eng.ansager_seat == 0 else "")
|
||||
)
|
||||
lbl_txt = f"{t('wt_your_hand_lbl')}{my_role}"
|
||||
lbl_sz = max(12 if compact else 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 240
|
||||
|
||||
box_w = max(320, min(cw - (18 if compact else 72), max(span_w + 48, txt_w + 48)))
|
||||
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 eng.turn_seat == 0 else "purple"
|
||||
)
|
||||
|
||||
hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||
start_x = box_cx - span_w // 2
|
||||
base_top = (zone_cy - 8) - 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 - (8 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",
|
||||
)
|
||||
|
||||
badge_key = card_role_badge_key(card, eng.schlag_rank, eng.trump_suit)
|
||||
if badge_key:
|
||||
b_txt = t(badge_key)
|
||||
b_col = (
|
||||
ACCENT_GOLD
|
||||
if badge_key in ("wt_role_max", "wt_role_belli", "wt_role_spitz", "wt_role_guade")
|
||||
else ACCENT_GOTH
|
||||
)
|
||||
view.arena_canvas.create_rectangle(
|
||||
cx_left + 3, cy_top + card_h - 19, cx_left + card_w - 3, cy_top + card_h - 3,
|
||||
fill="#0d0914", outline=b_col, width=1, tags="fg",
|
||||
)
|
||||
view.arena_canvas.create_text(
|
||||
cx_left + card_w // 2, cy_top + card_h - 11, text=b_txt,
|
||||
font=("Georgia", 8, "bold"), fill=b_col, tags="fg",
|
||||
)
|
||||
|
||||
hit_rects.append((card, cx_left, cy_top, cx_left + card_w, cy_top + card_h))
|
||||
|
||||
view._place_goth_photo_or_fallback(
|
||||
box_cx, zone_cy + box_h // 2 - 14, lbl_ph, lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN
|
||||
)
|
||||
return hit_rects
|
||||
|
|
@ -0,0 +1,303 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/views/watten_menu_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
||||
from games.party.watten.models.watten_tutorials import build_watten_tutorial_units
|
||||
from games.party.watten.views.watten_table_view import WattenTableView
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
BAVARIAN_CARD_THEME,
|
||||
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,
|
||||
WT_BOT_COUNT,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.layout_mode import LayoutMode
|
||||
from view.tutorial.tutorial_hub_view import TutorialHubView
|
||||
from view.tutorial.tutorial_models import TutorialProgressRepo, TutorialUnit
|
||||
from view.tutorial.tutorial_runner_view import TutorialRunnerView
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.inputs.goth_entry import GothEntry
|
||||
from view.widgets.shared_bases.menu_body_canvas import MenuBodyCanvas
|
||||
|
||||
GAME_FOLDER_ID = "party/watten"
|
||||
GAME_TITLE_KEY = "game_title_watten"
|
||||
|
||||
|
||||
class WattenMenuView:
|
||||
"""Vorauswahl-Menü für Oberbayerisches Watten inkl. interaktivem 4-Kapitel-Tutorial (Desktop & Kompakt)."""
|
||||
|
||||
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(WT_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 _open_tutorial_hub(self):
|
||||
if self._bot_entries:
|
||||
self._collect_and_save_bots()
|
||||
units = build_watten_tutorial_units()
|
||||
|
||||
def open_hub():
|
||||
TutorialHubView(
|
||||
self.ctx,
|
||||
game_folder_id=GAME_FOLDER_ID,
|
||||
game_title_key=GAME_TITLE_KEY,
|
||||
units=units,
|
||||
on_start_unit=start_unit,
|
||||
on_back_to_game_menu=self.show,
|
||||
).show()
|
||||
|
||||
def start_unit(unit: TutorialUnit):
|
||||
TutorialRunnerView(
|
||||
self.ctx,
|
||||
game_folder_id=GAME_FOLDER_ID,
|
||||
unit=unit,
|
||||
on_finish_to_hub=open_hub,
|
||||
card_theme=BAVARIAN_CARD_THEME,
|
||||
)
|
||||
|
||||
open_hub()
|
||||
|
||||
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("wt_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_norm, btn_purp = self.ctx.assets.raw_btn_default, self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
units = build_watten_tutorial_units()
|
||||
done_cnt = len(TutorialProgressRepo.get_completed_units(pid, GAME_FOLDER_ID))
|
||||
tut_unseen = done_cnt == 0
|
||||
tut_btn = ImageButton(
|
||||
cv,
|
||||
t("wt_btn_open_tutorial", done_cnt, len(units)),
|
||||
btn_fire if tut_unseen else btn_norm,
|
||||
btn_fire if tut_unseen else btn_purp,
|
||||
self._open_tutorial_hub,
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=216,
|
||||
height=36,
|
||||
style="fire" if tut_unseen else "amethyst",
|
||||
)
|
||||
|
||||
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(WT_BOT_COUNT):
|
||||
def_name = t("bot_default_name", 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)))
|
||||
else:
|
||||
b_name, b_lvl = def_name, 2
|
||||
|
||||
entry = GothEntry(cv, self.ctx.assets, width=190, 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=220, height=36,
|
||||
)
|
||||
self._bot_entries.append(entry)
|
||||
self._bot_lvl_vars.append(l_var)
|
||||
self._bot_dds.append(dd)
|
||||
|
||||
start_btn = ImageButton(
|
||||
cv,
|
||||
t("wt_start_btn"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: WattenTableView(
|
||||
self.ctx, variant_key="watten_std", bot_configs=self._collect_and_save_bots(), on_back_to_menu=self.show
|
||||
),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=210,
|
||||
height=40,
|
||||
style="fire",
|
||||
)
|
||||
|
||||
seat_role_keys = ("wt_menu_seat_west", "wt_menu_seat_partner", "wt_menu_seat_east")
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
rw, rh = self.ctx.root.winfo_width(), self.ctx.root.winfo_height()
|
||||
is_mobile = LayoutMode.is_compact(rw, rh) or (w < 780)
|
||||
pad_x = LayoutMode.outer_pad_x(w, h, desktop_ratio=0.075, desktop_min=64)
|
||||
|
||||
box_w = min(940, w - 2 * pad_x)
|
||||
cx = w // 2
|
||||
x_left = cx - box_w // 2
|
||||
cur_y = 12 if is_mobile else max(20, int(h * 0.045))
|
||||
|
||||
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG - (4 if is_mobile else 0), FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("wt_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() + 14
|
||||
|
||||
s1_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("wt_rules_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(s1_ph)
|
||||
cv.create_image(x_left + 4, cur_y, image=s1_ph, anchor="nw", tags="fg")
|
||||
cur_y += s1_ph.height() + 6
|
||||
|
||||
r_box_h = 114 if is_mobile else 84
|
||||
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_watten_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
d_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("wt_rule_summary"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_DEFAULT,
|
||||
max_width=box_w - (44 if is_mobile else 270), align="left",
|
||||
)
|
||||
self._photo_refs.extend([v_ph, d_ph])
|
||||
if is_mobile:
|
||||
cv.create_image(x_left + 22, cur_y + 22, image=v_ph, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 20, cur_y + 24, window=tut_btn, anchor="e", tags="fg")
|
||||
cv.create_image(x_left + 22, cur_y + 72, image=d_ph, anchor="w", tags="fg")
|
||||
else:
|
||||
cv.create_image(x_left + 26, r_cy - 16, image=v_ph, anchor="w", tags="fg")
|
||||
cv.create_image(x_left + 26, r_cy + 16, image=d_ph, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 24, r_cy, window=tut_btn, anchor="e", tags="fg")
|
||||
cur_y += r_box_h + 14
|
||||
|
||||
s2_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("wt_bots_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(s2_ph)
|
||||
cv.create_image(x_left + 4, cur_y, image=s2_ph, anchor="nw", tags="fg")
|
||||
cur_y += s2_ph.height() + 6
|
||||
|
||||
if is_mobile:
|
||||
b_box_h = 286
|
||||
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")
|
||||
|
||||
in_w = box_w - 44
|
||||
ent_w = max(140, int(in_w * 0.44))
|
||||
dd_w = max(150, in_w - ent_w - 10)
|
||||
for idx in range(WT_BOT_COUNT):
|
||||
ry = cur_y + 26 + idx * 72
|
||||
seat_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t(seat_role_keys[idx]), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(seat_lbl)
|
||||
cv.create_image(x_left + 22, ry, image=seat_lbl, anchor="w", tags="fg")
|
||||
|
||||
ent = self._bot_entries[idx]
|
||||
if hasattr(ent, "resize") and ent._width != ent_w:
|
||||
ent.resize(ent_w)
|
||||
cv.create_window(x_left + 22, ry + 30, window=ent, 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 + box_w - 22, ry + 30, window=dd, anchor="e", tags="fg")
|
||||
|
||||
cv.create_window(x_left + box_w - 24, cur_y + b_box_h - 32, window=start_btn, anchor="e", tags="fg")
|
||||
cv.set_scrollable_height(cur_y + b_box_h + 20, h)
|
||||
else:
|
||||
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")
|
||||
|
||||
ent_w = 220
|
||||
dd_w = max(200, box_w - 446)
|
||||
for idx in range(WT_BOT_COUNT):
|
||||
ry = cur_y + 38 + idx * 50
|
||||
seat_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t(seat_role_keys[idx]), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||
)
|
||||
self._photo_refs.append(seat_lbl)
|
||||
cv.create_image(x_left + 28, ry, image=seat_lbl, anchor="w", tags="fg")
|
||||
|
||||
ent = self._bot_entries[idx]
|
||||
if hasattr(ent, "resize") and ent._width != ent_w:
|
||||
ent.resize(ent_w)
|
||||
cv.create_window(x_left + 168, ry, window=ent, 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 + 402, 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.set_scrollable_height(cur_y + b_box_h + 20, h)
|
||||
|
||||
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(460, cv.winfo_width()), max(560, cv.winfo_height()))
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/views/watten_result_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from resources.code_res.game_constants import (
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_COLOR_STATUS_LOSS,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_HEADING,
|
||||
SUBTLE_BORDER,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
|
||||
class WattenResultDialog(CasinoResultDialogBase):
|
||||
"""Satz-Abschlussdialog für Watten (Endstand bis 11 Punkte, gespielte Hände & XP)."""
|
||||
|
||||
def __init__(
|
||||
self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu
|
||||
):
|
||||
dlg_w = 640
|
||||
dlg_h = 356 + (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):
|
||||
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 = 30
|
||||
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
|
||||
cur_y += hl_ph.height() + 16
|
||||
|
||||
# Team-Vergleichsboxen (Dein Team vs. Gegner-Team)
|
||||
box_w_sm, box_h_sm = (w - 92) // 2, 118
|
||||
teams = [
|
||||
(
|
||||
self.data["team0_names"],
|
||||
self.data["team0_pts"],
|
||||
p_won,
|
||||
),
|
||||
(
|
||||
self.data["team1_names"],
|
||||
self.data["team1_pts"],
|
||||
not p_won,
|
||||
),
|
||||
]
|
||||
for idx, (names_str, pts, is_w) in enumerate(teams):
|
||||
tx = 38 + idx * (box_w_sm + 16) + box_w_sm // 2
|
||||
ty = cur_y + box_h_sm // 2
|
||||
f_ph = self.assets.get_box_photo(
|
||||
"box_gold_small" if is_w else "box_purple", (box_w_sm, box_h_sm)
|
||||
)
|
||||
if f_ph:
|
||||
self._photo_refs.append(f_ph)
|
||||
self.create_image(tx, ty, image=f_ph, anchor="center")
|
||||
|
||||
n_ph = self.assets.get_goth_text_photo(
|
||||
names_str,
|
||||
FONT_SIZE_BODY - 1,
|
||||
FONT_COLOR_TITLE_MAIN if is_w else FONT_COLOR_HEADING_SUB,
|
||||
max_width=box_w_sm - 24,
|
||||
)
|
||||
p_ph = self.assets.get_goth_text_photo(
|
||||
t("wt_popup_team_pts", pts),
|
||||
FONT_SIZE_HEADING,
|
||||
FONT_COLOR_STATUS_WIN if is_w else FONT_COLOR_BODY_DEFAULT,
|
||||
max_width=box_w_sm - 24,
|
||||
)
|
||||
self._photo_refs.extend([n_ph, p_ph])
|
||||
self.create_image(tx, ty - 22, image=n_ph, anchor="center")
|
||||
self.create_image(tx, ty + 20, image=p_ph, anchor="center")
|
||||
|
||||
cur_y += box_h_sm + 18
|
||||
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("wt_popup_new_match_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")
|
||||
|
|
@ -0,0 +1,323 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/views/watten_table_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import tkinter as tk
|
||||
|
||||
from games.party.watten.models.watten_engine import (
|
||||
PHASE_HAND_DONE,
|
||||
PHASE_MATCH_DONE,
|
||||
PHASE_TRICK_PLAY,
|
||||
WattenEngine,
|
||||
)
|
||||
from games.party.watten.views.watten_arena_renderer import WattenArenaRenderer
|
||||
from games.party.watten.views.watten_result_dialog import WattenResultDialog
|
||||
from games.party.watten.views.watten_turn_driver import WattenTurnDriver
|
||||
from models.cards.bavarian_deck import BavarianCard
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
WT_BOT_TURN_DELAY_MS,
|
||||
WT_TRICK_CLEAR_DELAY_MS,
|
||||
WT_VARIANTS,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.shared_bases.casino_arena_base import CasinoArenaBase
|
||||
|
||||
GAME_FOLDER_ID = "party/watten"
|
||||
|
||||
|
||||
class WattenTableView(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 WT_VARIANTS else "watten_std"
|
||||
cfg = WT_VARIANTS[v_key]
|
||||
self._init_arena_state(context, v_key, cfg, on_back_to_menu)
|
||||
|
||||
self._bot_configs = list(bot_configs)
|
||||
self.engine = WattenEngine()
|
||||
self.engine.configure_seats(self.ctx.profile["name"], self._bot_configs)
|
||||
|
||||
self.match_start_time: float = time.time()
|
||||
self._hand_hit_rects: list[tuple[BavarianCard, int, int, int, int]] = []
|
||||
self._visible_completed_trick: list[tuple[int, BavarianCard]] = []
|
||||
self._trick_pause_job: str | None = None
|
||||
self._last_popup_payload: dict | None = None
|
||||
|
||||
self.ctx.sounds.play_ingame_music()
|
||||
self._build_ui()
|
||||
self._start_new_match()
|
||||
|
||||
def _cancel_jobs(self):
|
||||
if self._trick_pause_job is not None:
|
||||
try:
|
||||
self.ctx.root.after_cancel(self._trick_pause_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._trick_pause_job = None
|
||||
super()._cancel_jobs()
|
||||
|
||||
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=150,
|
||||
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_match_over 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):
|
||||
eng = self.engine
|
||||
schlag_s = t(f"bav_rank_{eng.schlag_rank}") if eng.schlag_rank else "?"
|
||||
trump_s = t(f"bav_suit_{eng.trump_suit}") if eng.trump_suit else "?"
|
||||
self._set_hud_segments(
|
||||
t("wt_hud_score", eng.team_points[0], eng.team_points[1], eng.current_stake),
|
||||
t("wt_hud_ansage", schlag_s, trump_s),
|
||||
t("wt_hud_tricks", eng.team_tricks[0], eng.team_tricks[1]),
|
||||
)
|
||||
|
||||
def _start_new_match(self):
|
||||
self._cancel_jobs()
|
||||
if self._result_dialog is not None:
|
||||
self._result_dialog.close_dialog()
|
||||
self._result_dialog = None
|
||||
self._visible_completed_trick.clear()
|
||||
self._last_popup_payload = None
|
||||
self.match_start_time = time.time()
|
||||
|
||||
self.engine.start_new_match()
|
||||
self.ctx.sounds.play("deal")
|
||||
if not self._canvas_alive():
|
||||
self._build_ui()
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _start_next_hand(self):
|
||||
self._cancel_jobs()
|
||||
self._visible_completed_trick.clear()
|
||||
self.engine.start_new_hand(rotate_dealer=True)
|
||||
self.ctx.sounds.play("deal")
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
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()
|
||||
)
|
||||
bot_bounds = WattenArenaRenderer.draw_other_seats(
|
||||
self, cw, pad_x, pad_top, table_rect
|
||||
)
|
||||
WattenArenaRenderer.draw_center_trick_area(
|
||||
self, cw, table_rect, bot_bounds, p_top
|
||||
)
|
||||
self._hand_hit_rects = WattenArenaRenderer.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):
|
||||
WattenTurnDriver.sync_turn_controls(self)
|
||||
|
||||
def _on_human_ask_schoenere(self):
|
||||
if self.engine.ask_schoenere(0):
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_human_reply_schoenere(self, accept: bool):
|
||||
if self.engine.reply_schoenere(0, accept):
|
||||
if accept:
|
||||
self.ctx.sounds.play("deal")
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_human_schlag(self, rank: str):
|
||||
if self.engine.declare_schlag(0, rank):
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_human_trumpf(self, suit: str):
|
||||
if self.engine.declare_trumpf(0, suit):
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_human_ausschaffen(self):
|
||||
if self.engine.initiate_ausschaffen(0):
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_human_reply_ausschaffen(self, hold: bool):
|
||||
if self.engine.respond_ausschaffen(0, hold):
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _on_canvas_click(self, event):
|
||||
if (
|
||||
self._fx_overlay is not None
|
||||
or self._result_dialog is not None
|
||||
or self._visible_completed_trick
|
||||
or self.engine.phase != PHASE_TRICK_PLAY
|
||||
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:
|
||||
res = self.engine.play_card(0, card)
|
||||
if res == "invalid":
|
||||
self.ctx.sounds.play("lose")
|
||||
self.status_var.set(t("wt_status_trump_compulsion"))
|
||||
return
|
||||
self.ctx.sounds.play("click")
|
||||
self._handle_post_card_play(res)
|
||||
return
|
||||
|
||||
def _handle_post_card_play(self, res: str):
|
||||
if res in ("trick_completed", "hand_completed", "match_completed"):
|
||||
self._visible_completed_trick = list(self.engine.last_completed_trick)
|
||||
win_id = self.engine.last_trick_winner
|
||||
if win_id is not None:
|
||||
self.status_var.set(
|
||||
t("wt_status_trick_winner", self.engine.seats[win_id].name)
|
||||
)
|
||||
self._render_table()
|
||||
self._sync_turn_controls()
|
||||
self._trick_pause_job = self.ctx.root.after(
|
||||
WT_TRICK_CLEAR_DELAY_MS, self._after_trick_pause
|
||||
)
|
||||
return
|
||||
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _after_trick_pause(self):
|
||||
self._trick_pause_job = None
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
self._visible_completed_trick.clear()
|
||||
self._render_table()
|
||||
self._advance_flow()
|
||||
|
||||
def _advance_flow(self):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
if self.engine.phase == PHASE_MATCH_DONE:
|
||||
self._finalize_match()
|
||||
return
|
||||
self._sync_turn_controls()
|
||||
if self.engine.phase != PHASE_HAND_DONE and self.engine.turn_seat != 0:
|
||||
self._turn_job = self.ctx.root.after(
|
||||
WT_BOT_TURN_DELAY_MS, lambda: WattenTurnDriver.execute_bot_step(self)
|
||||
)
|
||||
|
||||
def _finalize_match(self):
|
||||
self._set_bottom_buttons([])
|
||||
self.status_var.set("")
|
||||
|
||||
human_won = self.engine.match_winner_team == 0
|
||||
duration = max(1.0, time.time() - self.match_start_time)
|
||||
|
||||
prog_before = self.ctx.refresh_game_progress()
|
||||
opp_levels = [self.engine.seats[1].ai_level, self.engine.seats[3].ai_level]
|
||||
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,
|
||||
"team0_names": f"{self.engine.seats[0].name} & {self.engine.seats[2].name}",
|
||||
"team1_names": f"{self.engine.seats[1].name} & {self.engine.seats[3].name}",
|
||||
"team0_pts": self.engine.team_points[0],
|
||||
"team1_pts": self.engine.team_points[1],
|
||||
"xp_gained": xp_gained,
|
||||
"leveled_to": new_lvl if new_lvl > old_lvl else None,
|
||||
}
|
||||
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"]
|
||||
lvl_to = payload["leveled_to"]
|
||||
return {
|
||||
"headline": t("wt_popup_match_won") if p_won else t("wt_popup_match_lost"),
|
||||
"player_won": p_won,
|
||||
"team0_names": payload["team0_names"],
|
||||
"team1_names": payload["team1_names"],
|
||||
"team0_pts": payload["team0_pts"],
|
||||
"team1_pts": payload["team1_pts"],
|
||||
"xp_gained": payload["xp_gained"],
|
||||
"new_level_title": (
|
||||
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
|
||||
if lvl_to is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
def _show_result_dialog_now(self, popup_data: dict):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
self._result_dialog = WattenResultDialog(
|
||||
parent=self.arena_canvas,
|
||||
assets=self.ctx.assets,
|
||||
sounds=self.ctx.sounds,
|
||||
result_data=popup_data,
|
||||
on_next_round=self._start_new_match,
|
||||
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),
|
||||
)
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/watten/views/watten_turn_driver.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.party.watten.models.watten_ai import WattenBotAI
|
||||
from games.party.watten.models.watten_engine import (
|
||||
PHASE_ANSAGE_SCHLAG,
|
||||
PHASE_ANSAGE_TRUMPF,
|
||||
PHASE_AUSSCHAFFEN_REPLY,
|
||||
PHASE_HAND_DONE,
|
||||
PHASE_MATCH_DONE,
|
||||
PHASE_SCHOENERE_ASK,
|
||||
PHASE_SCHOENERE_REPLY,
|
||||
PHASE_TRICK_PLAY,
|
||||
)
|
||||
from games.party.watten.models.watten_rules import WATTEN_RANKS_32
|
||||
from resources.code_res.game_constants import BAVARIAN_SUITS
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
|
||||
class WattenTurnDriver:
|
||||
"""Kapselt die Phasen-Buttons der Fußleiste sowie die KI-Zugausführung für Watten."""
|
||||
|
||||
@staticmethod
|
||||
def sync_turn_controls(view) -> None:
|
||||
if not hasattr(view, "bottom_bar") or not view.bottom_bar.winfo_exists():
|
||||
return
|
||||
eng = view.engine
|
||||
btn_norm = view.ctx.assets.raw_btn_default
|
||||
btn_purp = view.ctx.assets.raw_btn_purple
|
||||
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
if eng.phase == PHASE_MATCH_DONE:
|
||||
view.status_var.set("")
|
||||
view._set_bottom_buttons([])
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_HAND_DONE:
|
||||
w_team = eng.hand_winner_team or 0
|
||||
msg_key = "wt_status_hand_won" if w_team == 0 else "wt_status_hand_lost"
|
||||
view.status_var.set(t(msg_key, eng.hand_points_awarded))
|
||||
nxt_btn = ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_next_hand"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
view._start_next_hand,
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=188,
|
||||
height=32,
|
||||
style="fire",
|
||||
)
|
||||
view._set_bottom_buttons([nxt_btn], overflow_buttons=[view._menu_btn])
|
||||
return
|
||||
|
||||
if view._visible_completed_trick or eng.turn_seat != 0:
|
||||
if not view._visible_completed_trick:
|
||||
actor = eng.seats[eng.turn_seat].name
|
||||
view.status_var.set(t("wt_status_waiting_for", actor))
|
||||
view._set_bottom_buttons([], overflow_buttons=[view._menu_btn])
|
||||
return
|
||||
|
||||
if eng.phase in (PHASE_SCHOENERE_ASK, PHASE_ANSAGE_SCHLAG):
|
||||
view.status_var.set(t("wt_status_pick_schlag"))
|
||||
rank_btns = [
|
||||
ImageButton(
|
||||
view.bottom_bar,
|
||||
rk,
|
||||
btn_norm,
|
||||
btn_purp,
|
||||
lambda r=rk: view._on_human_schlag(r),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=54,
|
||||
height=30,
|
||||
style="amethyst",
|
||||
)
|
||||
for rk in WATTEN_RANKS_32
|
||||
]
|
||||
ovf = [view._menu_btn]
|
||||
if eng.phase == PHASE_SCHOENERE_ASK:
|
||||
ovf.insert(
|
||||
0,
|
||||
ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_ask_schoenere"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
view._on_human_ask_schoenere,
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=136,
|
||||
height=30,
|
||||
style="fire",
|
||||
),
|
||||
)
|
||||
view._set_bottom_buttons(rank_btns, overflow_buttons=ovf)
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_SCHOENERE_REPLY:
|
||||
view.status_var.set(t("wt_status_reply_schoenere", eng.seats[eng.ansager_seat].name))
|
||||
b_yes = ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_schoenere_yes"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: view._on_human_reply_schoenere(True),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=164,
|
||||
height=32,
|
||||
style="fire",
|
||||
)
|
||||
b_no = ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_schoenere_no"),
|
||||
btn_norm,
|
||||
btn_purp,
|
||||
lambda: view._on_human_reply_schoenere(False),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=164,
|
||||
height=32,
|
||||
style="amethyst",
|
||||
)
|
||||
view._set_bottom_buttons([b_yes, b_no], overflow_buttons=[view._menu_btn])
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_ANSAGE_TRUMPF:
|
||||
view.status_var.set(t("wt_status_pick_trumpf", t(f"bav_rank_{eng.schlag_rank}")))
|
||||
suit_btns = [
|
||||
ImageButton(
|
||||
view.bottom_bar,
|
||||
t(f"bav_suit_{s}"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda su=s: view._on_human_trumpf(su),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=116,
|
||||
height=32,
|
||||
style="fire",
|
||||
)
|
||||
for s in BAVARIAN_SUITS
|
||||
]
|
||||
view._set_bottom_buttons(suit_btns, overflow_buttons=[view._menu_btn])
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_AUSSCHAFFEN_REPLY:
|
||||
view.status_var.set(t("wt_status_opp_raised", eng.proposed_stake, eng.current_stake))
|
||||
b_hold = ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_hold_stake", eng.proposed_stake),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: view._on_human_reply_ausschaffen(True),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=176,
|
||||
height=32,
|
||||
style="fire",
|
||||
)
|
||||
b_fold = ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_fold_hand"),
|
||||
btn_norm,
|
||||
btn_purp,
|
||||
lambda: view._on_human_reply_ausschaffen(False),
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=168,
|
||||
height=32,
|
||||
style="amethyst",
|
||||
)
|
||||
view._set_bottom_buttons([b_hold, b_fold], overflow_buttons=[view._menu_btn])
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_TRICK_PLAY:
|
||||
playable = eng.get_playable_cards(0)
|
||||
if len(playable) < len(eng.seats[0].hand):
|
||||
view.status_var.set(t("wt_status_trump_compulsion"))
|
||||
else:
|
||||
view.status_var.set(t("wt_status_your_turn_card"))
|
||||
|
||||
prim: list[ImageButton] = []
|
||||
if eng.can_seat_ausschaffen(0):
|
||||
prim.append(
|
||||
ImageButton(
|
||||
view.bottom_bar,
|
||||
t("wt_btn_ausschaffen", eng.current_stake + 1),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
view._on_human_ausschaffen,
|
||||
sound_mgr=view.ctx.sounds,
|
||||
width=186,
|
||||
height=32,
|
||||
style="fire",
|
||||
)
|
||||
)
|
||||
view._set_bottom_buttons(prim, overflow_buttons=[view._menu_btn])
|
||||
|
||||
@staticmethod
|
||||
def execute_bot_step(view) -> None:
|
||||
view._turn_job = None
|
||||
if not view._canvas_alive() or view.engine.turn_seat == 0:
|
||||
return
|
||||
eng = view.engine
|
||||
bot = eng.seats[eng.turn_seat]
|
||||
|
||||
if eng.phase == PHASE_SCHOENERE_ASK:
|
||||
if WattenBotAI.should_ask_schoenere(bot):
|
||||
bot.status_text = t("wt_act_asked_schoenere")
|
||||
eng.ask_schoenere(bot.seat_id)
|
||||
else:
|
||||
eng.skip_schoenere(bot.seat_id)
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_SCHOENERE_REPLY:
|
||||
accept = WattenBotAI.should_accept_schoenere(bot)
|
||||
bot.status_text = t("wt_act_schoenere_yes") if accept else t("wt_act_schoenere_no")
|
||||
eng.reply_schoenere(bot.seat_id, accept)
|
||||
if accept:
|
||||
view.ctx.sounds.play("deal")
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_ANSAGE_SCHLAG:
|
||||
rk = WattenBotAI.choose_schlag(bot)
|
||||
bot.status_text = f"{t('wt_lbl_schlag')}: {t(f'bav_rank_{rk}')}"
|
||||
eng.declare_schlag(bot.seat_id, rk)
|
||||
view.ctx.sounds.play("click")
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_ANSAGE_TRUMPF:
|
||||
su = WattenBotAI.choose_trumpf(bot, eng.schlag_rank or "O")
|
||||
bot.status_text = f"{t('wt_lbl_trumpf')}: {t(f'bav_suit_{su}')}"
|
||||
eng.declare_trumpf(bot.seat_id, su)
|
||||
view.ctx.sounds.play("click")
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_AUSSCHAFFEN_REPLY:
|
||||
hold = WattenBotAI.should_hold_ausschaffen(eng, bot)
|
||||
bot.status_text = t("wt_act_held", eng.proposed_stake) if hold else t("wt_act_folded")
|
||||
eng.respond_ausschaffen(bot.seat_id, hold)
|
||||
view.ctx.sounds.play("click" if hold else "stand")
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
if eng.phase == PHASE_TRICK_PLAY:
|
||||
if WattenBotAI.should_ausschaffen(eng, bot):
|
||||
bot.status_text = t("wt_act_raised", eng.current_stake + 1)
|
||||
eng.initiate_ausschaffen(bot.seat_id)
|
||||
view.ctx.sounds.play("stand")
|
||||
view._render_table()
|
||||
view._advance_flow()
|
||||
return
|
||||
|
||||
chosen = WattenBotAI.choose_card(eng, bot)
|
||||
bot.status_text = f"{t(f'bav_suit_{chosen.suit}')} {chosen.rank}"
|
||||
res = eng.play_card(bot.seat_id, chosen)
|
||||
view.ctx.sounds.play("click")
|
||||
view._handle_post_card_play(res)
|
||||
|
|
@ -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.cards.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
|
||||
|
|
@ -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.cards.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,
|
||||
}
|
||||
|
|
@ -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()
|
||||
|
|
@ -0,0 +1,310 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/party/zehner_raus/views/zehner_raus_arena_renderer.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.cards.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
|
||||
|
||||
ZR_GRID_SUITS = (
|
||||
("E", 0, 0),
|
||||
("B", 0, 1),
|
||||
("H", 1, 0),
|
||||
("S", 1, 1),
|
||||
)
|
||||
|
||||
|
||||
class ZehnerRausArenaRenderer:
|
||||
"""Rendert 10er raus (Desktop mit Seiten-Bots vs. Kompakt/Mobile mit 3er-Bot-Leiste oben)."""
|
||||
|
||||
@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]:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
bots = view.engine.seats[1:]
|
||||
if len(bots) < 3:
|
||||
return ty1 + 20, tx1 + 20, tx2 - 20
|
||||
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
if compact:
|
||||
gap = 6
|
||||
avail_w = max(320, cw - 2 * pad_x)
|
||||
box_w = min(212, (avail_w - 2 * gap) // 3)
|
||||
box_h = 80
|
||||
start_x = (cw - (3 * box_w + 2 * gap)) // 2 + box_w // 2
|
||||
top_cy = pad_top + box_h // 2 + 2
|
||||
coords = [(start_x + i * (box_w + gap), top_cy) for i in range(3)]
|
||||
back_sz = (32, 48)
|
||||
else:
|
||||
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), (cw // 2, top_cy), (right_cx, mid_side_y)]
|
||||
back_sz = ZR_BOT_BACK_SIZE
|
||||
|
||||
name_sz = max(12 if compact else 14, FONT_SIZE_SMALL_MIN if compact else FONT_SIZE_BODY - 1)
|
||||
sub_sz = max(11 if compact else 12, FONT_SIZE_SMALL_MIN - (1 if compact else 0))
|
||||
back_ph = view.ctx.assets.get_card_back_photo(size=back_sz, 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 and (not compact or box_w >= 178):
|
||||
vis_backs = min(4 if compact else 5, n_cards)
|
||||
step_b = 7 if compact else 9
|
||||
bx0 = bx - box_w // 2 + (10 if compact else 14)
|
||||
by0 = by - back_sz[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 + (22 if compact else 30)
|
||||
max_tw = box_w - (74 if compact else 96)
|
||||
else:
|
||||
txt_cx = bx
|
||||
max_tw = box_w - 18
|
||||
|
||||
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)
|
||||
|
||||
dy = 20 if compact else 22
|
||||
view._place_goth_photo_or_fallback(txt_cx, by - dy, 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 + dy, a_ph, act_txt, sub_sz, FG_COLOR)
|
||||
|
||||
if compact:
|
||||
# Volle Breite links & rechts frei für das 2x2-Farbenkreuz!
|
||||
return (top_cy + box_h // 2, 0, cw)
|
||||
return (
|
||||
top_cy + box_h // 2,
|
||||
coords[0][0] + box_w // 2,
|
||||
coords[2][0] - 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:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
top_obs_y, left_obs_x, right_obs_x = bot_bounds
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
|
||||
hand_real_top = player_top_y - (10 if compact else ZR_HAND_TOP_EXTEND_PX)
|
||||
felt_top = max(ty1 + (6 if compact else 14), top_obs_y + 8)
|
||||
felt_bot = min(ty2 - (4 if compact else 12), hand_real_top - 8)
|
||||
avail_h = max(160, felt_bot - felt_top)
|
||||
|
||||
side_pad = 6 if compact else 48
|
||||
felt_left = max(tx1 + side_pad, left_obs_x + (6 if compact else 16))
|
||||
felt_right = min(tx2 - side_pad, right_obs_x - (6 if compact else 16))
|
||||
avail_w = max(340, felt_right - felt_left)
|
||||
|
||||
grid_w = min(avail_w, 840)
|
||||
grid_h = min(avail_h, 286 if compact else 268)
|
||||
gx1 = (felt_left + felt_right - grid_w) // 2
|
||||
gy1 = felt_top + max(0, (avail_h - grid_h) // 2)
|
||||
gx2, gy2 = gx1 + grid_w, gy1 + grid_h
|
||||
mid_x, mid_y = (gx1 + gx2) // 2, (gy1 + gy2) // 2
|
||||
|
||||
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 + 8, mid_y, gx2 - 8, mid_y, fill=BORDER_COLOR, width=2, tags="fg")
|
||||
|
||||
quad_w = grid_w // 2
|
||||
quad_h = grid_h // 2
|
||||
hdr_h = 22 if compact else 24
|
||||
pad_qx = 8 if compact else 14
|
||||
|
||||
base_w, base_h = PLAYING_CARD_SIZE
|
||||
card_h = max(56 if compact else 62, min(94, quad_h - hdr_h - 10))
|
||||
card_w = max(39 if compact else 43, int(round(base_w * (card_h / max(1, base_h)))))
|
||||
card_sz = (card_w, card_h)
|
||||
|
||||
inner_cards_w = max(140, quad_w - 2 * pad_qx)
|
||||
step_x = min(card_w + 3, max(16 if compact else 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
|
||||
|
||||
lbl_y = qy1 + (14 if r_idx == 1 else 10)
|
||||
suit_lbl = f"{t(f'bav_suit_{suit}')} ✓" if is_done else t(f"bav_suit_{suit}")
|
||||
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 - 16)
|
||||
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(2, (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(10, card_w // 3), "bold"), fill=MUTED_FG, tags="fg",
|
||||
)
|
||||
continue
|
||||
|
||||
low_idx, high_idx = bounds
|
||||
if low_idx > 0:
|
||||
ZehnerRausArenaRenderer._draw_next_hint_slot(
|
||||
view, cards_x0 + (low_idx - 1) * step_x, row_top, card_w, card_h, BAVARIAN_RANKS[low_idx - 1]
|
||||
)
|
||||
if high_idx < 8:
|
||||
ZehnerRausArenaRenderer._draw_next_hint_slot(
|
||||
view, cards_x0 + (high_idx + 1) * step_x, row_top, card_w, card_h, BAVARIAN_RANKS[high_idx + 1]
|
||||
)
|
||||
for r_i in range(low_idx, high_idx + 1):
|
||||
ZehnerRausArenaRenderer._draw_lane_card(
|
||||
view, BavarianCard(suit, BAVARIAN_RANKS[r_i]),
|
||||
cards_x0 + r_i * step_x, 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(9, 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
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
ext = 10 if compact else ZR_HAND_TOP_EXTEND_PX
|
||||
eff_top = max(210, player_zone_top - ext)
|
||||
avail_h = max(148 if compact else 170, player_zone_bot - eff_top)
|
||||
zone_cy = (eff_top + player_zone_bot) // 2
|
||||
|
||||
base_w, base_h = PLAYING_CARD_SIZE
|
||||
target_h = max(106 if compact else 118, min(ZR_MAX_HAND_CARD_H, avail_h - 40))
|
||||
scale = target_h / max(1, base_h)
|
||||
card_w = max(72 if compact else 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(300, cw - (56 if compact else 180))
|
||||
step = min(card_w + 8, max(32 if compact else 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(12 if compact else 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 240
|
||||
|
||||
box_w = max(300, min(cw - (18 if compact else 72), max(span_w + 48, txt_w + 48)))
|
||||
box_h = min(avail_h + 6, card_h + 42)
|
||||
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 - 9) - 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 - (9 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 - 14, lbl_ph, lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN
|
||||
)
|
||||
return hit_rects
|
||||
|
|
@ -0,0 +1,293 @@
|
|||
# -*- 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.db.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.layout_mode import LayoutMode
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.inputs.goth_entry import GothEntry
|
||||
from view.widgets.shared_bases.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 (Desktop & Kompakt/Mobile)."""
|
||||
|
||||
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=200,
|
||||
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=230,
|
||||
height=36,
|
||||
)
|
||||
self._bot_entries.append(entry)
|
||||
self._bot_lvl_vars.append(l_var)
|
||||
self._bot_dds.append(dd)
|
||||
|
||||
start_btn = ImageButton(
|
||||
cv,
|
||||
t("zr_start_btn"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: ZehnerRausTableView(
|
||||
self.ctx,
|
||||
variant_key="zehner_raus_std",
|
||||
bot_configs=self._collect_and_save_bots(),
|
||||
on_back_to_menu=self.show,
|
||||
),
|
||||
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()
|
||||
|
||||
rw, rh = self.ctx.root.winfo_width(), self.ctx.root.winfo_height()
|
||||
is_mobile = LayoutMode.is_compact(rw, rh) or (w < 780)
|
||||
pad_x = LayoutMode.outer_pad_x(w, h, desktop_ratio=0.075, desktop_min=64)
|
||||
|
||||
box_w = min(940, w - 2 * pad_x)
|
||||
cx = w // 2
|
||||
x_left = cx - box_w // 2
|
||||
cur_y = 12 if is_mobile else max(22, int(h * 0.05))
|
||||
|
||||
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(GAME_TITLE_KEY),
|
||||
FONT_SIZE_TITLE_LG - (4 if is_mobile else 0),
|
||||
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() + (14 if is_mobile else 18)
|
||||
|
||||
# 1. Spielmodus & Regeln
|
||||
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 + 4, cur_y, image=s1_ph, anchor="nw", tags="fg")
|
||||
cur_y += s1_ph.height() + 6
|
||||
|
||||
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 - 48,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.extend([v_ph, d_ph])
|
||||
|
||||
r_box_h = max(74, 34 + d_ph.height() + 18)
|
||||
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")
|
||||
|
||||
cv.create_image(x_left + 24, cur_y + 22, image=v_ph, anchor="w", tags="fg")
|
||||
cv.create_image(x_left + 24, cur_y + 42, image=d_ph, anchor="nw", tags="fg")
|
||||
cur_y += r_box_h + (14 if is_mobile else 18)
|
||||
|
||||
# 2. 3 Pflicht-Mitspieler konfigurieren
|
||||
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 + 4, cur_y, image=s2_ph, anchor="nw", tags="fg")
|
||||
cur_y += s2_ph.height() + 6
|
||||
|
||||
if is_mobile:
|
||||
b_box_h = 286
|
||||
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")
|
||||
|
||||
in_w = box_w - 44
|
||||
ent_w = max(140, int(in_w * 0.44))
|
||||
dd_w = max(150, in_w - ent_w - 10)
|
||||
for idx in range(ZR_BOT_COUNT):
|
||||
ry = cur_y + 26 + idx * 72
|
||||
seat_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t("zr_seat_lbl", idx + 2),
|
||||
FONT_SIZE_SMALL_MIN + 1,
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(seat_lbl)
|
||||
cv.create_image(x_left + 22, ry, image=seat_lbl, anchor="w", tags="fg")
|
||||
|
||||
ent = self._bot_entries[idx]
|
||||
if hasattr(ent, "resize") and ent._width != ent_w:
|
||||
ent.resize(ent_w)
|
||||
cv.create_window(x_left + 22, ry + 30, window=ent, 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 + box_w - 22, ry + 30, window=dd, anchor="e", tags="fg")
|
||||
|
||||
cv.create_window(
|
||||
x_left + box_w - 24, cur_y + b_box_h - 32, window=start_btn, anchor="e", tags="fg"
|
||||
)
|
||||
cv.set_scrollable_height(cur_y + b_box_h + 20, h)
|
||||
else:
|
||||
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")
|
||||
|
||||
ent_w = 230
|
||||
dd_w = max(210, box_w - 426)
|
||||
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")
|
||||
|
||||
ent = self._bot_entries[idx]
|
||||
if hasattr(ent, "resize") and ent._width != ent_w:
|
||||
ent.resize(ent_w)
|
||||
cv.create_window(x_left + 130, ry, window=ent, 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 + 382, 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.set_scrollable_height(cur_y + b_box_h + 20, h)
|
||||
|
||||
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(460, cv.winfo_width()), max(560, cv.winfo_height()))
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
# -*- 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.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
MINI_BAV_CARD_SIZE = (40, 58)
|
||||
|
||||
|
||||
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 = 736
|
||||
dlg_h = 494 + (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 luftigen 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 = 26
|
||||
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
|
||||
cur_y += hl_ph.height() + 10
|
||||
|
||||
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 += 12
|
||||
|
||||
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 - 38
|
||||
|
||||
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 += 26
|
||||
|
||||
seats = self.data.get("seats_summary", [])
|
||||
cols = 2
|
||||
gap_x, gap_y = 14, 10
|
||||
card_w = (w - 72 - gap_x) // cols
|
||||
card_h = 128
|
||||
|
||||
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 - 1,
|
||||
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])
|
||||
|
||||
# Erst Mini-Karten in die Mitte legen, danach Name (oben) & Anzahl (unten) sauber darüber!
|
||||
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
|
||||
cards_top_y = sy - ch_m // 2 - 2
|
||||
for ci, cph in enumerate(c_photos):
|
||||
self.create_image(x0 + ci * step, cards_top_y, image=cph, anchor="nw")
|
||||
|
||||
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")
|
||||
|
||||
return cur_y + 2 * (card_h + gap_y) + 6
|
||||
|
|
@ -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.cards.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.shared_bases.casino_arena_base import CasinoArenaBase
|
||||
from view.widgets.buttons.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),
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -3,7 +3,7 @@
|
|||
import random
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
from resources.code_res.game_constants import BOT_DEITY_LEVEL, PK_STARTING_GOLD, RANKS, SUITS
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@
|
|||
# games/poker/models/poker_engine.py
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from models.card import Card
|
||||
from models.deck import Deck
|
||||
from models.cards.card import Card
|
||||
from models.cards.deck import Deck
|
||||
|
||||
|
||||
class PokerEngine:
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# games/poker/models/poker_evaluator.py
|
||||
from collections import Counter
|
||||
from itertools import combinations
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
|
||||
RANK_VAL = {
|
||||
"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/models/poker_seat.py
|
||||
from dataclasses import dataclass, field
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# games/poker/start.py
|
||||
from games.poker.views.poker_menu_view import PokerMenuView
|
||||
from games.poker.views.poker_table_view import PokerTableView
|
||||
from models.database import Database
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import CAT_LUCK, PK_MAX_BOTS
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,393 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_arena_renderer.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from models.db.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD,
|
||||
ACCENT_GOTH,
|
||||
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
|
||||
|
||||
PK_OVAL_BOARD_CARD = (78, 114)
|
||||
PK_BOT_SHOWDOWN_CARD = (42, 62)
|
||||
|
||||
SEAT_LAYOUT_BY_COUNT = {
|
||||
1: (2,),
|
||||
2: (1, 3),
|
||||
3: (1, 2, 3),
|
||||
4: (0, 1, 3, 4),
|
||||
5: (0, 1, 2, 3, 4),
|
||||
}
|
||||
|
||||
|
||||
class PokerArenaRenderer:
|
||||
"""Zeichnet die 6-Max-Tischszene für Texas Hold'em (Desktop-Oval vs. tischlose Kompakt-Ansicht)."""
|
||||
|
||||
@staticmethod
|
||||
def role_badge(eng, seat_idx: int) -> str:
|
||||
badges = []
|
||||
if seat_idx == eng.dealer_pos:
|
||||
badges.append(t("pk_role_dealer"))
|
||||
if seat_idx == eng.sb_pos:
|
||||
badges.append(t("pk_role_sb"))
|
||||
if seat_idx == eng.bb_pos:
|
||||
badges.append(t("pk_role_bb"))
|
||||
return "".join(badges)
|
||||
|
||||
@classmethod
|
||||
def draw_bots(
|
||||
cls,
|
||||
view,
|
||||
cw: int,
|
||||
ch: int,
|
||||
pad_x: int,
|
||||
pad_top: int,
|
||||
pad_bot: int,
|
||||
table_rect: tuple[int, int, int, int],
|
||||
) -> int:
|
||||
bot_seats = view.engine.seats[1:]
|
||||
if not bot_seats:
|
||||
return table_rect[1] + 12
|
||||
|
||||
if getattr(view, "is_compact_arena", False):
|
||||
return cls._draw_bots_top_grid(view, bot_seats, cw, pad_x, pad_top)
|
||||
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
is_showdown = (view.engine.street == "SHOWDOWN")
|
||||
box_h = 98 if is_showdown else 88
|
||||
base_box_w = 216 if is_showdown else 204
|
||||
|
||||
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
|
||||
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
|
||||
if bot_cy - top_cy < box_h + 16:
|
||||
mid_y = (top_cy + bot_cy) // 2
|
||||
top_cy, bot_cy = mid_y - (box_h + 16) // 2, mid_y + (box_h + 16) // 2
|
||||
|
||||
top_center_cy = max(pad_top + box_h // 2, ty1 + int(box_h * 0.42))
|
||||
top_center_bottom = ty1 + 24
|
||||
|
||||
slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4))
|
||||
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
|
||||
|
||||
for bot_i, seat in enumerate(bot_seats):
|
||||
coord_idx = slot_indices[bot_i]
|
||||
is_turn = (not is_showdown and view.engine.turn_pos == seat.seat_id)
|
||||
show_bot_cards = is_showdown and bool(seat.hole_cards) and (not seat.folded)
|
||||
|
||||
frame_style = "gold" if is_turn else "purple"
|
||||
status_border = ERROR_FG if seat.folded else (ACCENT_GOTH if seat.all_in else None)
|
||||
|
||||
base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name
|
||||
title_txt = f"{base_name}{cls.role_badge(view.engine, seat.seat_id)}"
|
||||
title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH)
|
||||
|
||||
stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet)
|
||||
st_txt = seat.status_text or "-"
|
||||
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
|
||||
|
||||
max_txt_w = 176 if show_bot_cards else 230
|
||||
title_ph = view._make_goth_photo(title_txt, name_sz, title_col, max_txt_w)
|
||||
stack_ph = view._make_goth_photo(stack_txt, sub_sz, ACCENT_GOLD, max_txt_w)
|
||||
st_ph = view._make_goth_photo(st_txt, sub_sz, st_col, max_txt_w)
|
||||
|
||||
widest_txt = max((ph.width() for ph in (title_ph, stack_ph, st_ph) if ph), default=140)
|
||||
extra_cards_w = (PK_BOT_SHOWDOWN_CARD[0] + 38) if show_bot_cards else 0
|
||||
box_w = max(base_box_w, min(296, widest_txt + extra_cards_w + 46))
|
||||
|
||||
if coord_idx == 2:
|
||||
bx, by = cw // 2, top_center_cy
|
||||
top_center_bottom = max(top_center_bottom, by + box_h // 2)
|
||||
elif coord_idx in (0, 1):
|
||||
bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
|
||||
by = bot_cy if coord_idx == 0 else top_cy
|
||||
else:
|
||||
bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
|
||||
by = top_cy if coord_idx == 3 else bot_cy
|
||||
|
||||
view._draw_framed_panel(bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border)
|
||||
cls._draw_bot_box_contents(
|
||||
view, seat, bx, by, box_w, show_bot_cards, PK_BOT_SHOWDOWN_CARD,
|
||||
title_ph, title_txt, title_col, stack_ph, stack_txt, st_ph, st_txt, st_col, name_sz, sub_sz,
|
||||
)
|
||||
|
||||
return top_center_bottom
|
||||
|
||||
@classmethod
|
||||
def _draw_bots_top_grid(cls, view, bot_seats: list, cw: int, pad_x: int, pad_top: int) -> int:
|
||||
"""Zeichnet 1..5 Poker-Bots im Kompaktmodus oben nebeneinander (max. 3 pro Reihe)."""
|
||||
is_showdown = (view.engine.street == "SHOWDOWN")
|
||||
n = len(bot_seats)
|
||||
cols = min(3, n)
|
||||
rows = (n + cols - 1) // cols
|
||||
gap_x, gap_y = 6, 6
|
||||
|
||||
avail_w = max(320, cw - 2 * pad_x)
|
||||
box_w = min(214, (avail_w - (cols - 1) * gap_x) // max(1, cols))
|
||||
box_h = 74 if rows == 2 else 82
|
||||
|
||||
mini_card = (34, 50)
|
||||
name_sz = max(12, FONT_SIZE_SMALL_MIN)
|
||||
sub_sz = max(11, FONT_SIZE_SMALL_MIN - 1)
|
||||
|
||||
bottom_edge = pad_top
|
||||
for idx, seat in enumerate(bot_seats):
|
||||
r, c = divmod(idx, cols)
|
||||
in_row = min(cols, n - r * cols)
|
||||
row_start_x = (cw - (in_row * box_w + (in_row - 1) * gap_x)) // 2 + box_w // 2
|
||||
bx = row_start_x + c * (box_w + gap_x)
|
||||
by = pad_top + r * (box_h + gap_y) + box_h // 2
|
||||
bottom_edge = max(bottom_edge, by + box_h // 2)
|
||||
|
||||
is_turn = (not is_showdown and view.engine.turn_pos == seat.seat_id)
|
||||
show_bot_cards = is_showdown and bool(seat.hole_cards) and (not seat.folded)
|
||||
status_border = ERROR_FG if seat.folded else (ACCENT_GOTH if seat.all_in else None)
|
||||
|
||||
base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name
|
||||
title_txt = f"{base_name}{cls.role_badge(view.engine, seat.seat_id)}"
|
||||
title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH)
|
||||
stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet)
|
||||
st_txt = seat.status_text or "-"
|
||||
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
|
||||
|
||||
max_tw = max(72, box_w - (68 if show_bot_cards else 18))
|
||||
title_ph = view._make_goth_photo(title_txt, name_sz, title_col, max_tw)
|
||||
stack_ph = view._make_goth_photo(stack_txt, sub_sz, ACCENT_GOLD, max_tw)
|
||||
st_ph = view._make_goth_photo(st_txt, sub_sz, st_col, max_tw)
|
||||
|
||||
view._draw_framed_panel(
|
||||
bx, by, box_w, box_h,
|
||||
frame_style="gold" if is_turn else "purple",
|
||||
status_border=status_border,
|
||||
)
|
||||
cls._draw_bot_box_contents(
|
||||
view, seat, bx, by, box_w, show_bot_cards, mini_card,
|
||||
title_ph, title_txt, title_col, stack_ph, stack_txt, st_ph, st_txt, st_col,
|
||||
name_sz, sub_sz, dy=20 if rows == 2 else 22,
|
||||
)
|
||||
|
||||
return bottom_edge
|
||||
|
||||
@staticmethod
|
||||
def _draw_bot_box_contents(
|
||||
view, seat, bx: int, by: int, box_w: int, show_cards: bool, card_sz: tuple[int, int],
|
||||
title_ph, title_txt: str, title_col: str, stack_ph, stack_txt: str,
|
||||
st_ph, st_txt: str, st_col: str, name_sz: int, sub_sz: int, dy: int = 23,
|
||||
) -> None:
|
||||
if show_cards:
|
||||
c_w, c_h = card_sz
|
||||
step_x = max(16, c_w // 2)
|
||||
fan_left, fan_top = bx - box_w // 2 + 10, by - c_h // 2
|
||||
for ci, c_obj in enumerate(seat.hole_cards[:2]):
|
||||
c_ph = view.ctx.assets.get_card_photo(c_obj.image_filename, size=card_sz)
|
||||
if c_ph is not None:
|
||||
view._photo_refs.append(c_ph)
|
||||
view.arena_canvas.create_image(fan_left + ci * step_x, fan_top, image=c_ph, anchor="nw", tags="fg")
|
||||
txt_cx = bx + (c_w + step_x) // 2 + 2
|
||||
else:
|
||||
txt_cx = bx
|
||||
view._place_goth_photo_or_fallback(txt_cx, by - dy, title_ph, title_txt, name_sz, title_col)
|
||||
view._place_goth_photo_or_fallback(txt_cx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
|
||||
view._place_goth_photo_or_fallback(txt_cx, by + dy, st_ph, st_txt, sub_sz, st_col)
|
||||
|
||||
@staticmethod
|
||||
def draw_board_and_pot(
|
||||
view, table_rect: tuple[int, int, int, int], top_obstacle_y: int, player_top_y: int
|
||||
) -> None:
|
||||
tx1, ty1, tx2, ty2 = table_rect
|
||||
t_cx = (tx1 + tx2) // 2
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
|
||||
if compact:
|
||||
felt_top = top_obstacle_y + 10
|
||||
felt_bot = player_top_y - 8
|
||||
else:
|
||||
t_h = max(260, ty2 - ty1)
|
||||
felt_top = max(ty1 + max(32, int(t_h * 0.14)), top_obstacle_y + 12)
|
||||
felt_bot = min(ty2 - max(24, int(t_h * 0.10)), player_top_y - 10)
|
||||
|
||||
avail_h = max(124 if compact else 148, felt_bot - felt_top)
|
||||
avail_w = max(320, tx2 - tx1 - 16)
|
||||
|
||||
base_cw, base_ch = PK_OVAL_BOARD_CARD
|
||||
scale_h = max(72, min(base_ch, avail_h - 48)) / max(1, base_ch)
|
||||
scale_w = (avail_w / 5.6) / max(1, base_cw)
|
||||
scale = min(1.0, scale_h, scale_w)
|
||||
card_w, card_h = max(52, int(round(base_cw * scale))), max(76, int(round(base_ch * scale)))
|
||||
card_sz = (card_w, card_h)
|
||||
|
||||
gap = max(6, int(card_w * 0.12))
|
||||
start_x = t_cx - (5 * card_w + 4 * gap) // 2
|
||||
board_cy = felt_top + card_h // 2 + max(2, (avail_h - card_h - 46) // 3)
|
||||
card_top = board_cy - card_h // 2
|
||||
|
||||
for slot_i in range(5):
|
||||
sx = start_x + slot_i * (card_w + gap)
|
||||
if slot_i < len(view.engine.board):
|
||||
photo = view.ctx.assets.get_card_photo(view.engine.board[slot_i].image_filename, size=card_sz)
|
||||
if photo:
|
||||
view._photo_refs.append(photo)
|
||||
view.arena_canvas.create_image(sx, card_top, image=photo, anchor="nw", tags="fg")
|
||||
continue
|
||||
view.arena_canvas.create_rectangle(
|
||||
sx, card_top, sx + card_w, card_top + card_h,
|
||||
fill="#161220", outline=SUBTLE_BORDER, width=1, tags="fg",
|
||||
)
|
||||
|
||||
pot_txt = t("pk_pot_banner", view.engine.total_pot).split("|")[0].strip()
|
||||
pot_cy = min(felt_bot - 18, max(board_cy + card_h // 2 + 24, (board_cy + card_h // 2 + felt_bot) // 2))
|
||||
pot_sz = max(14 if compact else 15, FONT_SIZE_BODY - (1 if compact else 0))
|
||||
pot_ph = view._make_goth_photo(pot_txt, pot_sz, FONT_COLOR_TITLE_MAIN)
|
||||
if pot_ph is not None:
|
||||
bw, bh = max(206, pot_ph.width() + 54), max(34, pot_ph.height() + 14)
|
||||
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
|
||||
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
|
||||
else:
|
||||
view._draw_framed_panel(t_cx, pot_cy, 220, 36, frame_style="gold")
|
||||
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_sz, ACCENT_GOLD)
|
||||
|
||||
@classmethod
|
||||
def draw_human_hand(cls, view, cw: int, pad_x: int, player_zone_top: int, player_zone_bot: int) -> None:
|
||||
human = view.engine.human_seat
|
||||
compact = getattr(view, "is_compact_arena", False)
|
||||
avail_h = max(136 if compact else 140, player_zone_bot - player_zone_top)
|
||||
zone_cy = (player_zone_top + player_zone_bot) // 2
|
||||
|
||||
base_w, base_h = PLAYING_CARD_SIZE
|
||||
scale = max(82, min(base_h, avail_h - 48)) / max(1, base_h)
|
||||
card_w, card_h = max(56, int(round(base_w * scale))), int(round(base_h * scale))
|
||||
card_sz = (card_w, card_h)
|
||||
|
||||
p_photos = [
|
||||
ph for card in human.hole_cards
|
||||
if (ph := view.ctx.assets.get_card_photo(card.image_filename, size=card_sz))
|
||||
]
|
||||
view._photo_refs.extend(p_photos)
|
||||
|
||||
state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "")
|
||||
role_str = cls.role_badge(view.engine, 0) or t("pk_role_player")
|
||||
lbl_txt = t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag)
|
||||
|
||||
is_my_turn = (view.engine.street != "SHOWDOWN" and view.engine.turn_pos == 0 and human.can_act)
|
||||
lbl_col = ERROR_FG if human.folded else FONT_COLOR_TITLE_MAIN
|
||||
lbl_sz = max(13 if compact else 14, FONT_SIZE_BODY - 1)
|
||||
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col, max_width=cw - 56)
|
||||
|
||||
cards_gap = 10 if compact else 12
|
||||
cards_span_w = len(p_photos) * card_w + max(0, len(p_photos) - 1) * cards_gap if p_photos else card_w * 2
|
||||
txt_w = lbl_ph.width() if lbl_ph is not None else 220
|
||||
|
||||
box_w = max(280, min(cw - 24 if compact else 540, max(cards_span_w + 76, txt_w + 56)))
|
||||
box_h = min(avail_h, card_h + 48)
|
||||
box_cx = cw // 2
|
||||
|
||||
status_bdr = ERROR_FG if human.folded else (ACCENT_GOTH if human.all_in else None)
|
||||
view._draw_framed_panel(
|
||||
box_cx, zone_cy, box_w, box_h,
|
||||
frame_style="gold" if is_my_turn else "purple", status_border=status_bdr,
|
||||
)
|
||||
|
||||
if p_photos:
|
||||
c_start_x = box_cx - cards_span_w // 2
|
||||
c_top_y = (zone_cy - 10) - card_h // 2
|
||||
for idx, ph in enumerate(p_photos):
|
||||
view.arena_canvas.create_image(
|
||||
c_start_x + idx * (card_w + cards_gap), c_top_y, image=ph, anchor="nw", tags="fg"
|
||||
)
|
||||
|
||||
view._place_goth_photo_or_fallback(box_cx, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col)
|
||||
|
||||
ref_btn = view._card_ref_btn
|
||||
if ref_btn is not None and ref_btn.winfo_exists():
|
||||
if view._result_dialog is not None or view._fx_overlay is not None or view.engine.street == "SHOWDOWN":
|
||||
ref_btn.place_forget()
|
||||
else:
|
||||
ref_bw, ref_bh = ref_btn.pixel_width, ref_btn.pixel_height
|
||||
if compact:
|
||||
ref_x = cw - pad_x - ref_bw - 4
|
||||
ref_y = max(player_zone_top - ref_bh - 4, zone_cy - box_h // 2 - ref_bh - 4)
|
||||
else:
|
||||
ref_x = box_cx + box_w // 2 + 16
|
||||
if ref_x + ref_bw > cw - pad_x - 6:
|
||||
ref_x = max(pad_x + 6, box_cx - box_w // 2 - ref_bw - 16)
|
||||
ref_y = zone_cy + box_h // 2 - ref_bh - 6
|
||||
ref_btn.place(x=ref_x, y=ref_y, width=ref_bw, height=ref_bh)
|
||||
tk.Widget.tkraise(ref_btn)
|
||||
|
||||
@staticmethod
|
||||
def collect_all_seats_reveal(eng, winner_names: list[str]) -> list[dict]:
|
||||
win_set = set(winner_names)
|
||||
entries = []
|
||||
for s in eng.seats:
|
||||
if s.hole_cards:
|
||||
cat_id, _ = PokerEvaluator.evaluate_best(s.hole_cards + eng.board)
|
||||
entries.append({
|
||||
"name": s.name,
|
||||
"cards": [[c.suit, c.rank] for c in s.hole_cards],
|
||||
"folded": s.folded,
|
||||
"cat_id": cat_id,
|
||||
"is_winner": (s.name in win_set) and (not s.folded),
|
||||
})
|
||||
return entries
|
||||
|
||||
@staticmethod
|
||||
def build_localized_popup_data(view, payload: dict) -> dict:
|
||||
hand_desc = (
|
||||
t("pk_popup_fold_win")
|
||||
if payload["by_fold"]
|
||||
else t(f"pk_hand_{payload['winning_hand_cat'] or 0}")
|
||||
)
|
||||
human_in_win = payload.get("human_in_winners", bool(payload.get("player_won")))
|
||||
if human_in_win:
|
||||
headline = (
|
||||
t("pk_popup_split_won", hand_desc)
|
||||
if payload["is_split"]
|
||||
else t("pk_popup_player_won", hand_desc)
|
||||
)
|
||||
else:
|
||||
headline = t("pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc)
|
||||
|
||||
other_gains = [t("pk_popup_bot_gain", b_n, b_g) for b_n, b_g in payload["bot_gains"] if b_g > 0]
|
||||
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
|
||||
)
|
||||
|
||||
seat_showdown = []
|
||||
for s_rev in payload.get("seats_reveal", []):
|
||||
raw_c = t(f"pk_hand_{s_rev['cat_id']}").strip()
|
||||
short_c = raw_c.split(" (")[0] if len(raw_c) > 20 else raw_c
|
||||
seat_showdown.append({
|
||||
"name": s_rev["name"],
|
||||
"cards": s_rev["cards"],
|
||||
"folded": s_rev["folded"],
|
||||
"is_winner": s_rev["is_winner"],
|
||||
"combo_text": f"{t('pk_bot_act_fold')} ({short_c})" if s_rev["folded"] else short_c,
|
||||
})
|
||||
|
||||
cur_gold = Database.get_poker_account(view.pk_account["id"])["gold"]
|
||||
return {
|
||||
"headline": headline,
|
||||
"player_won": payload["player_won"],
|
||||
"player_net": payload["player_net"],
|
||||
"other_gains": other_gains,
|
||||
"xp_gained": payload["xp_gained"],
|
||||
"new_level_title": lvl_str,
|
||||
"board_cards": payload.get("board_cards", []),
|
||||
"seat_showdown": seat_showdown,
|
||||
"can_continue": cur_gold >= view.cfg["min_entry"],
|
||||
"can_leave_menu": not view.devils_locked,
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ from resources.code_res.game_constants import (
|
|||
SUIT_SYMBOLS,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
HAND_REFERENCE_EXAMPLES = (
|
||||
(1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))),
|
||||
|
|
|
|||
|
|
@ -2,26 +2,9 @@
|
|||
# games/poker/views/poker_menu_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import tkinter as tk
|
||||
|
||||
from games.poker.views.poker_stats_view import PokerStatsView
|
||||
from games.poker.views.poker_table_view import PokerTableView
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from models.db.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
DEVILS_DEAL_GOLD_REWARD,
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
FONT_COLOR_BODY_MUTED,
|
||||
FONT_COLOR_DISABLED,
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_COLOR_STATUS_LOSS,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
GOLD_MAX_ACCOUNTS,
|
||||
PK_MAX_BOTS,
|
||||
PK_STARTING_GOLD,
|
||||
|
|
@ -29,491 +12,71 @@ from resources.code_res.game_constants import (
|
|||
XP_TO_GOLD_AMOUNT,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.bot_setup_widget import BotSetupWidget
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.goth_entry import GothEntry
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.shared_bases.luck_pouch_menu_base import LuckPouchMenuBase
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
|
||||
|
||||
class PokerMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self.bot_widget: BotSetupWidget | None = None
|
||||
self._photo_refs: list = []
|
||||
class PokerMenuView(LuckPouchMenuBase):
|
||||
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||
LAST_ACC_SETTING_PREFIX = "last_pk_account"
|
||||
STARTING_GOLD = PK_STARTING_GOLD
|
||||
MAX_BOTS = PK_MAX_BOTS
|
||||
REQUIRES_MIN_ONE_BOT = True
|
||||
DEVILS_DEFAULT_VARIANT = "poker_holdem"
|
||||
|
||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
||||
pid = self.ctx.profile["id"]
|
||||
KEY_TOPBAR = "pk_menu_topbar"
|
||||
KEY_HEADER_GOLD = "pk_header_gold"
|
||||
KEY_SEC1_TITLE = "pk_sec1_title"
|
||||
KEY_BOTS_TITLE = "pk_bots_sec_title"
|
||||
KEY_SEC3_TITLE = "pk_sec3_title"
|
||||
KEY_GOLD_DISPLAY = "pk_gold_display_lbl"
|
||||
KEY_DEFAULT_ACC_NAME = "pk_default_acc_name"
|
||||
KEY_ERR_DUPLICATE = "pk_err_duplicate_name"
|
||||
|
||||
devils_acc = Database.get_active_devils_pk_account(pid)
|
||||
if devils_acc is not None:
|
||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
||||
if saved is not None:
|
||||
PokerTableView(
|
||||
self.ctx,
|
||||
variant_key=saved["variant_key"],
|
||||
pk_account_id=devils_acc["id"],
|
||||
bot_configs=[],
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
resume_state_json=saved["state_json"],
|
||||
)
|
||||
return
|
||||
def _default_bot_configs(self) -> dict[int, tuple[str, int]]:
|
||||
return {
|
||||
0: (t("bot_default_name", 1), 1),
|
||||
1: (t("bot_default_name", 2), 2),
|
||||
}
|
||||
|
||||
self.ctx.sounds.play_menu_music()
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self._photo_refs.clear()
|
||||
pk_prog = self.ctx.refresh_game_progress()
|
||||
def _get_active_devils_account(self, pid: int):
|
||||
return Database.get_active_devils_pk_account(pid)
|
||||
|
||||
dyn_xp_cost = pk_prog["xp_exchange_cost"]
|
||||
is_divine = pk_prog["is_divine_punishment"]
|
||||
at_floor = pk_prog["at_divine_floor"]
|
||||
devils_deal_open = pk_prog["devils_deal_unlocked"]
|
||||
def _get_accounts(self, pid: int):
|
||||
return Database.get_poker_accounts(pid)
|
||||
|
||||
setting_key = f"last_pk_account_{pid}"
|
||||
accounts = Database.get_poker_accounts(pid)
|
||||
has_accounts = len(accounts) > 0
|
||||
def _get_account(self, acc_id: int):
|
||||
return Database.get_poker_account(acc_id)
|
||||
|
||||
if preselect_id is None and has_accounts:
|
||||
saved_id_str = Database.load_setting(setting_key, "")
|
||||
if saved_id_str.isdigit():
|
||||
preselect_id = int(saved_id_str)
|
||||
def _create_account(self, pid: int, name: str):
|
||||
return Database.create_poker_account(pid, name)
|
||||
|
||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
||||
acc_names = list(acc_by_name.keys())
|
||||
def _delete_account(self, acc_id: int):
|
||||
Database.delete_poker_account(acc_id)
|
||||
|
||||
active_acc = None
|
||||
if has_accounts:
|
||||
active_acc = accounts[0]
|
||||
if preselect_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == preselect_id:
|
||||
active_acc = a
|
||||
break
|
||||
Database.save_setting(setting_key, str(active_acc["id"]))
|
||||
def _exchange_xp(self, pid: int, acc_id: int):
|
||||
return Database.exchange_xp_for_pk_gold(pid, acc_id)
|
||||
|
||||
selected_name_var = tk.StringVar(
|
||||
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
|
||||
)
|
||||
state_msg = {"text": status_msg, "ok": status_is_ok}
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
return PK_VARIANTS
|
||||
|
||||
def get_current_acc() -> dict | None:
|
||||
return acc_by_name.get(selected_name_var.get())
|
||||
def _min_entry_for_variant(self, _v_key: str, cfg: dict) -> int:
|
||||
return cfg["min_entry"]
|
||||
|
||||
def open_pk_stats():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
PokerStatsView(
|
||||
self.ctx,
|
||||
on_back_to_pk_menu=lambda aid: self.show(preselect_id=aid),
|
||||
).show(selected_acc_id=cur["id"])
|
||||
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
|
||||
return t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"])
|
||||
|
||||
def refresh_on_lang_switch():
|
||||
cur = get_current_acc()
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
self.show(preselect_id=cur["id"] if cur else None)
|
||||
def _format_limit_info(self, dyn_xp_cost: int) -> str:
|
||||
classic = PK_VARIANTS["poker_holdem"]
|
||||
return t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic["sb"], classic["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
|
||||
topbar_gold_txt = (
|
||||
t("pk_header_gold", active_acc["account_name"], active_acc["gold"])
|
||||
if active_acc else ""
|
||||
)
|
||||
topbar = self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("pk_menu_topbar"),
|
||||
on_game_menu=None,
|
||||
on_stats=open_pk_stats,
|
||||
stats_enabled=has_accounts,
|
||||
extra_right_text=topbar_gold_txt,
|
||||
on_lang_refresh=refresh_on_lang_switch,
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
table_buttons: list[tuple[str, ImageButton]] = []
|
||||
|
||||
def on_account_switched(_val=None):
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
fresh = Database.get_poker_account(cur["id"])
|
||||
Database.save_setting(setting_key, str(fresh["id"]))
|
||||
topbar.extra_label.configure(text=t("pk_header_gold", fresh["account_name"], fresh["gold"]))
|
||||
for v_k, tb in table_buttons:
|
||||
tb.set_enabled(fresh["gold"] >= PK_VARIANTS[v_k]["min_entry"])
|
||||
state_msg["text"] = ""
|
||||
if cv.winfo_exists() and cv.winfo_width() >= 200:
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
|
||||
acc_dd = GothDropdown(
|
||||
cv,
|
||||
self.ctx.assets,
|
||||
values=acc_names if has_accounts else [t("bj_no_account_item")],
|
||||
textvariable=selected_name_var,
|
||||
on_change=on_account_switched,
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=215,
|
||||
height=36,
|
||||
enabled=has_accounts,
|
||||
)
|
||||
|
||||
def exchange_xp_action():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, msg = Database.exchange_xp_for_pk_gold(pid, cur["id"])
|
||||
if ok and is_divine:
|
||||
self.ctx.sounds.play("lose")
|
||||
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
|
||||
|
||||
can_afford_xp = is_divine or (pk_prog["total_points"] >= dyn_xp_cost)
|
||||
can_exchange = has_accounts and (not at_floor) and can_afford_xp
|
||||
ex_btn_txt = (
|
||||
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
exchange_btn = ImageButton(
|
||||
cv, ex_btn_txt, btn_norm, btn_purp,
|
||||
exchange_xp_action, sound_mgr=self.ctx.sounds,
|
||||
width=180, height=36, enabled=can_exchange, style="amethyst",
|
||||
)
|
||||
|
||||
def delete_selected_account():
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
Database.delete_poker_account(cur["id"])
|
||||
self.show()
|
||||
|
||||
delete_btn = ImageButton(
|
||||
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
|
||||
delete_selected_account, sound_mgr=self.ctx.sounds,
|
||||
width=136, height=32, enabled=has_accounts, style="amethyst",
|
||||
)
|
||||
|
||||
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
|
||||
next_idx = len(accounts) + 1
|
||||
new_acc_var = tk.StringVar(
|
||||
value=t("pk_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
|
||||
)
|
||||
new_entry = GothEntry(
|
||||
cv, self.ctx.assets, width=215, height=36,
|
||||
textvariable=new_acc_var, enabled=can_create_more,
|
||||
)
|
||||
|
||||
def create_new_account():
|
||||
if not can_create_more:
|
||||
return
|
||||
name = new_entry.get().strip()
|
||||
if not name:
|
||||
state_msg["text"] = t("bj_err_empty_name")
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
try:
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
created = Database.create_poker_account(pid, name)
|
||||
Database.save_setting(setting_key, str(created["id"]))
|
||||
self.show(preselect_id=created["id"])
|
||||
except (sqlite3.IntegrityError, RuntimeError) as exc:
|
||||
state_msg["text"] = t("pk_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc)
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
|
||||
if can_create_more:
|
||||
new_entry.bind_return(lambda _e: create_new_account())
|
||||
|
||||
create_btn = ImageButton(
|
||||
cv, t("bj_create_acc_btn", PK_STARTING_GOLD),
|
||||
btn_fire if not has_accounts else btn_norm,
|
||||
btn_fire if not has_accounts else btn_purp,
|
||||
create_new_account, sound_mgr=self.ctx.sounds,
|
||||
width=180, height=36, enabled=can_create_more,
|
||||
style="fire" if not has_accounts else "amethyst",
|
||||
)
|
||||
|
||||
sac_dd = None
|
||||
devil_btn = None
|
||||
min_sac_lvl = Progression.get_devils_deal_min_level()
|
||||
classic_cfg = PK_VARIANTS["poker_holdem"]
|
||||
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID) if (devils_deal_open and has_accounts) else []
|
||||
if sac_candidates:
|
||||
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
|
||||
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
|
||||
sac_dd = GothDropdown(
|
||||
cv, self.ctx.assets, values=list(sac_map.keys()),
|
||||
textvariable=sac_var, sound_mgr=self.ctx.sounds, width=250, height=34,
|
||||
)
|
||||
|
||||
def seal_devils_deal():
|
||||
cur = get_current_acc()
|
||||
victim_id = sac_map.get(sac_var.get())
|
||||
if cur is None or victim_id is None:
|
||||
return
|
||||
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
|
||||
if not active_bots:
|
||||
state_msg["text"] = t("pk_err_need_one_bot")
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
|
||||
if ok:
|
||||
self.ctx.sounds.play("end_battle")
|
||||
PokerTableView(
|
||||
self.ctx,
|
||||
variant_key="poker_holdem",
|
||||
pk_account_id=cur["id"],
|
||||
bot_configs=active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
|
||||
devil_btn = ImageButton(
|
||||
cv, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
|
||||
btn_fire, btn_fire, seal_devils_deal,
|
||||
sound_mgr=None, width=180, height=34, style="fire",
|
||||
)
|
||||
|
||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||
if not saved_bots:
|
||||
saved_bots = {
|
||||
0: (t("bot_default_name", 1), 1),
|
||||
1: (t("bot_default_name", 2), 2),
|
||||
}
|
||||
self.bot_widget = BotSetupWidget(cv, saved_bots, max_bots=PK_MAX_BOTS, enabled=has_accounts)
|
||||
|
||||
def enter_table(v_key: str):
|
||||
cur = get_current_acc()
|
||||
if not cur:
|
||||
return
|
||||
acc = Database.get_poker_account(cur["id"])
|
||||
if not acc:
|
||||
return
|
||||
Database.save_setting(setting_key, str(acc["id"]))
|
||||
active_bots, configs_to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
|
||||
|
||||
if not active_bots:
|
||||
state_msg["text"] = t("pk_err_need_one_bot")
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
|
||||
min_req = PK_VARIANTS[v_key]["min_entry"]
|
||||
cur_pk_prog = self.ctx.refresh_game_progress()
|
||||
if acc["gold"] < min_req:
|
||||
state_msg["text"] = t(
|
||||
"bj_err_not_enough_gold_entry",
|
||||
acc["account_name"], min_req, acc["gold"],
|
||||
cur_pk_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT,
|
||||
)
|
||||
state_msg["ok"] = False
|
||||
draw_layout(cv.winfo_width(), cv.winfo_height())
|
||||
return
|
||||
|
||||
PokerTableView(
|
||||
self.ctx, v_key, acc["id"], active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
|
||||
variant_items = list(PK_VARIANTS.items())
|
||||
for v_key, cfg in variant_items:
|
||||
can_play_v = bool(active_acc and active_acc["gold"] >= cfg["min_entry"])
|
||||
t_btn = ImageButton(
|
||||
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
|
||||
lambda k=v_key: enter_table(k),
|
||||
sound_mgr=self.ctx.sounds, width=168, height=38,
|
||||
enabled=can_play_v, style="fire",
|
||||
)
|
||||
table_buttons.append((v_key, t_btn))
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
compact = (h < 710)
|
||||
pad_x = max(44, int(w * 0.045))
|
||||
usable_w = min(1240, w - 2 * pad_x)
|
||||
x0 = (w - usable_w) // 2
|
||||
col_gap = 20
|
||||
col_w = (usable_w - col_gap) // 2
|
||||
left_x = x0
|
||||
right_x = x0 + col_w + col_gap
|
||||
|
||||
top_sec_y = 10 if compact else 18
|
||||
upper_h = max(296, PK_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 44)
|
||||
|
||||
s1_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("pk_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, PK_STARTING_GOLD),
|
||||
FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, max_width=col_w - 10, align="left",
|
||||
)
|
||||
s2_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("pk_bots_sec_title"), FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED,
|
||||
max_width=col_w - 10, align="left",
|
||||
)
|
||||
self._photo_refs.extend([s1_ph, s2_ph])
|
||||
cv.create_image(left_x + 8, top_sec_y + 12, image=s1_ph, anchor="w", tags="fg")
|
||||
cv.create_image(right_x + 8, top_sec_y + 12, image=s2_ph, anchor="w", tags="fg")
|
||||
|
||||
box_top = top_sec_y + 32
|
||||
box_cy = box_top + upper_h // 2
|
||||
|
||||
l_frame = self.ctx.assets.get_box_photo("box_big", (col_w, upper_h))
|
||||
r_frame = self.ctx.assets.get_box_photo("box_purple", (col_w, upper_h))
|
||||
if l_frame:
|
||||
self._photo_refs.append(l_frame)
|
||||
cv.create_image(left_x + col_w // 2, box_cy, image=l_frame, anchor="center", tags="fg")
|
||||
if r_frame:
|
||||
self._photo_refs.append(r_frame)
|
||||
cv.create_image(right_x + col_w // 2, box_cy, image=r_frame, anchor="center", tags="fg")
|
||||
|
||||
in_pad = 22
|
||||
lbl_col_w = 118
|
||||
btn_w = 180
|
||||
mid_field_w = max(140, col_w - 2 * in_pad - lbl_col_w - btn_w - 16)
|
||||
if acc_dd._width != mid_field_w:
|
||||
acc_dd._width = mid_field_w
|
||||
acc_dd.configure(width=mid_field_w)
|
||||
acc_dd._render_closed()
|
||||
|
||||
r1_y = box_top + 40
|
||||
l_act = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_active_acc_lbl"), FONT_SIZE_BODY,
|
||||
FONT_COLOR_BODY_DEFAULT if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
self._photo_refs.append(l_act)
|
||||
cv.create_image(left_x + in_pad, r1_y, image=l_act, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + in_pad + lbl_col_w, r1_y, window=acc_dd, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, r1_y, window=exchange_btn, anchor="e", tags="fg")
|
||||
|
||||
gb_y = r1_y + 54
|
||||
gb_w = col_w - 2 * in_pad
|
||||
gb_frame = self.ctx.assets.get_box_photo("box_gold_double", (gb_w, 50))
|
||||
if gb_frame:
|
||||
self._photo_refs.append(gb_frame)
|
||||
cv.create_image(left_x + col_w // 2, gb_y, image=gb_frame, anchor="center", tags="fg")
|
||||
|
||||
cur_acc_obj = get_current_acc()
|
||||
fresh_gold = Database.get_poker_account(cur_acc_obj["id"])["gold"] if cur_acc_obj else 0
|
||||
gold_str = t("pk_gold_display_lbl", fresh_gold) if cur_acc_obj else t("bj_gold_display_none")
|
||||
g_ph = self.ctx.assets.get_goth_text_photo(
|
||||
gold_str, FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_TITLE_MAIN if cur_acc_obj else FONT_COLOR_BODY_MUTED, align="left",
|
||||
)
|
||||
self._photo_refs.append(g_ph)
|
||||
cv.create_image(left_x + in_pad + 18, gb_y, image=g_ph, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad - 14, gb_y, window=delete_btn, anchor="e", tags="fg")
|
||||
|
||||
r3_y = gb_y + 54
|
||||
l_new = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_new_acc_lbl"), FONT_SIZE_BODY,
|
||||
FONT_COLOR_TITLE_MAIN if not has_accounts else (FONT_COLOR_BODY_DEFAULT if can_create_more else FONT_COLOR_DISABLED),
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(l_new)
|
||||
cv.create_image(left_x + in_pad, r3_y, image=l_new, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + in_pad + lbl_col_w, r3_y, window=new_entry, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, r3_y, window=create_btn, anchor="e", tags="fg")
|
||||
|
||||
info_y = r3_y + 42
|
||||
if devils_deal_open and has_accounts:
|
||||
warn_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
|
||||
FONT_SIZE_SMALL_MIN, FONT_COLOR_STATUS_LOSS, max_width=gb_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(warn_ph)
|
||||
cv.create_image(left_x + in_pad, info_y, image=warn_ph, anchor="nw", tags="fg")
|
||||
if sac_dd is not None and devil_btn is not None:
|
||||
dy = box_top + upper_h - 30
|
||||
cv.create_window(left_x + in_pad, dy, window=sac_dd, anchor="w", tags="fg")
|
||||
cv.create_window(left_x + col_w - in_pad, dy, window=devil_btn, anchor="e", tags="fg")
|
||||
else:
|
||||
none_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_devils_deal_none", min_sac_lvl), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||
)
|
||||
self._photo_refs.append(none_ph)
|
||||
cv.create_image(left_x + in_pad, box_top + upper_h - 28, image=none_ph, anchor="w", tags="fg")
|
||||
else:
|
||||
info_txt = (
|
||||
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine
|
||||
else t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic_cfg["sb"], classic_cfg["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
inf_ph = self.ctx.assets.get_goth_text_photo(
|
||||
info_txt, FONT_SIZE_SMALL_MIN,
|
||||
FONT_COLOR_STATUS_LOSS if is_divine else FONT_COLOR_BODY_MUTED,
|
||||
max_width=gb_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(inf_ph)
|
||||
cv.create_image(left_x + in_pad, info_y + 4, image=inf_ph, anchor="nw", tags="fg")
|
||||
|
||||
if self.bot_widget is not None:
|
||||
bw_w = col_w - 40
|
||||
bw_h = PK_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 8
|
||||
cv.create_window(
|
||||
right_x + col_w // 2, box_cy,
|
||||
window=self.bot_widget, width=bw_w, height=bw_h, anchor="center", tags="fg"
|
||||
)
|
||||
|
||||
sec3_hdr_y = box_top + upper_h + (18 if compact else 26)
|
||||
if state_msg["text"]:
|
||||
fb_ph = self.ctx.assets.get_goth_text_photo(
|
||||
state_msg["text"], FONT_SIZE_BODY,
|
||||
FONT_COLOR_STATUS_WIN if state_msg["ok"] else FONT_COLOR_STATUS_LOSS,
|
||||
max_width=usable_w // 2, align="right",
|
||||
)
|
||||
self._photo_refs.append(fb_ph)
|
||||
cv.create_image(x0 + usable_w - 6, sec3_hdr_y, image=fb_ph, anchor="e", tags="fg")
|
||||
|
||||
s3_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("pk_sec3_title"), FONT_SIZE_HEADING - 3,
|
||||
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
self._photo_refs.append(s3_ph)
|
||||
cv.create_image(left_x + 8, sec3_hdr_y, image=s3_ph, anchor="w", tags="fg")
|
||||
|
||||
var_top = sec3_hdr_y + 20
|
||||
var_h = max(118, min(148, h - var_top - 18))
|
||||
var_cy = var_top + var_h // 2
|
||||
|
||||
v_frame = self.ctx.assets.get_box_photo("box_gold_small", (col_w, var_h))
|
||||
if v_frame:
|
||||
self._photo_refs.append(v_frame)
|
||||
|
||||
for idx, (v_key, cfg) in enumerate(variant_items):
|
||||
vx = left_x if idx == 0 else right_x
|
||||
if v_frame:
|
||||
cv.create_image(vx + col_w // 2, var_cy, image=v_frame, anchor="center", tags="fg")
|
||||
|
||||
vt_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(f"variant_{v_key}"), FONT_SIZE_HEADING - 2,
|
||||
FONT_COLOR_TITLE_MAIN if has_accounts else FONT_COLOR_DISABLED, align="left",
|
||||
)
|
||||
vd_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"]),
|
||||
FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=col_w - 56, align="left",
|
||||
)
|
||||
self._photo_refs.extend([vt_ph, vd_ph])
|
||||
cv.create_image(vx + 28, var_top + 30, image=vt_ph, anchor="w", tags="fg")
|
||||
cv.create_image(vx + 28, var_top + 60, image=vd_ph, anchor="w", tags="fg")
|
||||
cv.create_window(
|
||||
vx + col_w - 28, var_top + var_h - 30,
|
||||
window=table_buttons[idx][1], 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()))
|
||||
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
|
||||
PokerTableView(
|
||||
self.ctx,
|
||||
variant_key=variant_key,
|
||||
pk_account_id=acc_id,
|
||||
bot_configs=bots,
|
||||
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
|
||||
resume_state_json=resume_json,
|
||||
)
|
||||
|
|
@ -2,241 +2,128 @@
|
|||
# games/poker/views/poker_result_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from models.card import Card
|
||||
from models.cards.card import Card
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD,
|
||||
ACCENT_GOTH,
|
||||
CELL_BG,
|
||||
ERROR_FG,
|
||||
FG_COLOR,
|
||||
MODAL_BG,
|
||||
MUTED_FG,
|
||||
SUBTLE_BORDER,
|
||||
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_SMALL_MIN,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.modal_veil import ModalVeil
|
||||
from view.widgets.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
|
||||
POPUP_HOLE_CARD_SIZE = (48, 70)
|
||||
POPUP_HOLE_CARD_SIZE = (46, 68)
|
||||
POPUP_BOARD_CARD_SIZE = (44, 64)
|
||||
|
||||
|
||||
class PokerResultDialog(tk.Frame):
|
||||
"""
|
||||
Ergebnis-Overlay für Texas Hold'em (ohne eingebettetes GIF),
|
||||
immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch.
|
||||
"""
|
||||
class PokerResultDialog(CasinoResultDialogBase):
|
||||
"""Gothic-Showdown-Overlay für Texas Hold'em auf Basis von CasinoResultDialogBase."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
assets,
|
||||
sounds,
|
||||
result_data: dict,
|
||||
on_next_round,
|
||||
on_back_to_menu,
|
||||
):
|
||||
GothDropdown.close_any_open_popup()
|
||||
top_root = parent.winfo_toplevel()
|
||||
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
|
||||
seats = result_data.get("seat_showdown", [])
|
||||
has_board = bool(result_data.get("board_cards"))
|
||||
cols = min(3, max(1, len(seats)))
|
||||
rows = (len(seats) + 2) // 3 if seats else 0
|
||||
extra_lines = len(result_data.get("other_gains", []))
|
||||
|
||||
super().__init__(
|
||||
top_root,
|
||||
bg=MODAL_BG,
|
||||
padx=26,
|
||||
pady=18,
|
||||
highlightthickness=2,
|
||||
highlightbackground=ACCENT_GOTH,
|
||||
dlg_w = max(580, min(840, cols * 252 + 64))
|
||||
dlg_h = (
|
||||
62
|
||||
+ (86 if has_board else 8)
|
||||
+ (rows * 134 + 14 if rows else 0)
|
||||
+ 92 + min(2, extra_lines) * 20
|
||||
+ (24 if result_data.get("new_level_title") else 0)
|
||||
+ 62
|
||||
)
|
||||
self.assets = assets
|
||||
self.sounds = sounds
|
||||
self.data = result_data
|
||||
self.on_next_round = on_next_round
|
||||
self.on_back_to_menu = on_back_to_menu
|
||||
self._card_photos = []
|
||||
|
||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self._build()
|
||||
self._veil = ModalVeil(top_root, assets, modal_widget=self)
|
||||
|
||||
def _build(self):
|
||||
p_won = self.data.get("player_won")
|
||||
headline_color = ACCENT_GOLD if p_won else (
|
||||
MUTED_FG if p_won is None else ERROR_FG
|
||||
)
|
||||
tk.Label(
|
||||
self,
|
||||
text=self.data["headline"],
|
||||
font=("Georgia", 16, "bold"),
|
||||
fg=headline_color,
|
||||
bg=MODAL_BG,
|
||||
wraplength=680,
|
||||
justify="center",
|
||||
).pack(pady=(2, 10))
|
||||
|
||||
reveal_box = tk.Frame(
|
||||
self,
|
||||
bg=CELL_BG,
|
||||
padx=12,
|
||||
pady=8,
|
||||
highlightthickness=1,
|
||||
highlightbackground=SUBTLE_BORDER,
|
||||
)
|
||||
reveal_box.pack(fill="x", pady=(0, 10))
|
||||
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||
|
||||
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||
board_raw = self.data.get("board_cards", [])
|
||||
if board_raw:
|
||||
b_row = tk.Frame(reveal_box, bg=CELL_BG)
|
||||
b_row.pack(pady=(0, 6))
|
||||
tk.Label(
|
||||
b_row,
|
||||
text=f"{t('pk_board_title')}:",
|
||||
font=("Georgia", 9, "bold"),
|
||||
fg=MUTED_FG,
|
||||
bg=CELL_BG,
|
||||
).pack(side="left", padx=(0, 8))
|
||||
b_box_h = 76
|
||||
b_cy = cur_y + b_box_h // 2
|
||||
b_box = self.assets.get_box_photo("box_gold_double", (w - 56, b_box_h))
|
||||
if b_box:
|
||||
self._photo_refs.append(b_box)
|
||||
self.create_image(cx, b_cy, image=b_box, anchor="center")
|
||||
|
||||
for s_suit, s_rank in board_raw:
|
||||
c_obj = Card(s_suit, s_rank)
|
||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_BOARD_CARD_SIZE)
|
||||
if ph:
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
|
||||
|
||||
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
|
||||
|
||||
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
|
||||
seats_row.pack()
|
||||
|
||||
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
|
||||
is_win = entry["is_winner"]
|
||||
folded = entry["folded"]
|
||||
|
||||
border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a")
|
||||
s_card = tk.Frame(
|
||||
seats_row,
|
||||
bg="#191521",
|
||||
padx=8,
|
||||
pady=5,
|
||||
highlightthickness=2 if is_win else 1,
|
||||
highlightbackground=border_c,
|
||||
lbl_ph = self.assets.get_goth_text_photo(
|
||||
f"{t('pk_board_title')}:", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
|
||||
self._photo_refs.append(lbl_ph)
|
||||
|
||||
name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH)
|
||||
tk.Label(
|
||||
s_card,
|
||||
text=entry["name"],
|
||||
font=("Georgia", 9, "bold"),
|
||||
fg=name_col,
|
||||
bg="#191521",
|
||||
).pack()
|
||||
|
||||
c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2)
|
||||
c_frame.pack(pady=3)
|
||||
for s_suit, s_rank in entry["cards"]:
|
||||
c_obj = Card(s_suit, s_rank)
|
||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_HOLE_CARD_SIZE)
|
||||
b_photos = []
|
||||
for s_suit, s_rank in board_raw:
|
||||
ph = self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_BOARD_CARD_SIZE)
|
||||
if ph:
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=1)
|
||||
self._photo_refs.append(ph)
|
||||
b_photos.append(ph)
|
||||
|
||||
combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR)
|
||||
tk.Label(
|
||||
s_card,
|
||||
text=entry["combo_text"],
|
||||
font=("Helvetica", 8, "bold"),
|
||||
fg=combo_col,
|
||||
bg="#191521",
|
||||
wraplength=112,
|
||||
justify="center",
|
||||
).pack()
|
||||
cw_b, ch_b = POPUP_BOARD_CARD_SIZE
|
||||
cards_w = len(b_photos) * cw_b + max(0, len(b_photos) - 1) * 6
|
||||
total_w = lbl_ph.width() + 14 + cards_w
|
||||
start_x = cx - total_w // 2
|
||||
|
||||
info_box = tk.Frame(
|
||||
self,
|
||||
bg=CELL_BG,
|
||||
padx=20,
|
||||
pady=10,
|
||||
highlightthickness=1,
|
||||
highlightbackground=SUBTLE_BORDER,
|
||||
)
|
||||
info_box.pack(fill="x", pady=(0, 12))
|
||||
self.create_image(start_x, b_cy, image=lbl_ph, anchor="w")
|
||||
cx_card = start_x + lbl_ph.width() + 14
|
||||
for bph in b_photos:
|
||||
self.create_image(cx_card, b_cy - ch_b // 2, image=bph, anchor="nw")
|
||||
cx_card += cw_b + 6
|
||||
|
||||
p_net = self.data["player_net"]
|
||||
if p_net > 0:
|
||||
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
|
||||
elif p_net < 0:
|
||||
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
|
||||
else:
|
||||
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
|
||||
cur_y += b_box_h + 8
|
||||
|
||||
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
|
||||
seats = self.data.get("seat_showdown", [])
|
||||
if not seats:
|
||||
return cur_y
|
||||
|
||||
for extra_line in self.data.get("other_gains", []):
|
||||
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
|
||||
max_cols = 3
|
||||
rows = (len(seats) + max_cols - 1) // max_cols
|
||||
seat_w = min(244, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(seats))))
|
||||
seat_h = 126 if rows > 1 else 132
|
||||
|
||||
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
|
||||
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
|
||||
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
|
||||
if win_box:
|
||||
self._photo_refs.append(win_box)
|
||||
if std_box:
|
||||
self._photo_refs.append(std_box)
|
||||
|
||||
tk.Label(
|
||||
info_box,
|
||||
text=t("bj_popup_xp_earned", self.data["xp_gained"]),
|
||||
font=("Helvetica", 11, "bold"),
|
||||
fg=ACCENT_GOTH,
|
||||
bg=CELL_BG,
|
||||
).pack(pady=1)
|
||||
for idx, entry in enumerate(seats):
|
||||
r_i, c_i = divmod(idx, max_cols)
|
||||
in_row = min(max_cols, len(seats) - r_i * max_cols)
|
||||
row_total_w = in_row * seat_w + (in_row - 1) * 10
|
||||
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
|
||||
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
|
||||
|
||||
if self.data.get("new_level_title"):
|
||||
tk.Label(
|
||||
info_box,
|
||||
text=self.data["new_level_title"],
|
||||
font=("Georgia", 11, "bold"),
|
||||
fg=ACCENT_GOLD,
|
||||
bg=CELL_BG,
|
||||
).pack(pady=(3, 0))
|
||||
is_win, folded = entry["is_winner"], entry["folded"]
|
||||
frame_ph = win_box if is_win else std_box
|
||||
if frame_ph:
|
||||
self.create_image(sx, sy, image=frame_ph, anchor="center")
|
||||
|
||||
btn_row = tk.Frame(self, bg=MODAL_BG)
|
||||
btn_row.pack(fill="x", pady=(4, 0))
|
||||
n_col = FONT_COLOR_TITLE_MAIN if is_win else (FONT_COLOR_BODY_MUTED if folded else FONT_COLOR_HEADING_SUB)
|
||||
n_ph = self.assets.get_goth_text_photo(entry["name"], FONT_SIZE_SMALL_MIN + 1, n_col, max_width=seat_w - 24)
|
||||
self._photo_refs.append(n_ph)
|
||||
self.create_image(sx, sy - seat_h // 2 + 19, image=n_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
|
||||
cw_h, ch_h = POPUP_HOLE_CARD_SIZE
|
||||
h_photos = [
|
||||
ph for s_suit, s_rank in entry["cards"]
|
||||
if (ph := self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_HOLE_CARD_SIZE))
|
||||
]
|
||||
self._photo_refs.extend(h_photos)
|
||||
if h_photos:
|
||||
span_w = len(h_photos) * cw_h + max(0, len(h_photos) - 1) * 6
|
||||
hx = sx - span_w // 2
|
||||
for hph in h_photos:
|
||||
self.create_image(hx, sy - ch_h // 2 + 1, image=hph, anchor="nw")
|
||||
hx += cw_h + 6
|
||||
|
||||
if self.data.get("can_continue", True):
|
||||
ImageButton(
|
||||
btn_row,
|
||||
t("bj_popup_next_round_btn"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
self._handle_next,
|
||||
sound_mgr=self.sounds,
|
||||
width=200,
|
||||
height=38,
|
||||
style="fire",
|
||||
).pack(side="left", padx=(0, 10))
|
||||
cb_col = FONT_COLOR_STATUS_WIN if is_win else (FONT_COLOR_STATUS_LOSS if folded else FONT_COLOR_BODY_DEFAULT)
|
||||
cb_ph = self.assets.get_goth_text_photo(entry["combo_text"], FONT_SIZE_SMALL_MIN, cb_col, max_width=seat_w - 20)
|
||||
self._photo_refs.append(cb_ph)
|
||||
self.create_image(sx, sy + seat_h // 2 - 18, image=cb_ph, anchor="center")
|
||||
|
||||
if self.data.get("can_leave_menu", True):
|
||||
ImageButton(
|
||||
btn_row,
|
||||
t("bj_popup_to_menu_btn"),
|
||||
btn_norm,
|
||||
btn_purp,
|
||||
self._handle_menu,
|
||||
sound_mgr=self.sounds,
|
||||
width=170,
|
||||
height=38,
|
||||
style="amethyst",
|
||||
).pack(side="right")
|
||||
|
||||
def close_dialog(self):
|
||||
self._veil.release()
|
||||
if self.winfo_exists():
|
||||
self.destroy()
|
||||
|
||||
def _handle_next(self):
|
||||
self.close_dialog()
|
||||
self.on_next_round()
|
||||
|
||||
def _handle_menu(self):
|
||||
self.close_dialog()
|
||||
self.on_back_to_menu()
|
||||
return cur_y + rows * (seat_h + 6) + 6
|
||||
|
|
@ -1,132 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_stats_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_SIZE_BODY,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from view.widgets.stats_board_widget import StatsBoardWidget
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
|
||||
|
||||
class PokerStatsView:
|
||||
"""Rahmenlose Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
|
||||
|
||||
def __init__(self, context, on_back_to_pk_menu):
|
||||
self.ctx = context
|
||||
self.on_back_to_pk_menu = on_back_to_pk_menu
|
||||
self._photo_refs: list = []
|
||||
|
||||
def show(self, selected_acc_id: int | None = None):
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self._photo_refs.clear()
|
||||
|
||||
pid = self.ctx.profile["id"]
|
||||
accounts = Database.get_poker_accounts(pid)
|
||||
if not accounts:
|
||||
self.on_back_to_pk_menu(None)
|
||||
return
|
||||
|
||||
active_acc = accounts[0]
|
||||
if selected_acc_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == selected_acc_id:
|
||||
active_acc = a
|
||||
break
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("pk_stats_view_topbar"),
|
||||
on_game_menu=lambda: self.on_back_to_pk_menu(active_acc["id"]),
|
||||
extra_right_text=t("pk_header_gold", active_acc["account_name"], active_acc["gold"]),
|
||||
on_lang_refresh=lambda: self.show(active_acc["id"]),
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
acc_btns: list[tuple[ImageButton, int]] = []
|
||||
for acc in accounts:
|
||||
is_sel = (acc["id"] == active_acc["id"])
|
||||
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
|
||||
b = ImageButton(
|
||||
cv,
|
||||
btn_lbl,
|
||||
btn_fire if is_sel else btn_norm,
|
||||
btn_fire if is_sel else btn_purp,
|
||||
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=180,
|
||||
height=38,
|
||||
style="fire" if is_sel else "amethyst",
|
||||
)
|
||||
acc_btns.append((b, b.pixel_width))
|
||||
|
||||
pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
|
||||
pk_filter_map = {t("pk_filter_all_tables"): None}
|
||||
for v in pk_variants:
|
||||
pk_filter_map[v["translated_name"]] = v["id"]
|
||||
|
||||
board = StatsBoardWidget(
|
||||
cv,
|
||||
title=t("bj_stats_acc_title", active_acc["account_name"]),
|
||||
filter_map=pk_filter_map,
|
||||
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid),
|
||||
)
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
pad_x = max(56, int(w * 0.065))
|
||||
content_w = min(1060, w - 2 * pad_x)
|
||||
left_edge = (w - content_w) // 2
|
||||
|
||||
sel_h = 114
|
||||
sel_top = max(24, int(h * 0.05))
|
||||
sel_cy = sel_top + sel_h // 2
|
||||
|
||||
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
|
||||
if sel_box:
|
||||
self._photo_refs.append(sel_box)
|
||||
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
|
||||
|
||||
lbl_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("bj_stats_select_acc_lbl"),
|
||||
size_px=FONT_SIZE_BODY + 2,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(lbl_ph)
|
||||
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
|
||||
|
||||
cur_bx = left_edge + 26
|
||||
for b_wgt, bw in acc_btns:
|
||||
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
|
||||
cur_bx += bw + 10
|
||||
|
||||
board_top = sel_top + sel_h + 22
|
||||
board_h = max(238, min(270, h - board_top - 32))
|
||||
cv.create_window(
|
||||
w // 2,
|
||||
board_top + board_h // 2,
|
||||
window=board,
|
||||
width=content_w,
|
||||
height=board_h,
|
||||
anchor="center",
|
||||
tags="fg",
|
||||
)
|
||||
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
|
||||
|
||||
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(600, cv.winfo_height()))
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,270 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_turn_driver.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from games.poker.views.poker_arena_renderer import PokerArenaRenderer
|
||||
from models.db.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
PK_BOT_TURN_DELAY_MS,
|
||||
PK_STREET_DELAY_MS,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
|
||||
class PokerTurnDriver:
|
||||
"""Steuert Setzrunden, Spieler-Aktionsleiste, KI-Züge und Showdown-Abrechnung beim Poker."""
|
||||
|
||||
@classmethod
|
||||
def process_current_turn(cls, view) -> None:
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
if view.engine.only_one_left():
|
||||
cls.finalize_hand(view)
|
||||
return
|
||||
if view.engine.is_betting_round_complete():
|
||||
cls.advance_street_or_showdown(view)
|
||||
return
|
||||
if (
|
||||
view.engine.turn_pos < 0
|
||||
or not view.engine.seats[view.engine.turn_pos].can_act
|
||||
):
|
||||
view.engine.advance_turn_pointer()
|
||||
if view.engine.turn_pos < 0:
|
||||
cls.advance_street_or_showdown(view)
|
||||
return
|
||||
|
||||
if view.engine.turn_pos == 0:
|
||||
view._render_table()
|
||||
cls.show_human_controls(view)
|
||||
else:
|
||||
view._set_bottom_buttons([])
|
||||
bot = view.engine.seats[view.engine.turn_pos]
|
||||
view._render_table()
|
||||
view._turn_job = view.ctx.root.after(
|
||||
PK_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_turn(view, b)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def advance_street_or_showdown(cls, view) -> None:
|
||||
view._set_bottom_buttons([])
|
||||
if view.engine.street == "RIVER":
|
||||
cls.finalize_hand(view)
|
||||
return
|
||||
view.ctx.sounds.play("click")
|
||||
new_street = view.engine.advance_to_next_street()
|
||||
view._persist_state()
|
||||
view._render_table()
|
||||
if new_street == "SHOWDOWN":
|
||||
cls.finalize_hand(view)
|
||||
elif view.engine.should_auto_runout_board():
|
||||
view._turn_job = view.ctx.root.after(
|
||||
PK_STREET_DELAY_MS, lambda: cls.advance_street_or_showdown(view)
|
||||
)
|
||||
else:
|
||||
cls.process_current_turn(view)
|
||||
|
||||
@staticmethod
|
||||
def show_human_controls(view) -> None:
|
||||
if not hasattr(view, "bottom_bar") or not view.bottom_bar.winfo_exists():
|
||||
return
|
||||
human = view.engine.human_seat
|
||||
to_call = max(0, view.engine.current_bet - human.street_bet)
|
||||
dyn_chips = view._get_current_level_chips()
|
||||
btn_norm = view.ctx.assets.raw_btn_default
|
||||
btn_purp = view.ctx.assets.raw_btn_purple
|
||||
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
primary_btns: list[ImageButton] = []
|
||||
overflow_btns: list[ImageButton] = []
|
||||
|
||||
if to_call == 0:
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("pk_btn_check"), btn_fire, btn_fire,
|
||||
lambda: view._on_human_action("CHECK", 0), sound_mgr=None,
|
||||
width=138, height=30, style="fire",
|
||||
hover_text=lambda: t("pk_tip_check"),
|
||||
)
|
||||
)
|
||||
elif human.stack > to_call:
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("pk_btn_call", to_call), btn_fire, btn_fire,
|
||||
lambda: view._on_human_action("CALL", 0),
|
||||
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
|
||||
hover_text=lambda: t("pk_tip_call"),
|
||||
)
|
||||
)
|
||||
|
||||
avail_after_call = human.stack - to_call
|
||||
min_r = view.engine.min_raise_delta
|
||||
offered = sorted(
|
||||
{max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call}
|
||||
)[:4]
|
||||
for r_delta in offered:
|
||||
primary_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, f"+{r_delta}g", btn_norm, btn_purp,
|
||||
lambda d=r_delta: view._on_human_action("RAISE", d),
|
||||
sound_mgr=view.ctx.sounds, width=74, height=30, style="amethyst",
|
||||
hover_text=lambda: t("pk_tip_raise"),
|
||||
)
|
||||
)
|
||||
|
||||
if human.stack > 0:
|
||||
allin_fire = to_call > 0 and human.stack <= to_call
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("pk_btn_allin", human.stack),
|
||||
btn_fire if allin_fire else btn_norm,
|
||||
btn_fire if allin_fire else btn_purp,
|
||||
lambda: view._on_human_action("ALLIN", 0),
|
||||
sound_mgr=view.ctx.sounds, width=132, height=30,
|
||||
style="fire" if allin_fire else "amethyst",
|
||||
hover_text=lambda: t("pk_tip_allin"),
|
||||
)
|
||||
)
|
||||
|
||||
overflow_btns.append(
|
||||
ImageButton(
|
||||
view.bottom_bar, t("pk_btn_fold"), btn_norm, btn_purp,
|
||||
lambda: view._on_human_action("FOLD", 0),
|
||||
sound_mgr=view.ctx.sounds, width=122, height=30, style="amethyst",
|
||||
hover_text=lambda: t("pk_tip_fold"),
|
||||
)
|
||||
)
|
||||
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
|
||||
|
||||
@classmethod
|
||||
def execute_bot_turn(cls, view, bot: PokerSeat) -> None:
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
active_opps = sum(
|
||||
1 for s in view.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id
|
||||
)
|
||||
act, r_delta = view.bot_ai.decide_action(
|
||||
bot=bot,
|
||||
board=view.engine.board,
|
||||
current_bet=view.engine.current_bet,
|
||||
pot=view.engine.total_pot,
|
||||
min_raise_delta=view.engine.min_raise_delta,
|
||||
chips=view._get_current_level_chips(),
|
||||
active_opponents=active_opps,
|
||||
)
|
||||
paid = view.engine.apply_action(bot.seat_id, act, r_delta)
|
||||
if act == "FOLD":
|
||||
bot.status_text = t("pk_bot_act_fold")
|
||||
elif act == "CHECK":
|
||||
bot.status_text = t("pk_bot_act_check")
|
||||
elif act == "ALLIN":
|
||||
view.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_allin", bot.total_committed)
|
||||
elif act == "RAISE":
|
||||
view.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_raise", paid)
|
||||
else:
|
||||
view.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_call", paid)
|
||||
|
||||
view.engine.advance_turn_pointer()
|
||||
view._persist_state()
|
||||
view._render_table()
|
||||
cls.process_current_turn(view)
|
||||
|
||||
@staticmethod
|
||||
def finalize_hand(view) -> None:
|
||||
ImageButton.close_active_hover_tip()
|
||||
view._close_hands_overlay()
|
||||
view._set_bottom_buttons([])
|
||||
|
||||
res = view.engine.resolve_hand()
|
||||
if res["human_payout"] > 0:
|
||||
view.pk_account = Database.update_poker_gold(
|
||||
view.pk_account["id"], res["human_payout"]
|
||||
)
|
||||
|
||||
duration = max(0.5, time.time() - view.round_start_time)
|
||||
prog_before = view.ctx.refresh_game_progress()
|
||||
opp_levels = [s.ai_level for s in view.engine.seats[1:]]
|
||||
win_cat = res["winning_hand_cat"] or 0
|
||||
|
||||
if res["human_won"] and res["human_net"] > 0:
|
||||
out_type = (
|
||||
"WIN_777" if win_cat >= 8 else ("WIN_BJ" if win_cat >= 6 else "WIN")
|
||||
)
|
||||
won_stat: bool | None = True
|
||||
elif res["human_net"] == 0 and res["human_payout"] > 0:
|
||||
out_type, won_stat = "TIE", None
|
||||
elif res["human_won"]:
|
||||
out_type, won_stat = "WIN", True
|
||||
else:
|
||||
out_type, won_stat = "LOSE", False
|
||||
|
||||
xp_gained = Progression.calculate_match_xp(
|
||||
prog_before["level"],
|
||||
opp_levels,
|
||||
out_type,
|
||||
variant_mult=view.cfg["xp_mult"],
|
||||
)
|
||||
if won_stat is None:
|
||||
Database.add_game_points(
|
||||
view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained
|
||||
)
|
||||
prog_after = view.ctx.refresh_game_progress()
|
||||
view.ctx.sounds.play("end_battle")
|
||||
leveled_to = (
|
||||
prog_after["level"]
|
||||
if prog_after["level"] > prog_before["level"]
|
||||
else None
|
||||
)
|
||||
else:
|
||||
old_lvl, new_lvl = view.ctx.record_result(
|
||||
view.variant_key,
|
||||
won=won_stat,
|
||||
duration_sec=duration,
|
||||
points_gained=xp_gained,
|
||||
pk_account_id=view.pk_account["id"],
|
||||
)
|
||||
leveled_to = new_lvl if new_lvl > old_lvl else None
|
||||
|
||||
if view.devils_locked:
|
||||
fresh_acc = Database.get_poker_account(view.pk_account["id"])
|
||||
if not (out_type == "TIE" and fresh_acc["gold"] == 10):
|
||||
Database.set_pk_devils_deal_active(view.pk_account["id"], False)
|
||||
view.devils_locked = False
|
||||
view._clear_persisted_state()
|
||||
else:
|
||||
view._clear_persisted_state()
|
||||
|
||||
payload = {
|
||||
"by_fold": res["by_fold"],
|
||||
"winner_names": res["winner_names"],
|
||||
"winning_hand_cat": res["winning_hand_cat"],
|
||||
"player_won": won_stat,
|
||||
"human_in_winners": bool(res["human_won"]),
|
||||
"is_split": res["is_split"],
|
||||
"player_net": res["human_net"],
|
||||
"bot_gains": res["bot_gains"],
|
||||
"xp_gained": xp_gained,
|
||||
"leveled_to": leveled_to,
|
||||
"board_cards": [[c.suit, c.rank] for c in view.engine.board],
|
||||
"seats_reveal": PokerArenaRenderer.collect_all_seats_reveal(
|
||||
view.engine, res["winner_names"]
|
||||
),
|
||||
}
|
||||
view._last_popup_payload = payload
|
||||
if view.devils_locked:
|
||||
view._persist_state()
|
||||
elif view._canvas_alive():
|
||||
view.topbar.set_locked_exit(False)
|
||||
|
||||
view._render_table()
|
||||
view._open_result_popup(
|
||||
PokerArenaRenderer.build_localized_popup_data(view, payload),
|
||||
play_fx=True,
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,172 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/card_animator.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
|
||||
class CardFlightAnimator:
|
||||
"""
|
||||
Schneller, nicht-blockierender Canvas-Animator für gleitende Kartenbewegungen.
|
||||
Nutzt Canvas-Tag-Verschiebung (canvas.move) ohne teures Neu-Rendern des Hintergrunds.
|
||||
"""
|
||||
|
||||
FRAME_MS = 14 # ~70 FPS Zielrate auf Tkinter
|
||||
|
||||
def __init__(self, root: tk.Misc, canvas: tk.Canvas):
|
||||
self.root = root
|
||||
self.canvas = canvas
|
||||
self._job: str | None = None
|
||||
self._flights: list[dict] = []
|
||||
self._on_done: Callable[[], None] | None = None
|
||||
self._start_ts: float = 0.0
|
||||
self._duration_sec: float = 0.12
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
return self._job is not None
|
||||
|
||||
def cancel(self):
|
||||
"""Bricht laufende Timer sofort ab (z. B. beim Schließen des Fensters)."""
|
||||
if self._job is not None:
|
||||
try:
|
||||
self.root.after_cancel(self._job)
|
||||
except Exception:
|
||||
pass
|
||||
self._job = None
|
||||
try:
|
||||
if self.canvas.winfo_exists():
|
||||
self.canvas.delete("anim_flight")
|
||||
except Exception:
|
||||
pass
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
|
||||
def flush(self):
|
||||
"""
|
||||
Beendet eine laufende Animation sofort sauber im Zielzustand,
|
||||
damit schnelle Klickfolgen des Spielers niemals ausgebremst werden.
|
||||
"""
|
||||
if not self.is_active:
|
||||
return
|
||||
cb = self._on_done
|
||||
self.cancel()
|
||||
if callable(cb):
|
||||
cb()
|
||||
|
||||
def start(
|
||||
self,
|
||||
flights: list[dict],
|
||||
draw_card_cb: Callable,
|
||||
duration_ms: int = 115,
|
||||
on_done: Callable[[], None] | None = None,
|
||||
):
|
||||
"""
|
||||
flights: Liste aus Dicts:
|
||||
{
|
||||
"card": SolitaireCard,
|
||||
"start": (x0, y0),
|
||||
"end": (x1, y1),
|
||||
"highlight": Optional[str],
|
||||
}
|
||||
"""
|
||||
self.flush()
|
||||
if not flights:
|
||||
if callable(on_done):
|
||||
on_done()
|
||||
return
|
||||
|
||||
try:
|
||||
if not self.canvas.winfo_exists():
|
||||
if callable(on_done):
|
||||
on_done()
|
||||
return
|
||||
except Exception:
|
||||
return
|
||||
|
||||
active_flights: list[dict] = []
|
||||
max_dist = 0.0
|
||||
for idx, item in enumerate(flights):
|
||||
sx, sy = item["start"]
|
||||
ex, ey = item["end"]
|
||||
dist = ((ex - sx) ** 2 + (ey - sy) ** 2) ** 0.5
|
||||
if dist > max_dist:
|
||||
max_dist = dist
|
||||
tag = f"anim_item_{idx}"
|
||||
draw_card_cb(
|
||||
item["card"],
|
||||
int(round(sx)),
|
||||
int(round(sy)),
|
||||
tags=("anim_flight", tag),
|
||||
highlight_color=item.get("highlight"),
|
||||
)
|
||||
active_flights.append({
|
||||
"tag": tag,
|
||||
"sx": float(sx),
|
||||
"sy": float(sy),
|
||||
"ex": float(ex),
|
||||
"ey": float(ey),
|
||||
"cur_x": float(sx),
|
||||
"cur_y": float(sy),
|
||||
})
|
||||
|
||||
# Bei minimaler Distanz (< 4 px) direkt fertigstellen
|
||||
if max_dist < 4.0:
|
||||
self.canvas.delete("anim_flight")
|
||||
if callable(on_done):
|
||||
on_done()
|
||||
return
|
||||
|
||||
# Kurze Wege noch knackiger, weite Wege über den ganzen Tisch minimal länger
|
||||
scaled_ms = max(65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45))))
|
||||
self._flights = active_flights
|
||||
self._on_done = on_done
|
||||
self._duration_sec = scaled_ms / 1000.0
|
||||
self._start_ts = time.perf_counter()
|
||||
self._step()
|
||||
|
||||
def _step(self):
|
||||
self._job = None
|
||||
try:
|
||||
if not self.canvas.winfo_exists():
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
return
|
||||
except Exception:
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
return
|
||||
|
||||
elapsed = time.perf_counter() - self._start_ts
|
||||
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)
|
||||
|
||||
for fl in self._flights:
|
||||
nx = fl["sx"] + (fl["ex"] - fl["sx"]) * ease
|
||||
ny = fl["sy"] + (fl["ey"] - fl["sy"]) * ease
|
||||
dx = nx - fl["cur_x"]
|
||||
dy = ny - fl["cur_y"]
|
||||
if abs(dx) >= 0.25 or abs(dy) >= 0.25:
|
||||
self.canvas.move(fl["tag"], dx, dy)
|
||||
fl["cur_x"] = nx
|
||||
fl["cur_y"] = ny
|
||||
|
||||
if t_raw >= 1.0:
|
||||
cb = self._on_done
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
try:
|
||||
self.canvas.delete("anim_flight")
|
||||
except Exception:
|
||||
pass
|
||||
if callable(cb):
|
||||
cb()
|
||||
return
|
||||
|
||||
try:
|
||||
self._job = self.root.after(self.FRAME_MS, self._step)
|
||||
except Exception:
|
||||
self._job = None
|
||||
|
|
@ -0,0 +1,352 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/cards/card_animator.py
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
import tkinter as tk
|
||||
from typing import Callable, Iterable
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
|
||||
class CardFlightAnimator:
|
||||
"""
|
||||
Zentraler, nicht-blockierender Canvas-Animator für alle Solitaire-Tische:
|
||||
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
|
||||
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):
|
||||
self.root = root
|
||||
self.canvas = canvas
|
||||
|
||||
# 1. Lineare Kartenflüge
|
||||
self._job: str | None = None
|
||||
self._flights: list[dict] = []
|
||||
self._on_done: Callable[[], None] | None = None
|
||||
self._start_ts: float = 0.0
|
||||
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
|
||||
def is_active(self) -> bool:
|
||||
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):
|
||||
"""Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab."""
|
||||
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
|
||||
|
||||
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):
|
||||
"""Beendet eine laufende Flug-Animation sofort sauber im Zielzustand."""
|
||||
if not self.is_active:
|
||||
return
|
||||
cb = self._on_done
|
||||
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):
|
||||
cb()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste)
|
||||
# ------------------------------------------------------------------
|
||||
def start(
|
||||
self,
|
||||
flights: list[dict],
|
||||
draw_card_cb: Callable,
|
||||
duration_ms: int = 115,
|
||||
on_done: Callable[[], None] | None = None,
|
||||
):
|
||||
self.flush()
|
||||
if not flights or not self._canvas_alive():
|
||||
if callable(on_done):
|
||||
on_done()
|
||||
return
|
||||
|
||||
active_flights: list[dict] = []
|
||||
max_dist = 0.0
|
||||
for idx, item in enumerate(flights):
|
||||
sx, sy = item["start"]
|
||||
ex, ey = item["end"]
|
||||
dist = ((ex - sx) ** 2 + (ey - sy) ** 2) ** 0.5
|
||||
if dist > max_dist:
|
||||
max_dist = dist
|
||||
tag = f"anim_item_{idx}"
|
||||
draw_card_cb(
|
||||
item["card"],
|
||||
int(round(sx)),
|
||||
int(round(sy)),
|
||||
tags=("anim_flight", tag),
|
||||
highlight_color=item.get("highlight"),
|
||||
)
|
||||
active_flights.append({
|
||||
"tag": tag,
|
||||
"sx": float(sx),
|
||||
"sy": float(sy),
|
||||
"ex": float(ex),
|
||||
"ey": float(ey),
|
||||
"cur_x": float(sx),
|
||||
"cur_y": float(sy),
|
||||
})
|
||||
|
||||
if max_dist < 4.0:
|
||||
self.canvas.delete("anim_flight")
|
||||
if callable(on_done):
|
||||
on_done()
|
||||
return
|
||||
|
||||
scaled_ms = max(
|
||||
65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45)))
|
||||
)
|
||||
self._flights = active_flights
|
||||
self._on_done = on_done
|
||||
self._duration_sec = scaled_ms / 1000.0
|
||||
self._start_ts = time.perf_counter()
|
||||
self._step()
|
||||
|
||||
def _step(self):
|
||||
self._job = None
|
||||
if not self._canvas_alive():
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
return
|
||||
|
||||
elapsed = time.perf_counter() - self._start_ts
|
||||
t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec)))
|
||||
ease = 1.0 - ((1.0 - t_raw) ** 3)
|
||||
|
||||
for fl in self._flights:
|
||||
nx = fl["sx"] + (fl["ex"] - fl["sx"]) * ease
|
||||
ny = fl["sy"] + (fl["ey"] - fl["sy"]) * ease
|
||||
dx = nx - fl["cur_x"]
|
||||
dy = ny - fl["cur_y"]
|
||||
if abs(dx) >= 0.25 or abs(dy) >= 0.25:
|
||||
self.canvas.move(fl["tag"], dx, dy)
|
||||
fl["cur_x"] = nx
|
||||
fl["cur_y"] = ny
|
||||
|
||||
if t_raw >= 1.0:
|
||||
cb = self._on_done
|
||||
self._flights.clear()
|
||||
self._on_done = None
|
||||
try:
|
||||
self.canvas.delete("anim_flight")
|
||||
except Exception:
|
||||
pass
|
||||
if callable(cb):
|
||||
cb()
|
||||
return
|
||||
|
||||
try:
|
||||
self._job = self.root.after(self.FRAME_MS, self._step)
|
||||
except Exception:
|
||||
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)
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/card_hover_zoom.py
|
||||
# games/solitaire/base/cards/card_hover_zoom.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
from games.solitaire.base.solitaire_card import SolitaireCard
|
||||
from games.solitaire.base.cards.solitaire_card import SolitaireCard
|
||||
from resources.code_res.game_constants import ACCENT_GOLD, BORDER_COLOR
|
||||
|
||||
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_card.py
|
||||
# games/solitaire/base/cards/solitaire_card.py
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_modal_dialog.py
|
||||
# games/solitaire/base/session/solitaire_modal_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
|
@ -13,9 +13,9 @@ from resources.code_res.game_constants import (
|
|||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
)
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.modal_veil import ModalVeil
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.overlays.modal_veil import ModalVeil
|
||||
|
||||
|
||||
class SolitaireModalDialog(tk.Canvas):
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/session/solitaire_outcome_flow.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.solitaire.base.session.solitaire_modal_dialog import SolitaireModalDialog
|
||||
from models.db.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import SOLO_FORFEIT_XP_RATIO
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.overlays.endgame_fx_overlay import EndgameFxOverlay
|
||||
|
||||
|
||||
class SolitaireOutcomeFlow:
|
||||
"""Kapselt Sieg-, Niederlage-, Aufgabe- und Deadlock-Abläufe für alle Solitaire-Tische."""
|
||||
|
||||
@staticmethod
|
||||
def _leave_to_menu(view, status_msg: str = "", ok: bool = False) -> None:
|
||||
view._close_active_modal()
|
||||
view._cleanup_timers()
|
||||
if callable(view.on_back_to_menu):
|
||||
if status_msg:
|
||||
view.on_back_to_menu(status_msg, ok)
|
||||
else:
|
||||
view.on_back_to_menu()
|
||||
|
||||
@staticmethod
|
||||
def _restart_from_modal(view) -> None:
|
||||
view._close_active_modal()
|
||||
view._start_fresh_deal()
|
||||
|
||||
@staticmethod
|
||||
def compute_forfeit_penalty(view) -> int:
|
||||
pid = view.ctx.profile["id"]
|
||||
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||
win_xp = Progression.calculate_match_xp(
|
||||
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult
|
||||
)
|
||||
return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
||||
|
||||
@classmethod
|
||||
def show_deadlock_modal(cls, view) -> None:
|
||||
if view.hover_zoom is not None:
|
||||
view.hover_zoom.cancel()
|
||||
view.engine.pause_timer()
|
||||
view._save_progress()
|
||||
penalty = cls.compute_forfeit_penalty(view)
|
||||
|
||||
def undo_step():
|
||||
view._close_active_modal()
|
||||
view._on_undo()
|
||||
|
||||
def undo_everything():
|
||||
view._close_active_modal()
|
||||
view._on_undo_all()
|
||||
|
||||
view._modal_overlay = SolitaireModalDialog(
|
||||
view.ctx,
|
||||
title_txt=t("sol_deadlock_title"),
|
||||
body_txt=t("sol_deadlock_desc", penalty),
|
||||
is_danger=True,
|
||||
buttons=[
|
||||
(t("sol_deadlock_btn_undo"), "fire", undo_step, view.engine.can_undo),
|
||||
(t("sol_deadlock_btn_undo_all"), "fire", undo_everything, view.engine.can_undo_all),
|
||||
(
|
||||
t("sol_deadlock_btn_end", penalty),
|
||||
"amethyst",
|
||||
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
|
||||
True,
|
||||
),
|
||||
],
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
||||
@classmethod
|
||||
def show_forfeit_modal(cls, view) -> None:
|
||||
if view.hover_zoom is not None:
|
||||
view.hover_zoom.cancel()
|
||||
view.engine.pause_timer()
|
||||
view._save_progress()
|
||||
penalty = cls.compute_forfeit_penalty(view)
|
||||
|
||||
view._modal_overlay = SolitaireModalDialog(
|
||||
view.ctx,
|
||||
title_txt=t("sol_forfeit_title"),
|
||||
body_txt=t("sol_forfeit_desc", penalty),
|
||||
is_danger=True,
|
||||
buttons=[
|
||||
(t("sol_btn_cancel"), "amethyst", view._close_active_modal),
|
||||
(
|
||||
t("sol_forfeit_confirm_new"),
|
||||
"fire",
|
||||
lambda: cls.execute_forfeit(view, penalty, go_menu=False),
|
||||
),
|
||||
(
|
||||
t("sol_forfeit_confirm_menu"),
|
||||
"amethyst",
|
||||
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
|
||||
),
|
||||
],
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
||||
@classmethod
|
||||
def execute_forfeit(cls, view, penalty: int, go_menu: bool) -> None:
|
||||
if view.hover_zoom is not None:
|
||||
view.hover_zoom.cancel()
|
||||
pid = view.ctx.profile["id"]
|
||||
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
||||
|
||||
view._game_concluded = True
|
||||
view.engine.pause_timer()
|
||||
dur = view.engine.get_elapsed_seconds()
|
||||
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
|
||||
Database.record_game_result(
|
||||
pid, variant_key=view.variant_key, won=False, duration_sec=dur, points_gained=0
|
||||
)
|
||||
updated = Database.adjust_game_points(
|
||||
pid, view.GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp
|
||||
)
|
||||
deducted = max(0, prog["total_points"] - updated["total_points"])
|
||||
view.topbar.update_level_xp_text()
|
||||
view.ctx.sounds.play("lose")
|
||||
|
||||
if view._modal_overlay is not None:
|
||||
try:
|
||||
view._modal_overlay.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
view._modal_overlay = None
|
||||
|
||||
view._sync_buttons()
|
||||
|
||||
def _after_lose_fx():
|
||||
view._fx_overlay = None
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
cls._show_defeat_result_modal(view, deducted, dur, prefer_menu=go_menu)
|
||||
|
||||
view._fx_overlay = EndgameFxOverlay.play(
|
||||
view.ctx.root,
|
||||
view.ctx.assets,
|
||||
outcome="lose",
|
||||
on_continue=_after_lose_fx,
|
||||
target_canvas=view.canvas,
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
||||
@classmethod
|
||||
def _show_defeat_result_modal(cls, view, deducted: int, dur: float, prefer_menu: bool) -> None:
|
||||
lines = [
|
||||
t(
|
||||
"sol_win_summary",
|
||||
view.engine.score,
|
||||
view.engine.moves,
|
||||
Database.format_seconds(dur),
|
||||
t(f"sol_diff_short_{view.difficulty}"),
|
||||
),
|
||||
t("sol_loss_xp", deducted),
|
||||
]
|
||||
|
||||
view._modal_overlay = SolitaireModalDialog(
|
||||
view.ctx,
|
||||
title_txt=t("sol_forfeit_title"),
|
||||
body_txt="\n".join(lines),
|
||||
is_danger=True,
|
||||
buttons=[
|
||||
(
|
||||
t("sol_play_again_btn"),
|
||||
"amethyst" if prefer_menu else "fire",
|
||||
lambda: cls._restart_from_modal(view),
|
||||
),
|
||||
(
|
||||
t("bj_popup_to_menu_btn"),
|
||||
"fire" if prefer_menu else "amethyst",
|
||||
lambda: cls._leave_to_menu(view, t("sol_loss_xp", deducted), False),
|
||||
),
|
||||
],
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
||||
@classmethod
|
||||
def handle_victory(cls, view) -> None:
|
||||
if view.hover_zoom is not None:
|
||||
view.hover_zoom.cancel()
|
||||
view._game_concluded = True
|
||||
view.engine.pause_timer()
|
||||
pid = view.ctx.profile["id"]
|
||||
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
|
||||
dur = view.engine.get_elapsed_seconds()
|
||||
|
||||
fast_t, mid_t = view.SPEED_THRESHOLDS_SEC
|
||||
speed_bonus = 1.25 if dur <= fast_t else (1.12 if dur <= mid_t else 1.0)
|
||||
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
|
||||
xp_earned = Progression.calculate_match_xp(
|
||||
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult * speed_bonus
|
||||
)
|
||||
|
||||
old_lvl, new_lvl = Database.record_game_result(
|
||||
pid, variant_key=view.variant_key, won=True, duration_sec=dur, points_gained=xp_earned
|
||||
)
|
||||
view.topbar.update_level_xp_text()
|
||||
view.ctx.sounds.play("win")
|
||||
view._sync_buttons()
|
||||
|
||||
def _after_win_fx():
|
||||
view._fx_overlay = None
|
||||
if not view._canvas_alive():
|
||||
return
|
||||
cls._show_victory_modal(view, xp_earned, old_lvl, new_lvl, dur)
|
||||
|
||||
view._fx_overlay = EndgameFxOverlay.play(
|
||||
view.ctx.root,
|
||||
view.ctx.assets,
|
||||
outcome="win",
|
||||
on_continue=_after_win_fx,
|
||||
target_canvas=view.canvas,
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
||||
@classmethod
|
||||
def _show_victory_modal(cls, view, xp_earned: int, old_lvl: int, new_lvl: int, dur: float) -> None:
|
||||
lines = [
|
||||
t(
|
||||
"sol_win_summary",
|
||||
view.engine.score,
|
||||
view.engine.moves,
|
||||
Database.format_seconds(dur),
|
||||
t(f"sol_diff_short_{view.difficulty}"),
|
||||
),
|
||||
t("bj_popup_xp_earned", xp_earned),
|
||||
]
|
||||
if new_lvl > old_lvl:
|
||||
lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)))
|
||||
|
||||
view._modal_overlay = SolitaireModalDialog(
|
||||
view.ctx,
|
||||
title_txt=t("sol_win_title"),
|
||||
body_txt="\n".join(lines),
|
||||
buttons=[
|
||||
(
|
||||
t("sol_play_again_btn"),
|
||||
"fire",
|
||||
lambda: cls._restart_from_modal(view),
|
||||
),
|
||||
(
|
||||
t("bj_popup_to_menu_btn"),
|
||||
"amethyst",
|
||||
lambda: cls._leave_to_menu(view),
|
||||
),
|
||||
],
|
||||
)
|
||||
view._sync_buttons()
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/session/solitaire_session_guard.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
||||
from games.solitaire.base.table.solitaire_canvas_input import SolitaireCanvasInput
|
||||
from models.db.database import Database
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
|
||||
class SolitaireSessionGuard(SolitaireCanvasInput):
|
||||
"""
|
||||
Verwaltet für alle Solitaire-Tische Fokus-Pause, 500ms-Uhr-Tick,
|
||||
Savegame-Checkpoints, Root-Keybindings, Sprachwechsel und sauberes Timer-Cleanup.
|
||||
"""
|
||||
|
||||
CHECKPOINT_TICKS: int = 30
|
||||
|
||||
def _is_ui_locked(self) -> bool:
|
||||
return (
|
||||
self.engine.won
|
||||
or self._game_concluded
|
||||
or self._auto_running
|
||||
or (self._modal_overlay is not None)
|
||||
or (self._fx_overlay is not None)
|
||||
)
|
||||
|
||||
def _canvas_alive(self) -> bool:
|
||||
if not self._alive:
|
||||
return False
|
||||
try:
|
||||
return bool(self.canvas.winfo_exists())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _can_show_hover_zoom(self) -> bool:
|
||||
return (
|
||||
self._canvas_alive()
|
||||
and not self._is_ui_locked()
|
||||
and not self._dragging
|
||||
and self._press_info is None
|
||||
and self._window_active
|
||||
and (self.animator is None or not self.animator.is_active)
|
||||
)
|
||||
|
||||
def _play_table_music(self):
|
||||
for method_name in ("play_ingame_music", "play_table_music"):
|
||||
fn = getattr(self.ctx.sounds, method_name, None)
|
||||
if callable(fn):
|
||||
fn()
|
||||
return
|
||||
|
||||
def _bind_root(self, seq: str, callback):
|
||||
if seq and seq.startswith("<") and seq.endswith(">"):
|
||||
try:
|
||||
func_id = self.ctx.root.bind(seq, callback, add="+")
|
||||
if func_id:
|
||||
self._bind_ids.append((seq, func_id))
|
||||
except tk.TclError:
|
||||
pass
|
||||
|
||||
def _on_canvas_destroy(self, event=None):
|
||||
if event is not None and event.widget is not self.canvas:
|
||||
return
|
||||
if not self._alive:
|
||||
return
|
||||
try:
|
||||
self.engine.pause_timer()
|
||||
if not self._game_concluded:
|
||||
self._save_progress()
|
||||
except Exception:
|
||||
pass
|
||||
self._cleanup_timers()
|
||||
|
||||
def _cleanup_timers(self):
|
||||
self._alive = False
|
||||
self.engine.pause_timer()
|
||||
if self._fx_overlay is not None:
|
||||
self._fx_overlay.cancel()
|
||||
self._fx_overlay = None
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
if self.animator is not None:
|
||||
self.animator.cancel()
|
||||
for job in (
|
||||
self._tick_job,
|
||||
self._focus_job,
|
||||
self._hint_job,
|
||||
self._auto_job,
|
||||
self._resize_job,
|
||||
):
|
||||
if job is not None:
|
||||
try:
|
||||
self.ctx.root.after_cancel(job)
|
||||
except Exception:
|
||||
pass
|
||||
self._tick_job = self._focus_job = self._hint_job = None
|
||||
self._auto_job = self._resize_job = None
|
||||
|
||||
for seq, func_id in self._bind_ids:
|
||||
try:
|
||||
self.ctx.root.unbind(seq, func_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._bind_ids.clear()
|
||||
|
||||
def _schedule_focus_check(self, _event=None):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
if self._focus_job is not None:
|
||||
try:
|
||||
self.ctx.root.after_cancel(self._focus_job)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._focus_job = self.ctx.root.after(60, self._check_window_focus)
|
||||
except Exception:
|
||||
self._focus_job = None
|
||||
|
||||
def _check_window_focus(self):
|
||||
self._focus_job = None
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
try:
|
||||
is_iconic = self.ctx.root.state() == "iconic"
|
||||
has_focus = self.ctx.root.focus_displayof() is not None and not is_iconic
|
||||
except Exception:
|
||||
return
|
||||
|
||||
should_run = (
|
||||
has_focus
|
||||
and (self._modal_overlay is None)
|
||||
and (self._fx_overlay is None)
|
||||
and (not self._game_concluded)
|
||||
and (not self.engine.won)
|
||||
)
|
||||
prev_paused = self.engine.is_timer_paused
|
||||
self._window_active = has_focus
|
||||
|
||||
if should_run:
|
||||
self.engine.resume_timer()
|
||||
elif not prev_paused:
|
||||
self.engine.pause_timer()
|
||||
self._save_progress()
|
||||
|
||||
if prev_paused != self.engine.is_timer_paused:
|
||||
self._update_hud_text()
|
||||
if (
|
||||
self.animator is None or not self.animator.is_active
|
||||
) and self._fx_overlay is None:
|
||||
self.redraw()
|
||||
|
||||
def _close_active_modal(self):
|
||||
if self._modal_overlay is not None:
|
||||
try:
|
||||
self._modal_overlay.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
self._modal_overlay = None
|
||||
self._check_window_focus()
|
||||
self._sync_buttons()
|
||||
|
||||
def _refresh_lang(self):
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
self.engine.pause_timer()
|
||||
self._save_progress()
|
||||
state_json = self.engine.to_json()
|
||||
self._cleanup_timers()
|
||||
type(self)(
|
||||
self.ctx,
|
||||
variant_key=self.variant_key,
|
||||
difficulty=self.difficulty,
|
||||
on_back_to_menu=self.on_back_to_menu,
|
||||
resume_state_json=state_json,
|
||||
)
|
||||
|
||||
def _save_progress(self):
|
||||
if self._game_concluded:
|
||||
return
|
||||
pid = self.ctx.profile["id"]
|
||||
if self.engine.won:
|
||||
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
|
||||
return
|
||||
Database.save_game_state(
|
||||
pid, self.GAME_FOLDER_ID, self.variant_key, self.engine.to_json()
|
||||
)
|
||||
|
||||
def _start_clock(self):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
self._check_window_focus()
|
||||
self._update_hud_text()
|
||||
|
||||
if (
|
||||
self.engine.has_timer_started
|
||||
and not self.engine.is_timer_paused
|
||||
and not self.engine.won
|
||||
and not self._game_concluded
|
||||
):
|
||||
self._checkpoint_ticks += 1
|
||||
if self._checkpoint_ticks >= self.CHECKPOINT_TICKS:
|
||||
self._checkpoint_ticks = 0
|
||||
self._save_progress()
|
||||
try:
|
||||
self._tick_job = self.ctx.root.after(500, self._start_clock)
|
||||
except Exception:
|
||||
self._tick_job = None
|
||||
|
||||
def _extra_hud_suffix(self) -> str:
|
||||
return ""
|
||||
|
||||
def _update_hud_text(self):
|
||||
if not self._alive:
|
||||
return
|
||||
try:
|
||||
elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds())
|
||||
paused_tag = (
|
||||
t("sol_hud_paused_tag")
|
||||
if (
|
||||
self.engine.is_timer_paused
|
||||
and not self.engine.won
|
||||
and not self._game_concluded
|
||||
)
|
||||
else ""
|
||||
)
|
||||
diff_label = t(f"sol_diff_short_{self.difficulty}")
|
||||
new_hud = (
|
||||
t(
|
||||
"sol_hud_stats",
|
||||
self.engine.score,
|
||||
self.engine.moves,
|
||||
elapsed_str,
|
||||
paused_tag,
|
||||
diff_label,
|
||||
)
|
||||
+ self._extra_hud_suffix()
|
||||
)
|
||||
if self.hud_var.get() != new_hud:
|
||||
self.hud_var.set(new_hud)
|
||||
except Exception:
|
||||
pass
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/session/solitaire_tap_prefs.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.db.database import Database
|
||||
|
||||
TAP_TO_MOVE_SETTING_KEY = "sol_single_tap_to_move"
|
||||
SINGLE_TAP_MAX_HOLD_SEC = 0.28
|
||||
|
||||
_single_tap_cache: bool | None = None
|
||||
|
||||
|
||||
def invalidate_tap_prefs_cache() -> None:
|
||||
"""Leert den Cache beim Wechsel auf eine andere user_data.db."""
|
||||
global _single_tap_cache
|
||||
_single_tap_cache = None
|
||||
|
||||
|
||||
def is_single_tap_to_move_enabled() -> bool:
|
||||
global _single_tap_cache
|
||||
if _single_tap_cache is None:
|
||||
try:
|
||||
raw = Database.load_setting(TAP_TO_MOVE_SETTING_KEY, "0")
|
||||
_single_tap_cache = str(raw).strip().lower() in ("1", "true", "yes", "on")
|
||||
except Exception:
|
||||
_single_tap_cache = False
|
||||
return _single_tap_cache
|
||||
|
||||
|
||||
def set_single_tap_to_move_enabled(enabled: bool, persist: bool = True) -> None:
|
||||
global _single_tap_cache
|
||||
state = bool(enabled)
|
||||
_single_tap_cache = state
|
||||
if persist:
|
||||
try:
|
||||
Database.save_setting(TAP_TO_MOVE_SETTING_KEY, "1" if state else "0")
|
||||
except Exception:
|
||||
pass
|
||||
|
|
@ -0,0 +1,476 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_menu_base.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tkinter as tk
|
||||
|
||||
from games.solitaire.base.session.solitaire_modal_dialog import SolitaireModalDialog
|
||||
from models.db.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
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_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
SOLITAIRE_DIFFICULTIES,
|
||||
SOLO_FORFEIT_XP_RATIO,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.layout_mode import LayoutMode
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.shared_bases.menu_body_canvas import MenuBodyCanvas
|
||||
|
||||
|
||||
class SolitaireMenuBase:
|
||||
"""Gemeinsame Vorauswahl-Menü-Basisklasse für alle Solitaire-Spiele (Desktop & Kompakt/Mobile)."""
|
||||
|
||||
GAME_FOLDER_ID: str = ""
|
||||
GAME_TITLE_KEY: str = ""
|
||||
TOPBAR_KEY: str = ""
|
||||
SUBTITLE_KEY: str = "sol_menu_subtitle"
|
||||
CONTROLS_HINT_KEY: str = ""
|
||||
|
||||
DIFF_SETTING_PREFIX: str = ""
|
||||
VARIANT_SETTING_PREFIX: str = ""
|
||||
DEFAULT_VARIANT_KEY: str = ""
|
||||
DEFAULT_SCORE: int = 0
|
||||
REQUIRED_BOARD_KEYS: tuple[str, ...] = ("tableau",)
|
||||
|
||||
MODE_LABEL_KEY: str = ""
|
||||
VARIANT_TOGGLES: tuple[tuple[str, str], ...] = ()
|
||||
TOGGLE_BTN_WIDTH: int = 160
|
||||
DESC_KEY_PREFIX: str = ""
|
||||
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self._modal_overlay: tk.Widget | None = None
|
||||
self._return_bind_id: str | None = None
|
||||
self._photo_refs: list = []
|
||||
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
raise NotImplementedError
|
||||
|
||||
def _launch_table_view(
|
||||
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def _clear_modal(self):
|
||||
if self._return_bind_id is not None:
|
||||
try:
|
||||
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._return_bind_id = None
|
||||
if self._modal_overlay is not None:
|
||||
try:
|
||||
self._modal_overlay.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
self._modal_overlay = None
|
||||
|
||||
def show(
|
||||
self,
|
||||
status_msg: str = "",
|
||||
status_is_ok: bool = False,
|
||||
ask_resume_popup: bool = False,
|
||||
):
|
||||
self._clear_modal()
|
||||
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.ctx.refresh_game_progress()
|
||||
|
||||
diff_setting_key = f"{self.DIFF_SETTING_PREFIX}_{pid}"
|
||||
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
||||
selected_diff = (
|
||||
int(saved_diff_str)
|
||||
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
||||
else 1
|
||||
)
|
||||
|
||||
variants_map = self._variants_dict()
|
||||
if self.VARIANT_SETTING_PREFIX and len(variants_map) > 1:
|
||||
var_setting_key = f"{self.VARIANT_SETTING_PREFIX}_{pid}"
|
||||
selected_variant = Database.load_setting(var_setting_key, self.DEFAULT_VARIANT_KEY)
|
||||
if selected_variant not in variants_map:
|
||||
selected_variant = self.DEFAULT_VARIANT_KEY
|
||||
else:
|
||||
var_setting_key = ""
|
||||
selected_variant = self.DEFAULT_VARIANT_KEY
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t(self.TOPBAR_KEY),
|
||||
stats_endpoint=self.GAME_FOLDER_ID,
|
||||
on_game_menu=None,
|
||||
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
||||
stats_enabled=True,
|
||||
extra_right_text="",
|
||||
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
saved = Database.load_game_state(pid, self.GAME_FOLDER_ID)
|
||||
saved_meta = self._parse_saved_meta(saved)
|
||||
|
||||
resume_btn = None
|
||||
if saved and saved_meta is not None:
|
||||
resume_btn = ImageButton(
|
||||
cv, t("sol_resume_btn"), btn_fire, btn_fire,
|
||||
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
||||
sound_mgr=self.ctx.sounds, width=174, height=36, style="fire",
|
||||
)
|
||||
|
||||
def switch_variant(v_key: str):
|
||||
if v_key == selected_variant or self._modal_overlay is not None:
|
||||
return
|
||||
if var_setting_key:
|
||||
Database.save_setting(var_setting_key, v_key)
|
||||
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
|
||||
|
||||
toggle_btns: list[ImageButton] = []
|
||||
for v_key, lbl_key in self.VARIANT_TOGGLES:
|
||||
is_sel = (selected_variant == v_key)
|
||||
toggle_btns.append(
|
||||
ImageButton(
|
||||
cv, t(lbl_key),
|
||||
btn_fire if is_sel else btn_norm,
|
||||
btn_fire if is_sel else btn_purp,
|
||||
lambda k=v_key: switch_variant(k),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=min(self.TOGGLE_BTN_WIDTH, 152), height=34,
|
||||
style="fire" if is_sel else "amethyst",
|
||||
)
|
||||
)
|
||||
|
||||
diff_levels = sorted(SOLITAIRE_DIFFICULTIES.keys())
|
||||
diff_labels = [t(f"sol_diff_{lvl}") for lvl in diff_levels]
|
||||
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in diff_levels}
|
||||
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
||||
|
||||
diff_dd = GothDropdown(
|
||||
cv, self.ctx.assets, values=diff_labels, textvariable=diff_var,
|
||||
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
|
||||
sound_mgr=self.ctx.sounds, width=380, height=38,
|
||||
)
|
||||
|
||||
start_btn = ImageButton(
|
||||
cv, t("sol_start_btn"), btn_fire, btn_fire,
|
||||
lambda: self._on_start_clicked(selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta),
|
||||
sound_mgr=self.ctx.sounds, width=205, height=40, style="fire",
|
||||
)
|
||||
|
||||
has_toggles = len(toggle_btns) > 0
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h)
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
rw, rh = self.ctx.root.winfo_width(), self.ctx.root.winfo_height()
|
||||
is_mobile = LayoutMode.is_compact(rw, rh) or (w < 780)
|
||||
pad_x = LayoutMode.outer_pad_x(w, h, desktop_ratio=0.075, desktop_min=64)
|
||||
|
||||
box_w = min(940, w - 2 * pad_x)
|
||||
cx = w // 2
|
||||
x_left = cx - box_w // 2
|
||||
cur_y = 14 if is_mobile else max(24, int(h * 0.055))
|
||||
|
||||
title_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(self.GAME_TITLE_KEY), FONT_SIZE_TITLE_LG - (4 if is_mobile else 0),
|
||||
FONT_COLOR_TITLE_MAIN, align="left",
|
||||
)
|
||||
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(self.SUBTITLE_KEY), 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() + 12
|
||||
|
||||
if status_msg:
|
||||
st_ph = self.ctx.assets.get_goth_text_photo(
|
||||
status_msg, FONT_SIZE_BODY,
|
||||
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
|
||||
max_width=box_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(st_ph)
|
||||
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
|
||||
cur_y += st_ph.height() + 10
|
||||
|
||||
if saved and saved_meta is not None and resume_btn is not None:
|
||||
res_h = 98 if is_mobile else 84
|
||||
res_cy = cur_y + res_h // 2
|
||||
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
|
||||
if r_box:
|
||||
self._photo_refs.append(r_box)
|
||||
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
|
||||
|
||||
rt_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
ri_ph = self.ctx.assets.get_goth_text_photo(
|
||||
self._format_resume_info(saved, saved_meta),
|
||||
FONT_SIZE_SMALL_MIN if is_mobile else FONT_SIZE_BODY,
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
max_width=max(160, box_w - resume_btn.pixel_width - 58), align="left",
|
||||
)
|
||||
self._photo_refs.extend([rt_ph, ri_ph])
|
||||
cv.create_image(x_left + 22, res_cy - 18, image=rt_ph, anchor="w", tags="fg")
|
||||
cv.create_image(x_left + 22, res_cy + 16, image=ri_ph, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 20, res_cy, window=resume_btn, anchor="e", tags="fg")
|
||||
cur_y += res_h + 16
|
||||
|
||||
sec_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB,
|
||||
max_width=box_w, align="left",
|
||||
)
|
||||
self._photo_refs.append(sec_ph)
|
||||
cv.create_image(x_left + 4, cur_y, image=sec_ph, anchor="nw", tags="fg")
|
||||
cur_y += sec_ph.height() + 8
|
||||
|
||||
dsc_txt = t(f"{self.DESC_KEY_PREFIX}{selected_variant}")
|
||||
if is_mobile:
|
||||
# Kompakte gestapelte Innenanordnung ohne Überhang rechts
|
||||
setup_h = 278 if has_toggles else 248
|
||||
setup_cy = cur_y + setup_h // 2
|
||||
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
|
||||
if s_box:
|
||||
self._photo_refs.append(s_box)
|
||||
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
|
||||
|
||||
in_x = x_left + 24
|
||||
in_w = box_w - 48
|
||||
iy = cur_y + 24
|
||||
m_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t(self.MODE_LABEL_KEY), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(m_lbl)
|
||||
cv.create_image(in_x, iy, image=m_lbl, anchor="w", tags="fg")
|
||||
|
||||
if has_toggles:
|
||||
iy += 32
|
||||
bx_cur = in_x
|
||||
for tb in toggle_btns:
|
||||
cv.create_window(bx_cur, iy, window=tb, anchor="w", tags="fg")
|
||||
bx_cur += tb.pixel_width + 8
|
||||
iy += 28
|
||||
else:
|
||||
m_val = self.ctx.assets.get_goth_text_photo(
|
||||
t(f"variant_{selected_variant}"), FONT_SIZE_BODY + 1, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
self._photo_refs.append(m_val)
|
||||
cv.create_image(in_x + m_lbl.width() + 14, iy, image=m_val, anchor="w", tags="fg")
|
||||
iy += 24
|
||||
|
||||
dsc_ph = self.ctx.assets.get_goth_text_photo(
|
||||
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=in_w, align="left"
|
||||
)
|
||||
self._photo_refs.append(dsc_ph)
|
||||
cv.create_image(in_x, iy, image=dsc_ph, anchor="nw", tags="fg")
|
||||
iy += dsc_ph.height() + 16
|
||||
|
||||
d_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_diff_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(d_lbl)
|
||||
cv.create_image(in_x, iy, image=d_lbl, anchor="w", tags="fg")
|
||||
iy += 28
|
||||
|
||||
if diff_dd._width != in_w:
|
||||
diff_dd._width = in_w
|
||||
diff_dd.configure(width=in_w)
|
||||
diff_dd._render_closed()
|
||||
cv.create_window(in_x, iy, window=diff_dd, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 24, cur_y + setup_h - 34, window=start_btn, anchor="e", tags="fg")
|
||||
else:
|
||||
setup_h = 238 if has_toggles else 208
|
||||
setup_cy = cur_y + setup_h // 2
|
||||
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
|
||||
if s_box:
|
||||
self._photo_refs.append(s_box)
|
||||
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
|
||||
|
||||
lbl_col, val_col = x_left + 32, x_left + 220
|
||||
r1_y = cur_y + 44
|
||||
m_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t(self.MODE_LABEL_KEY), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||
)
|
||||
self._photo_refs.append(m_lbl)
|
||||
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
|
||||
|
||||
if has_toggles:
|
||||
bx_cur = val_col
|
||||
for tb in toggle_btns:
|
||||
cv.create_window(bx_cur, r1_y, window=tb, anchor="w", tags="fg")
|
||||
bx_cur += tb.pixel_width + 10
|
||||
dsc_ph = self.ctx.assets.get_goth_text_photo(
|
||||
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w - 260, align="left"
|
||||
)
|
||||
self._photo_refs.append(dsc_ph)
|
||||
cv.create_image(val_col, r1_y + 34, image=dsc_ph, anchor="w", tags="fg")
|
||||
r2_y = cur_y + 128
|
||||
else:
|
||||
m_val = self.ctx.assets.get_goth_text_photo(
|
||||
t(f"variant_{selected_variant}"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
dsc_ph = self.ctx.assets.get_goth_text_photo(
|
||||
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
|
||||
max_width=max(180, box_w - 275 - m_val.width()), align="left",
|
||||
)
|
||||
self._photo_refs.extend([m_val, dsc_ph])
|
||||
cv.create_image(val_col, r1_y, image=m_val, anchor="w", tags="fg")
|
||||
cv.create_image(val_col + m_val.width() + 18, r1_y, image=dsc_ph, anchor="w", tags="fg")
|
||||
r2_y = cur_y + 104
|
||||
|
||||
d_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||
)
|
||||
self._photo_refs.append(d_lbl)
|
||||
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
|
||||
|
||||
dd_w = max(240, box_w - 260)
|
||||
if diff_dd._width != dd_w:
|
||||
diff_dd._width = dd_w
|
||||
diff_dd.configure(width=dd_w)
|
||||
diff_dd._render_closed()
|
||||
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
|
||||
|
||||
hint_y = cur_y + setup_h + 12
|
||||
hint_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(self.CONTROLS_HINT_KEY), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
|
||||
)
|
||||
self._photo_refs.append(hint_ph)
|
||||
cv.create_image(x_left + 4, hint_y, image=hint_ph, anchor="nw", tags="fg")
|
||||
cv.set_scrollable_height(hint_y + hint_ph.height() + 20, h)
|
||||
|
||||
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(460, cv.winfo_width()), max(560, cv.winfo_height()))
|
||||
|
||||
if ask_resume_popup and saved and saved_meta is not None:
|
||||
self._show_resume_prompt_modal(saved, saved_meta)
|
||||
|
||||
def _parse_saved_meta(self, saved: dict | None) -> dict | None:
|
||||
if not saved:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(saved["state_json"])
|
||||
if data.get("won"):
|
||||
return None
|
||||
board = data.get("board", {})
|
||||
if not board or any(req_k not in board for req_k in self.REQUIRED_BOARD_KEYS):
|
||||
return None
|
||||
return {
|
||||
"moves": max(0, int(data.get("moves", 0))),
|
||||
"score": int(data.get("score", self.DEFAULT_SCORE)),
|
||||
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
||||
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _format_resume_info(saved: dict, saved_meta: dict) -> str:
|
||||
return t(
|
||||
"sol_resume_info",
|
||||
t(f"variant_{saved['variant_key']}"),
|
||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
||||
saved_meta["moves"],
|
||||
saved_meta["score"],
|
||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
||||
)
|
||||
|
||||
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
||||
self._clear_modal()
|
||||
|
||||
def resume_now(_event=None):
|
||||
self._clear_modal()
|
||||
self._resume_saved(saved, saved_meta["difficulty"])
|
||||
|
||||
try:
|
||||
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
||||
except tk.TclError:
|
||||
self._return_bind_id = None
|
||||
|
||||
self._modal_overlay = SolitaireModalDialog(
|
||||
self.ctx,
|
||||
title_txt=t("sol_resume_box_title"),
|
||||
body_txt=self._format_resume_info(saved, saved_meta),
|
||||
buttons=[
|
||||
(t("sol_resume_btn"), "fire", resume_now),
|
||||
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||
],
|
||||
)
|
||||
|
||||
def _resume_saved(self, saved: dict, difficulty: int):
|
||||
self._clear_modal()
|
||||
self._launch_table_view(saved["variant_key"], difficulty, resume_state_json=saved["state_json"])
|
||||
|
||||
def _on_start_clicked(
|
||||
self, variant_key: str, difficulty: int, saved: dict | None, saved_meta: dict | None
|
||||
):
|
||||
if self._modal_overlay is not None:
|
||||
return
|
||||
if saved and saved_meta and saved_meta["moves"] > 0:
|
||||
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
||||
return
|
||||
self._launch_fresh_game(variant_key, difficulty)
|
||||
|
||||
def _show_overwrite_confirm_modal(
|
||||
self, new_variant_key: str, new_difficulty: int, saved: dict, saved_meta: dict
|
||||
):
|
||||
pid = self.ctx.profile["id"]
|
||||
old_v, old_diff = saved["variant_key"], saved_meta["difficulty"]
|
||||
prog = Database.get_game_progress(pid, self.GAME_FOLDER_ID)
|
||||
variants_map = self._variants_dict()
|
||||
v_mult = variants_map.get(old_v, {"xp_mult": 1.0})["xp_mult"]
|
||||
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
||||
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
||||
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
||||
|
||||
def forfeit_and_start():
|
||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
||||
Database.record_game_result(
|
||||
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
|
||||
)
|
||||
Database.adjust_game_points(pid, self.GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
||||
self.ctx.refresh_game_progress()
|
||||
self._clear_modal()
|
||||
self._launch_fresh_game(new_variant_key, new_difficulty)
|
||||
|
||||
self._modal_overlay = SolitaireModalDialog(
|
||||
self.ctx,
|
||||
title_txt=t("sol_forfeit_title"),
|
||||
body_txt=t("sol_forfeit_desc", penalty),
|
||||
is_danger=True,
|
||||
buttons=[
|
||||
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
|
||||
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
|
||||
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||
],
|
||||
)
|
||||
|
||||
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
||||
pid = self.ctx.profile["id"]
|
||||
Database.save_setting(f"{self.DIFF_SETTING_PREFIX}_{pid}", str(difficulty))
|
||||
if self.VARIANT_SETTING_PREFIX:
|
||||
Database.save_setting(f"{self.VARIANT_SETTING_PREFIX}_{pid}", variant_key)
|
||||
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
|
||||
self._launch_table_view(variant_key, difficulty, resume_state_json=None)
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_stats_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from models.database import Database
|
||||
from resources.code_res.game_constants import (
|
||||
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_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
STAT_FIELD_KEYS,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
|
||||
"klondike_1": "kl_draw_toggle_1",
|
||||
"klondike_3": "kl_draw_toggle_3",
|
||||
"spider_1suit": "sp_suit_toggle_1",
|
||||
"spider_2suit": "sp_suit_toggle_2",
|
||||
"spider_4suit": "sp_suit_toggle_4",
|
||||
}
|
||||
|
||||
|
||||
class SolitaireStatsView:
|
||||
"""Rahmenlose Solitaire-Statistik-Ansicht mit direktem Varianten-Umschalter."""
|
||||
|
||||
def __init__(self, context, game_folder: str, game_title_key: str, on_back):
|
||||
self.ctx = context
|
||||
self.game_folder = game_folder
|
||||
self.game_title_key = game_title_key
|
||||
self.on_back = on_back
|
||||
self._active_variant_id: int | None = None
|
||||
self._photo_refs: list = []
|
||||
|
||||
def show(self, preselect_variant_id: int | None = None):
|
||||
pid = self.ctx.profile["id"]
|
||||
self._active_variant_id = preselect_variant_id
|
||||
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self._photo_refs.clear()
|
||||
|
||||
prog = Database.get_game_progress(pid, self.game_folder)
|
||||
game_name = t(self.game_title_key)
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("stats_view_topbar", game_name),
|
||||
on_game_menu=self.on_back,
|
||||
on_stats=None,
|
||||
stats_enabled=False,
|
||||
on_lang_refresh=lambda: self.show(preselect_variant_id=self._active_variant_id),
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
variants = Database.get_variants_for_filter(self.game_folder)
|
||||
tab_btns: list[tuple[ImageButton, int]] = []
|
||||
if len(variants) > 1:
|
||||
tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
|
||||
for v in variants:
|
||||
v_key = v["variant_key"]
|
||||
short_lbl = (
|
||||
t(SHORT_VARIANT_TAB_KEYS[v_key])
|
||||
if v_key in SHORT_VARIANT_TAB_KEYS
|
||||
else v["translated_name"]
|
||||
)
|
||||
tabs.append((v["id"], short_lbl))
|
||||
|
||||
for vid, tab_text in tabs:
|
||||
is_sel = (self._active_variant_id == vid)
|
||||
bw = 118 if vid is None else 156
|
||||
b = ImageButton(
|
||||
cv,
|
||||
tab_text,
|
||||
btn_fire if is_sel else btn_norm,
|
||||
btn_fire if is_sel else btn_purp,
|
||||
lambda target_vid=vid: self._switch_tab(target_vid),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=bw,
|
||||
height=36,
|
||||
style="fire" if is_sel else "amethyst",
|
||||
)
|
||||
tab_btns.append((b, bw))
|
||||
|
||||
active_title = t("stats_all_variants_of_game", game_name)
|
||||
for v in variants:
|
||||
if v["id"] == self._active_variant_id:
|
||||
active_title = v["translated_name"]
|
||||
break
|
||||
|
||||
stats = Database.get_stats_overview(
|
||||
pid,
|
||||
variant_id=self._active_variant_id,
|
||||
folder_path=self.game_folder if self._active_variant_id is None else None,
|
||||
)
|
||||
|
||||
def draw_layout(w: int, h: int):
|
||||
cv.sync_bg(w, h) # type: ignore[attr-defined]
|
||||
cv.delete("fg")
|
||||
self._photo_refs.clear()
|
||||
|
||||
pad_x = max(56, int(w * 0.065))
|
||||
content_w = min(1020, w - 2 * pad_x)
|
||||
left_x = (w - content_w) // 2
|
||||
|
||||
# 1. Obere Rang- & Umschalter-Box in box_gold_double
|
||||
hdr_h = 74
|
||||
hdr_top = max(24, int(h * 0.05))
|
||||
hdr_cy = hdr_top + hdr_h // 2
|
||||
|
||||
hdr_box = self.ctx.assets.get_box_photo("box_gold_double", (content_w, hdr_h))
|
||||
if hdr_box:
|
||||
self._photo_refs.append(hdr_box)
|
||||
cv.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg")
|
||||
|
||||
tabs_total_w = sum(bw + 8 for _, bw in tab_btns)
|
||||
rank_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(
|
||||
"stats_game_rank_info",
|
||||
game_name,
|
||||
prog["title"],
|
||||
prog["level"],
|
||||
prog["current_xp"],
|
||||
prog["needed_xp"],
|
||||
),
|
||||
size_px=FONT_SIZE_BODY + 1,
|
||||
color=FONT_COLOR_TITLE_MAIN,
|
||||
max_width=max(200, content_w - tabs_total_w - 64),
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(rank_ph)
|
||||
cv.create_image(left_x + 26, hdr_cy, image=rank_ph, anchor="w", tags="fg")
|
||||
|
||||
rx = left_x + content_w - 24
|
||||
for b_wgt, bw in reversed(tab_btns):
|
||||
cv.create_window(rx, hdr_cy, window=b_wgt, anchor="e", tags="fg")
|
||||
rx -= (bw + 8)
|
||||
|
||||
# 2. Haupttafel in box_big mit 2x4 box_purple Zellen
|
||||
board_top = hdr_top + hdr_h + 18
|
||||
board_h = max(260, min(330, h - board_top - 32))
|
||||
board_cy = board_top + board_h // 2
|
||||
|
||||
outer_box = self.ctx.assets.get_box_photo("box_big", (content_w, board_h))
|
||||
if outer_box:
|
||||
self._photo_refs.append(outer_box)
|
||||
cv.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg")
|
||||
|
||||
sub_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("stats_game_board_title", active_title),
|
||||
size_px=FONT_SIZE_HEADING - 2,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(sub_ph)
|
||||
cv.create_image(left_x + 28, board_top + 34, image=sub_ph, anchor="w", tags="fg")
|
||||
|
||||
grid_top = board_top + 66
|
||||
grid_h = board_h - 88
|
||||
cols, rows = 4, 2
|
||||
gap_x, gap_y = 14, 12
|
||||
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
|
||||
cell_h = (grid_h - (rows - 1) * gap_y) // rows
|
||||
|
||||
cell_frame = self.ctx.assets.get_box_photo("box_purple", (cell_w, cell_h))
|
||||
if cell_frame:
|
||||
self._photo_refs.append(cell_frame)
|
||||
|
||||
for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS):
|
||||
r, c = divmod(idx, cols)
|
||||
cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2
|
||||
cy = grid_top + r * (cell_h + gap_y) + cell_h // 2
|
||||
|
||||
if cell_frame:
|
||||
cv.create_image(cx, cy, image=cell_frame, anchor="center", tags="fg")
|
||||
|
||||
lbl_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(label_i18n_key), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
|
||||
max_width=cell_w - 24, align="center",
|
||||
)
|
||||
if field_key == "won":
|
||||
v_col = FONT_COLOR_STATUS_WIN
|
||||
elif field_key == "lost":
|
||||
v_col = FONT_COLOR_STATUS_LOSS
|
||||
elif "streak" in field_key or field_key == "win_pct":
|
||||
v_col = FONT_COLOR_HEADING_SUB
|
||||
else:
|
||||
v_col = FONT_COLOR_BODY_DEFAULT
|
||||
|
||||
val_ph = self.ctx.assets.get_goth_text_photo(
|
||||
str(stats.get(field_key, "--")), FONT_SIZE_HEADING - 2, v_col,
|
||||
max_width=cell_w - 24, align="center",
|
||||
)
|
||||
self._photo_refs.extend([lbl_ph, val_ph])
|
||||
cv.create_image(cx, cy - cell_h // 4 + 2, image=lbl_ph, anchor="center", tags="fg")
|
||||
cv.create_image(cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", 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(600, cv.winfo_height()))
|
||||
|
||||
def _switch_tab(self, variant_id: int | None):
|
||||
if variant_id == self._active_variant_id:
|
||||
return
|
||||
self.show(preselect_variant_id=variant_id)
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_tap_prefs.py
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
|
||||
from models.database import Database
|
||||
|
||||
TAP_TO_MOVE_SETTING_KEY = "sol_single_tap_to_move"
|
||||
SINGLE_TAP_MAX_HOLD_SEC = 0.28
|
||||
|
||||
_single_tap_cache: bool | None = None
|
||||
|
||||
|
||||
def _get_user_db_path() -> str:
|
||||
for attr in ("USER_DB_PATH", "DB_PATH", "_user_db_path", "db_path"):
|
||||
val = getattr(Database, attr, None)
|
||||
if isinstance(val, str) and val.strip():
|
||||
return val
|
||||
return "user_data.db"
|
||||
|
||||
|
||||
def _load_persisted_flag(default: bool = False) -> bool:
|
||||
try:
|
||||
with sqlite3.connect(_get_user_db_path()) as conn:
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS app_settings ("
|
||||
"key TEXT PRIMARY KEY, "
|
||||
"val TEXT NOT NULL"
|
||||
")"
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT val FROM app_settings WHERE key = ?",
|
||||
(TAP_TO_MOVE_SETTING_KEY,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
return str(row[0]).strip().lower() in ("1", "true", "yes", "on")
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
|
||||
def _save_persisted_flag(enabled: bool) -> None:
|
||||
try:
|
||||
with sqlite3.connect(_get_user_db_path()) as conn:
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS app_settings ("
|
||||
"key TEXT PRIMARY KEY, "
|
||||
"val TEXT NOT NULL"
|
||||
")"
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO app_settings (key, val) VALUES (?, ?)",
|
||||
(TAP_TO_MOVE_SETTING_KEY, "1" if enabled else "0"),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def is_single_tap_to_move_enabled() -> bool:
|
||||
"""Gibt zurück, ob 'Einfacher Klick zum Schieben' aktiv ist (mit In-Memory-Cache)."""
|
||||
global _single_tap_cache
|
||||
if _single_tap_cache is None:
|
||||
_single_tap_cache = _load_persisted_flag(default=False)
|
||||
return _single_tap_cache
|
||||
|
||||
|
||||
def set_single_tap_to_move_enabled(enabled: bool, persist: bool = True) -> None:
|
||||
"""Aktiviert/deaktiviert 'Einfacher Klick zum Schieben' und speichert es optional in user_data.db."""
|
||||
global _single_tap_cache
|
||||
state = bool(enabled)
|
||||
_single_tap_cache = state
|
||||
if persist:
|
||||
_save_persisted_flag(state)
|
||||
|
|
@ -2,110 +2,92 @@
|
|||
# games/solitaire/base/solitaire_theme.py
|
||||
from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
import warnings
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageTk
|
||||
|
||||
from view.layout_mode import LayoutMode
|
||||
|
||||
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
|
||||
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
|
||||
|
||||
|
||||
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
|
||||
def _pick_largest_rgba_frame(candidates, loader_fn) -> Image.Image | None:
|
||||
best_img: Image.Image | None = None
|
||||
best_area = -1
|
||||
for item in candidates:
|
||||
try:
|
||||
frame = loader_fn(item).convert("RGBA")
|
||||
area = frame.width * frame.height
|
||||
if area > best_area:
|
||||
best_area = area
|
||||
best_img = frame
|
||||
except Exception:
|
||||
continue
|
||||
return best_img
|
||||
|
||||
|
||||
def extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
|
||||
"""Liest den höchstauflösenden RGBA-Frame aus einer .ico-Datei."""
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", UserWarning)
|
||||
with Image.open(icon_path) as ico:
|
||||
best_img = None
|
||||
best_area = -1
|
||||
ico_helper = getattr(ico, "ico", None)
|
||||
best_img = None
|
||||
if ico_helper is not None and hasattr(ico_helper, "sizes"):
|
||||
for sz in ico_helper.sizes():
|
||||
try:
|
||||
frame = ico_helper.getimage(sz).convert("RGBA")
|
||||
area = frame.width * frame.height
|
||||
if area > best_area:
|
||||
best_area = area
|
||||
best_img = frame
|
||||
except Exception:
|
||||
continue
|
||||
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
|
||||
if best_img is None:
|
||||
for idx in range(getattr(ico, "n_frames", 1)):
|
||||
try:
|
||||
ico.seek(idx)
|
||||
frame = ico.copy().convert("RGBA")
|
||||
area = frame.width * frame.height
|
||||
if area > best_area:
|
||||
best_area = area
|
||||
best_img = frame
|
||||
except Exception:
|
||||
continue
|
||||
best_img = _pick_largest_rgba_frame(
|
||||
range(getattr(ico, "n_frames", 1)),
|
||||
lambda idx: (ico.seek(idx), ico.copy())[1],
|
||||
)
|
||||
return best_img if best_img is not None else ico.convert("RGBA")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _scan_badge_axis(primary_len: int, secondary_len: int, probe_pixel_fn) -> list[int]:
|
||||
min_span = int(secondary_len * 0.38)
|
||||
valid: list[int] = []
|
||||
for p in range(primary_len):
|
||||
cnt = sum(2 for s in range(0, secondary_len, 2) if probe_pixel_fn(p, s))
|
||||
if cnt >= min_span:
|
||||
valid.append(p)
|
||||
return valid
|
||||
|
||||
|
||||
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
|
||||
"""
|
||||
Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben)
|
||||
ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus.
|
||||
"""
|
||||
w, h = img.size
|
||||
px = img.load()
|
||||
|
||||
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
|
||||
if a < 40:
|
||||
return False
|
||||
# Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren
|
||||
if r > 228 and g > 228 and b > 228:
|
||||
return False
|
||||
return True
|
||||
return a >= 40 and not (r > 228 and g > 228 and b > 228)
|
||||
|
||||
# Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks
|
||||
# (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!)
|
||||
min_row_span = int(w * 0.38)
|
||||
valid_rows: list[int] = []
|
||||
for y in range(h):
|
||||
cnt = 0
|
||||
for x in range(0, w, 2):
|
||||
if is_badge_pixel(*px[x, y]):
|
||||
cnt += 2
|
||||
if cnt >= min_row_span:
|
||||
valid_rows.append(y)
|
||||
valid_rows = _scan_badge_axis(h, w, lambda y, x: is_badge_pixel(*px[x, y]))
|
||||
valid_cols = _scan_badge_axis(w, h, lambda x, y: is_badge_pixel(*px[x, y]))
|
||||
|
||||
min_col_span = int(h * 0.38)
|
||||
valid_cols: list[int] = []
|
||||
for x in range(w):
|
||||
cnt = 0
|
||||
for y in range(0, h, 2):
|
||||
if is_badge_pixel(*px[x, y]):
|
||||
cnt += 2
|
||||
if cnt >= min_col_span:
|
||||
valid_cols.append(x)
|
||||
cropped = (
|
||||
img.crop((valid_cols[0], valid_rows[0], valid_cols[-1] + 1, valid_rows[-1] + 1))
|
||||
if (valid_rows and valid_cols)
|
||||
else img
|
||||
)
|
||||
|
||||
if valid_rows and valid_cols:
|
||||
top, bottom = valid_rows[0], valid_rows[-1] + 1
|
||||
left, right = valid_cols[0], valid_cols[-1] + 1
|
||||
cropped = img.crop((left, top, right, bottom))
|
||||
else:
|
||||
cropped = img
|
||||
|
||||
# Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren
|
||||
side = max(cropped.width, cropped.height)
|
||||
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
|
||||
|
||||
mask_big = Image.new("L", (side * 2, side * 2), 0)
|
||||
draw = ImageDraw.Draw(mask_big)
|
||||
radius = int(side * 2 * 0.195)
|
||||
pad = int(side * 2 * 0.008)
|
||||
draw.rounded_rectangle(
|
||||
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
|
||||
radius=radius,
|
||||
radius=int(side * 2 * 0.195),
|
||||
fill=255,
|
||||
)
|
||||
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
|
||||
|
||||
r_ch, g_ch, b_ch, a_ch = square.split()
|
||||
square.putalpha(ImageChops.multiply(a_ch, mask))
|
||||
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
|
||||
return square
|
||||
|
||||
|
||||
|
|
@ -119,24 +101,19 @@ def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk
|
|||
return _ICON_TK_CACHE[cache_key]
|
||||
|
||||
if icon_path not in _ICON_PIL_CACHE:
|
||||
raw = _extract_best_ico_pil(icon_path)
|
||||
raw = extract_best_ico_pil(icon_path)
|
||||
if raw is None:
|
||||
return None
|
||||
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
|
||||
|
||||
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
|
||||
photo = ImageTk.PhotoImage(resized)
|
||||
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
|
||||
_ICON_TK_CACHE[cache_key] = photo
|
||||
return photo
|
||||
|
||||
|
||||
class SolitaireTableBgRenderer:
|
||||
"""
|
||||
Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas
|
||||
und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen.
|
||||
"""
|
||||
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
|
||||
|
||||
# Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen)
|
||||
FRAME_X_RATIO = 0.075
|
||||
FRAME_TOP_RATIO = 0.095
|
||||
FRAME_BOT_RATIO = 0.090
|
||||
|
|
@ -145,8 +122,7 @@ class SolitaireTableBgRenderer:
|
|||
self.res_mgr = res_mgr
|
||||
self._raw_pil: Image.Image | None = None
|
||||
self._loaded = False
|
||||
self._cached_size: tuple[int, int] = (0, 0)
|
||||
self._cached_photo: ImageTk.PhotoImage | None = None
|
||||
self._slice_photo: ImageTk.PhotoImage | None = None
|
||||
|
||||
def _ensure_pil(self) -> Image.Image | None:
|
||||
if not self._loaded:
|
||||
|
|
@ -161,13 +137,15 @@ class SolitaireTableBgRenderer:
|
|||
return self._raw_pil
|
||||
|
||||
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
|
||||
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
|
||||
if LayoutMode.is_compact(canvas_w, canvas_h):
|
||||
return max(8, int(canvas_w * 0.018)), 6, 8
|
||||
if self._ensure_pil() is None:
|
||||
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
|
||||
ix = max(36, int(canvas_w * self.FRAME_X_RATIO))
|
||||
itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO))
|
||||
ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO))
|
||||
return ix, itop, ibot
|
||||
return (
|
||||
max(36, int(canvas_w * self.FRAME_X_RATIO)),
|
||||
max(28, int(canvas_h * self.FRAME_TOP_RATIO)),
|
||||
max(26, int(canvas_h * self.FRAME_BOT_RATIO)),
|
||||
)
|
||||
|
||||
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
|
||||
if canvas_w < 80 or canvas_h < 80:
|
||||
|
|
@ -177,8 +155,7 @@ class SolitaireTableBgRenderer:
|
|||
if assets is None:
|
||||
return
|
||||
|
||||
rw = max(canvas_w, root.winfo_width())
|
||||
rh = max(canvas_h, root.winfo_height())
|
||||
rw, rh = max(canvas_w, root.winfo_width()), max(canvas_h, root.winfo_height())
|
||||
ox = max(0, min(rw - canvas_w, canvas.winfo_rootx() - root.winfo_rootx()))
|
||||
oy = max(0, min(rh - canvas_h, canvas.winfo_rooty() - root.winfo_rooty()))
|
||||
new_photo = assets.get_bg_patch_photo(rw, rh, ox, oy, canvas_w, canvas_h)
|
||||
|
|
|
|||
|
|
@ -1,178 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_victory_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
BG_COLOR,
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
FONT_COLOR_HEADING_SUB,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_HEADING,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
|
||||
class SolitaireVictoryDialog(tk.Canvas):
|
||||
"""
|
||||
Rahmenloses Gothic-Sieg-Overlay für Solitaire auf background_vertical.jpg + box_big.png
|
||||
mit animiertem win_gif und PIL-Old-London-Typografie.
|
||||
"""
|
||||
|
||||
DLG_W = 500
|
||||
DLG_H = 365
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ctx,
|
||||
score: int,
|
||||
moves: int,
|
||||
dur: float,
|
||||
difficulty: int,
|
||||
xp_earned: int,
|
||||
old_lvl: int,
|
||||
new_lvl: int,
|
||||
on_play_again,
|
||||
on_to_menu,
|
||||
):
|
||||
GothDropdown.close_any_open_popup()
|
||||
super().__init__(
|
||||
ctx.root,
|
||||
width=self.DLG_W,
|
||||
height=self.DLG_H,
|
||||
bg=BG_COLOR,
|
||||
bd=0,
|
||||
highlightthickness=0,
|
||||
)
|
||||
self.ctx = ctx
|
||||
self._photo_refs: list[ImageTk.PhotoImage] = []
|
||||
self._gif_job: str | None = None
|
||||
self._gif_item: int | None = None
|
||||
|
||||
self.place(relx=0.5, rely=0.52, anchor="center")
|
||||
self.bind("<Destroy>", self._on_destroy)
|
||||
self._build_scene(
|
||||
score, moves, dur, difficulty, xp_earned, old_lvl, new_lvl, on_play_again, on_to_menu
|
||||
)
|
||||
|
||||
def _on_destroy(self, _event=None):
|
||||
if self._gif_job is not None:
|
||||
try:
|
||||
self.after_cancel(self._gif_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._gif_job = None
|
||||
|
||||
def _build_scene(
|
||||
self,
|
||||
score: int,
|
||||
moves: int,
|
||||
dur: float,
|
||||
difficulty: int,
|
||||
xp_earned: int,
|
||||
old_lvl: int,
|
||||
new_lvl: int,
|
||||
on_play_again,
|
||||
on_to_menu,
|
||||
):
|
||||
w, h = self.DLG_W, self.DLG_H
|
||||
cx = w // 2
|
||||
assets = self.ctx.assets
|
||||
|
||||
bg_src = assets.raw_bg_vertical or assets.raw_bg_horizontal or 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")
|
||||
|
||||
box_ph = assets.get_box_photo("box_big", (w - 6, h - 6))
|
||||
if box_ph:
|
||||
self._photo_refs.append(box_ph)
|
||||
self.create_image(cx, h // 2, image=box_ph, anchor="center")
|
||||
|
||||
cur_y = 26
|
||||
frames = assets.get_gif_frames("win_gif", size=(155, 86))
|
||||
if frames:
|
||||
self._gif_item = self.create_image(cx, cur_y + 43, image=frames[0], anchor="center")
|
||||
cur_y += 96
|
||||
if len(frames) > 1:
|
||||
self._step_gif(frames, 0)
|
||||
else:
|
||||
cur_y += 18
|
||||
|
||||
t_ph = assets.get_goth_text_photo(
|
||||
t("sol_win_title"), FONT_SIZE_TITLE_LG - 2, FONT_COLOR_TITLE_MAIN, max_width=w - 60
|
||||
)
|
||||
self._photo_refs.append(t_ph)
|
||||
self.create_image(cx, cur_y + t_ph.height() // 2, image=t_ph, anchor="center")
|
||||
cur_y += t_ph.height() + 10
|
||||
|
||||
sum_txt = t(
|
||||
"sol_win_summary",
|
||||
score,
|
||||
moves,
|
||||
Database.format_seconds(dur),
|
||||
t(f"sol_diff_short_{difficulty}"),
|
||||
).replace("•", "-")
|
||||
s_ph = assets.get_goth_text_photo(
|
||||
sum_txt, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=w - 68
|
||||
)
|
||||
self._photo_refs.append(s_ph)
|
||||
self.create_image(cx, cur_y + s_ph.height() // 2, image=s_ph, anchor="center")
|
||||
cur_y += s_ph.height() + 10
|
||||
|
||||
xp_ph = assets.get_goth_text_photo(
|
||||
t("bj_popup_xp_earned", xp_earned), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, max_width=w - 68
|
||||
)
|
||||
self._photo_refs.append(xp_ph)
|
||||
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
|
||||
cur_y += xp_ph.height() + 8
|
||||
|
||||
if new_lvl > old_lvl:
|
||||
lvl_ph = assets.get_goth_text_photo(
|
||||
t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)),
|
||||
FONT_SIZE_BODY + 1,
|
||||
FONT_COLOR_STATUS_WIN,
|
||||
max_width=w - 64,
|
||||
)
|
||||
self._photo_refs.append(lvl_ph)
|
||||
self.create_image(cx, cur_y + lvl_ph.height() // 2, image=lvl_ph, anchor="center")
|
||||
|
||||
btn_norm = assets.raw_btn_default
|
||||
btn_purp = assets.raw_btn_purple
|
||||
btn_fire = assets.raw_btn_fire or btn_purp
|
||||
|
||||
b_again = ImageButton(
|
||||
self, t("sol_play_again_btn"), btn_fire, btn_fire,
|
||||
on_play_again, sound_mgr=self.ctx.sounds, width=178, height=38, style="fire"
|
||||
)
|
||||
b_menu = ImageButton(
|
||||
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
|
||||
on_to_menu, sound_mgr=self.ctx.sounds, width=178, height=38, style="amethyst"
|
||||
)
|
||||
|
||||
gap = 12
|
||||
tot_w = b_again.pixel_width + b_menu.pixel_width + gap
|
||||
sx = (w - tot_w) // 2
|
||||
self.create_window(sx + b_again.pixel_width // 2, h - 44, window=b_again, anchor="center")
|
||||
self.create_window(
|
||||
sx + b_again.pixel_width + gap + b_menu.pixel_width // 2,
|
||||
h - 44,
|
||||
window=b_menu,
|
||||
anchor="center",
|
||||
)
|
||||
|
||||
def _step_gif(self, frames: list, idx: int):
|
||||
if not self.winfo_exists() or self._gif_item is None:
|
||||
return
|
||||
self.itemconfigure(self._gif_item, image=frames[idx % len(frames)])
|
||||
self._gif_job = self.after(90, self._step_gif, frames, (idx + 1) % len(frames))
|
||||
|
|
@ -0,0 +1,374 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/table/solitaire_canvas_input.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from games.solitaire.base.table.solitaire_core import SolitaireCard
|
||||
from games.solitaire.base.session.solitaire_tap_prefs import (
|
||||
SINGLE_TAP_MAX_HOLD_SEC,
|
||||
is_single_tap_to_move_enabled,
|
||||
)
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD,
|
||||
BORDER_COLOR,
|
||||
CELL_BG,
|
||||
ERROR_FG,
|
||||
FONT_COLOR_TITLE_MAIN,
|
||||
FONT_SIZE_BODY,
|
||||
MUTED_FG,
|
||||
PLAYING_CARD_SIZE,
|
||||
SUBTLE_BORDER,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
|
||||
class SolitaireCanvasInput:
|
||||
"""
|
||||
Kapselt für alle Solitaire-Tische das Canvas-Frame-Rendering, Slot-/Karten-Zeichnen,
|
||||
Kartenflug-Animationen sowie Maus-, Drag-&-Drop- und Tap-/Doppelklick-Steuerung.
|
||||
"""
|
||||
|
||||
DRAG_STACK_DY_FACTOR: float = 0.195
|
||||
DRAG_THRESHOLD_PX: int = 5
|
||||
DOUBLE_CLICK_SEC: float = 0.30
|
||||
|
||||
@staticmethod
|
||||
def _card_key(card: SolitaireCard) -> tuple[str, str, int]:
|
||||
return (card.suit, card.rank, card.deck_id)
|
||||
|
||||
def _get_card_aspect(self) -> float:
|
||||
if self._card_aspect is None:
|
||||
sample_pil = self.ctx.assets._load_pil(
|
||||
self.ctx.assets.res.get_card_back_path(self.cfg["back_color"])
|
||||
)
|
||||
if sample_pil and sample_pil.size[0] > 0:
|
||||
self._card_aspect = sample_pil.size[1] / sample_pil.size[0]
|
||||
else:
|
||||
self._card_aspect = PLAYING_CARD_SIZE[1] / PLAYING_CARD_SIZE[0]
|
||||
return self._card_aspect
|
||||
|
||||
def _on_canvas_configure(self, _event=None):
|
||||
if not self._canvas_alive() or self._fx_overlay is not None:
|
||||
return
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
if self._resize_job is not None:
|
||||
try:
|
||||
self.ctx.root.after_cancel(self._resize_job)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._resize_job = self.ctx.root.after(35, self._recompute_and_draw)
|
||||
except Exception:
|
||||
self._resize_job = None
|
||||
|
||||
def _prepare_canvas_frame(
|
||||
self, min_w: int = 640, min_h: int = 420
|
||||
) -> tuple[int, int]:
|
||||
keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set(
|
||||
self.canvas.find_withtag("modal_dim_veil")
|
||||
)
|
||||
for item_id in self.canvas.find_all():
|
||||
if item_id not in keep_ids:
|
||||
self.canvas.delete(item_id)
|
||||
self._canvas_ui_refs.clear()
|
||||
cw = max(min_w, self.canvas.winfo_width())
|
||||
ch = max(min_h, self.canvas.winfo_height())
|
||||
self._bg_renderer.draw_on_canvas(self.canvas, cw, ch)
|
||||
return cw, ch
|
||||
|
||||
def _finish_canvas_frame(
|
||||
self, canvas_w: int, canvas_h: int, exclude_source, hidden: set
|
||||
):
|
||||
if (
|
||||
self.engine.has_timer_started
|
||||
and not self._window_active
|
||||
and not self.engine.won
|
||||
and not self._game_concluded
|
||||
and self._modal_overlay is None
|
||||
and self._fx_overlay is None
|
||||
):
|
||||
p_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN
|
||||
)
|
||||
bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18)
|
||||
box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh))
|
||||
self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph])
|
||||
pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18
|
||||
if box_ph:
|
||||
self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center")
|
||||
self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center")
|
||||
|
||||
if self.canvas.find_withtag("modal_dim_veil"):
|
||||
self.canvas.tag_raise("modal_dim_veil")
|
||||
if self.hover_zoom is not None and exclude_source is None and not hidden:
|
||||
self.hover_zoom.refresh_after_redraw()
|
||||
self._sync_buttons()
|
||||
|
||||
def _draw_slot(
|
||||
self,
|
||||
x: int,
|
||||
y: int,
|
||||
symbol: str = "",
|
||||
symbol_color: str = MUTED_FG,
|
||||
highlight_color: str | None = None,
|
||||
draw_red_cross: bool = False,
|
||||
):
|
||||
cw, ch = self.card_size
|
||||
outline = (
|
||||
ERROR_FG
|
||||
if draw_red_cross
|
||||
else (highlight_color if highlight_color else BORDER_COLOR)
|
||||
)
|
||||
width = 2 if (highlight_color or draw_red_cross) else 1
|
||||
self.canvas.create_rectangle(
|
||||
x, y, x + cw, y + ch, fill=CELL_BG, outline=outline, width=width
|
||||
)
|
||||
if draw_red_cross:
|
||||
px, py = max(14, int(cw * 0.22)), max(18, int(ch * 0.22))
|
||||
self.canvas.create_line(
|
||||
x + px, y + py, x + cw - px, y + ch - py,
|
||||
fill="#ff4455", width=4, capstyle="round",
|
||||
)
|
||||
self.canvas.create_line(
|
||||
x + cw - px, y + py, x + px, y + ch - py,
|
||||
fill="#ff4455", width=4, capstyle="round",
|
||||
)
|
||||
elif symbol:
|
||||
self.canvas.create_text(
|
||||
x + cw // 2,
|
||||
y + ch // 2,
|
||||
text=symbol,
|
||||
font=("Georgia", max(13, cw // 4), "bold"),
|
||||
fill=symbol_color,
|
||||
)
|
||||
|
||||
def _draw_card_at(
|
||||
self,
|
||||
card: SolitaireCard,
|
||||
x: int,
|
||||
y: int,
|
||||
tags: tuple[str, ...] = (),
|
||||
highlight_color: str | None = None,
|
||||
dim_non_movable: bool = False,
|
||||
):
|
||||
cw, ch = self.card_size
|
||||
photo = (
|
||||
self.ctx.assets.get_card_photo(card.filename, size=self.card_size)
|
||||
if card.face_up
|
||||
else self.ctx.assets.get_card_back_photo(
|
||||
self.cfg["back_color"], size=self.card_size
|
||||
)
|
||||
)
|
||||
if photo is not None:
|
||||
self.canvas.create_image(x, y, image=photo, anchor="nw", tags=tags)
|
||||
else:
|
||||
fill_c = "#f5f2f8" if card.face_up else "#201a2b"
|
||||
self.canvas.create_rectangle(
|
||||
x, y, x + cw, y + ch, fill=fill_c, outline=BORDER_COLOR, tags=tags
|
||||
)
|
||||
if card.face_up:
|
||||
txt_c = "#c93b4b" if card.is_red else "#16131d"
|
||||
self.canvas.create_text(
|
||||
x + 9, y + 11, text=card.label, anchor="nw",
|
||||
font=("Georgia", 10, "bold"), fill=txt_c, tags=tags,
|
||||
)
|
||||
|
||||
if dim_non_movable and card.face_up and not highlight_color:
|
||||
self.canvas.create_rectangle(
|
||||
x, y, x + cw, y + ch, outline=SUBTLE_BORDER, width=1, tags=tags
|
||||
)
|
||||
if highlight_color:
|
||||
self.canvas.create_rectangle(
|
||||
x - 2, y - 2, x + cw + 2, y + ch + 2,
|
||||
outline=highlight_color, width=2, tags=tags,
|
||||
)
|
||||
|
||||
def _run_animated_action(
|
||||
self, action_fn, override_starts=None, duration_ms: int = 115, after_cb=None
|
||||
) -> bool:
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
before_pos = self._snapshot_card_positions()
|
||||
if override_starts:
|
||||
before_pos.update(override_starts)
|
||||
|
||||
if not action_fn():
|
||||
return False
|
||||
|
||||
after_pos = self._snapshot_card_positions()
|
||||
moved_keys = {
|
||||
k
|
||||
for k, end_xy in after_pos.items()
|
||||
if k in before_pos
|
||||
and (
|
||||
abs(end_xy[0] - before_pos[k][0]) > 3
|
||||
or abs(end_xy[1] - before_pos[k][1]) > 3
|
||||
)
|
||||
}
|
||||
if not moved_keys or self.animator is None:
|
||||
(after_cb if callable(after_cb) else self.redraw)()
|
||||
return True
|
||||
|
||||
flights = [
|
||||
{
|
||||
"card": c,
|
||||
"start": before_pos[self._card_key(c)],
|
||||
"end": after_pos[self._card_key(c)],
|
||||
}
|
||||
for c in self._ordered_moved_cards(moved_keys)
|
||||
]
|
||||
self.redraw(hidden_card_keys=moved_keys)
|
||||
|
||||
def finish():
|
||||
if self._canvas_alive():
|
||||
(after_cb if callable(after_cb) else self.redraw)()
|
||||
|
||||
self.animator.start(
|
||||
flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish
|
||||
)
|
||||
return True
|
||||
|
||||
def _on_mouse_down(self, event):
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
if self._is_ui_locked():
|
||||
return
|
||||
if self.animator and self.animator.is_active:
|
||||
self.animator.flush()
|
||||
self._window_active = True
|
||||
self._clear_hint()
|
||||
hit = self._hit_test(event.x, event.y)
|
||||
self._press_info = None
|
||||
self._dragging = False
|
||||
if not hit:
|
||||
return
|
||||
self.engine.start_timer_if_needed()
|
||||
self._update_hud_text()
|
||||
hit["start_xy"] = (event.x, event.y)
|
||||
hit["press_ts"] = time.monotonic()
|
||||
self._press_info = hit
|
||||
|
||||
def _on_mouse_move(self, event):
|
||||
if (
|
||||
not self._press_info
|
||||
or not self._press_info.get("cards")
|
||||
or self._fx_overlay is not None
|
||||
):
|
||||
return
|
||||
sx, sy = self._press_info["start_xy"]
|
||||
if not self._dragging:
|
||||
if (
|
||||
abs(event.x - sx) < self.DRAG_THRESHOLD_PX
|
||||
and abs(event.y - sy) < self.DRAG_THRESHOLD_PX
|
||||
):
|
||||
return
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
self._dragging = True
|
||||
self._drag_last_xy = (sx, sy)
|
||||
self.redraw(exclude_source=self._press_info)
|
||||
ox, oy = self._press_info["origin"]
|
||||
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
|
||||
for i, card in enumerate(self._press_info["cards"]):
|
||||
self._draw_card_at(
|
||||
card,
|
||||
ox,
|
||||
oy + i * drag_dy,
|
||||
tags=("drag_ghost",),
|
||||
highlight_color=ACCENT_GOLD if i == 0 else None,
|
||||
)
|
||||
|
||||
dx = event.x - self._drag_last_xy[0]
|
||||
dy = event.y - self._drag_last_xy[1]
|
||||
self._drag_last_xy = (event.x, event.y)
|
||||
self.canvas.move("drag_ghost", dx, dy)
|
||||
|
||||
def _on_drop_succeeded_sound(self):
|
||||
self.ctx.sounds.play("click")
|
||||
|
||||
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
|
||||
|
||||
ox, oy = info["origin"]
|
||||
sx, sy = info["start_xy"]
|
||||
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
|
||||
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
|
||||
override = {
|
||||
self._card_key(c): (drop_x, drop_y + i * drag_dy)
|
||||
for i, c in enumerate(info["cards"])
|
||||
}
|
||||
|
||||
if self._run_animated_action(
|
||||
lambda: self._try_drop(info, drop_x, drop_y),
|
||||
override_starts=override,
|
||||
duration_ms=78,
|
||||
after_cb=self._after_player_move,
|
||||
):
|
||||
self._on_drop_succeeded_sound()
|
||||
else:
|
||||
target_pos = self._snapshot_card_positions()
|
||||
cards: list[SolitaireCard] = info["cards"]
|
||||
hidden_keys = {self._card_key(c) for c in cards}
|
||||
flights = [
|
||||
{
|
||||
"card": c,
|
||||
"start": override[self._card_key(c)],
|
||||
"end": target_pos.get(self._card_key(c), (ox, oy + i * drag_dy)),
|
||||
}
|
||||
for i, c in enumerate(cards)
|
||||
]
|
||||
self.redraw(hidden_card_keys=hidden_keys)
|
||||
if self.animator:
|
||||
self.animator.start(
|
||||
flights, self._draw_card_at, duration_ms=85, on_done=self.redraw
|
||||
)
|
||||
else:
|
||||
self.redraw()
|
||||
|
||||
def _dispatch_tap_or_double_click(self, info: dict):
|
||||
now = time.monotonic()
|
||||
if is_single_tap_to_move_enabled():
|
||||
self._last_click_target = None
|
||||
if (now - info.get("press_ts", now)) <= SINGLE_TAP_MAX_HOLD_SEC:
|
||||
self._smart_auto_move(info)
|
||||
return
|
||||
target_id = (info["zone"], info.get("col", -1), info.get("idx", -1))
|
||||
if (
|
||||
self._last_click_target == target_id
|
||||
and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC
|
||||
):
|
||||
self._last_click_target = None
|
||||
self._smart_auto_move(info)
|
||||
else:
|
||||
self._last_click_ts = now
|
||||
self._last_click_target = target_id
|
||||
|
||||
def _on_right_click(self, event):
|
||||
if self.hover_zoom is not None:
|
||||
self.hover_zoom.cancel()
|
||||
if self._is_ui_locked():
|
||||
return
|
||||
if self.animator and self.animator.is_active:
|
||||
self.animator.flush()
|
||||
self._window_active = True
|
||||
self._clear_hint()
|
||||
hit = self._hit_test(event.x, event.y)
|
||||
if hit:
|
||||
self.engine.start_timer_if_needed()
|
||||
self._update_hud_text()
|
||||
if hit.get("zone") == "stock":
|
||||
self._handle_click(hit)
|
||||
else:
|
||||
self._smart_auto_move(hit)
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/solitaire_core.py
|
||||
# games/solitaire/base/table/solitaire_core.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
from games.solitaire.base.solitaire_card import (
|
||||
from games.solitaire.base.cards.solitaire_card import (
|
||||
RANK_VALUES,
|
||||
SOLITAIRE_RANKS,
|
||||
SolitaireCard,
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/table/solitaire_table_controller.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
||||
from games.solitaire.base.cards.card_animator import CardFlightAnimator
|
||||
from games.solitaire.base.cards.card_hover_zoom import CardHoverZoom
|
||||
from view.widgets.bars.goth_bottombar import GothBottombar
|
||||
from games.solitaire.base.table.solitaire_core import SolitaireCard
|
||||
from games.solitaire.base.session.solitaire_outcome_flow import SolitaireOutcomeFlow
|
||||
from games.solitaire.base.session.solitaire_session_guard import SolitaireSessionGuard
|
||||
from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer
|
||||
from resources.code_res.game_constants import (
|
||||
PLAYING_CARD_SIZE,
|
||||
SOLITAIRE_DIFFICULTIES,
|
||||
TABLE_BG,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.overlays.endgame_fx_overlay import EndgameFxOverlay
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
|
||||
|
||||
class SolitaireTableController(SolitaireSessionGuard):
|
||||
"""
|
||||
Gemeinsame Tisch-Basisklasse für alle Solitaire-Spiele:
|
||||
Baut Topbar/BottomBar/Canvas auf und steuert Undo, Hint, Auto-Complete & Neu-Geben.
|
||||
"""
|
||||
|
||||
GAME_FOLDER_ID: str = ""
|
||||
HAS_AUTOCOMPLETE_BTN: bool = True
|
||||
AUTO_STEP_DELAY_MS: int = 12
|
||||
AUTO_FLIGHT_MS: int = 75
|
||||
SPEED_THRESHOLDS_SEC: tuple[int, int] = (180, 330)
|
||||
|
||||
def _init_controller_state(
|
||||
self, context, variant_key: str, cfg: dict, difficulty: int, on_back_to_menu
|
||||
):
|
||||
self.ctx = context
|
||||
self.variant_key = variant_key
|
||||
self.cfg = cfg
|
||||
self.difficulty = max(0, min(3, int(difficulty)))
|
||||
self.on_back_to_menu = on_back_to_menu
|
||||
|
||||
self._alive = True
|
||||
self._game_concluded = False
|
||||
self._window_active = True
|
||||
self._checkpoint_ticks = 0
|
||||
self._tick_job: str | None = None
|
||||
self._focus_job: str | None = None
|
||||
self._hint_job: str | None = None
|
||||
self._auto_job: str | None = None
|
||||
self._resize_job: str | None = None
|
||||
self._bind_ids: list[tuple[str, str]] = []
|
||||
self._auto_running = False
|
||||
|
||||
self.animator: CardFlightAnimator | None = None
|
||||
self.hover_zoom: CardHoverZoom | None = None
|
||||
self._fx_overlay: EndgameFxOverlay | None = None
|
||||
self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res)
|
||||
self._frame_bot_pad: int = 18
|
||||
self._canvas_ui_refs: list = []
|
||||
|
||||
self._card_aspect: float | None = None
|
||||
self.card_size: tuple[int, int] = PLAYING_CARD_SIZE
|
||||
|
||||
self._press_info: dict | None = None
|
||||
self._dragging: bool = False
|
||||
self._drag_last_xy: tuple[int, int] = (0, 0)
|
||||
self._last_click_ts: float = 0.0
|
||||
self._last_click_target: tuple | None = None
|
||||
self._active_hint: dict | None = None
|
||||
self._modal_overlay: tk.Widget | None = None
|
||||
self.auto_btn: ImageButton | None = None
|
||||
|
||||
def _finish_startup(self, is_resumed: bool):
|
||||
self._build_ui()
|
||||
if not is_resumed:
|
||||
self.ctx.sounds.play("deal")
|
||||
self._check_window_focus()
|
||||
self._save_progress()
|
||||
self._start_clock()
|
||||
|
||||
@property
|
||||
def _combined_xp_mult(self) -> float:
|
||||
d_mult = SOLITAIRE_DIFFICULTIES.get(
|
||||
self.difficulty, SOLITAIRE_DIFFICULTIES[1]
|
||||
)["xp_mult"]
|
||||
return self.cfg["xp_mult"] * d_mult
|
||||
|
||||
def _build_ui(self):
|
||||
self._play_table_music()
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
self.ctx.refresh_game_progress()
|
||||
|
||||
self.topbar = self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
stats_endpoint=self.GAME_FOLDER_ID,
|
||||
stats_enabled=True,
|
||||
on_lang_refresh=self._refresh_lang,
|
||||
on_stats_back=self._schedule_focus_check,
|
||||
)
|
||||
|
||||
self.hud_var = tk.StringVar(value="")
|
||||
self.status_var = tk.StringVar(value="")
|
||||
|
||||
self.bottom_bar = GothBottombar(
|
||||
self.ctx.root, self.ctx, self.hud_var, self.status_var
|
||||
)
|
||||
self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10))
|
||||
|
||||
btn_norm = self.ctx.assets.raw_btn_default
|
||||
btn_purp = self.ctx.assets.raw_btn_purple
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
|
||||
|
||||
self.undo_btn = ImageButton(
|
||||
self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp,
|
||||
self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32,
|
||||
enabled=self.engine.can_undo, style="amethyst",
|
||||
)
|
||||
self.undo_all_btn = ImageButton(
|
||||
self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp,
|
||||
self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32,
|
||||
enabled=self.engine.can_undo_all, style="amethyst",
|
||||
)
|
||||
self.hint_btn = ImageButton(
|
||||
self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp,
|
||||
self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32,
|
||||
enabled=not self.engine.won, style="amethyst",
|
||||
)
|
||||
main_btns = [self.undo_btn, self.undo_all_btn, self.hint_btn]
|
||||
if self.HAS_AUTOCOMPLETE_BTN:
|
||||
self.auto_btn = ImageButton(
|
||||
self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire,
|
||||
self._start_auto_complete, sound_mgr=self.ctx.sounds,
|
||||
width=112, height=32, enabled=self.engine.can_auto_complete(),
|
||||
style="fire",
|
||||
)
|
||||
main_btns.append(self.auto_btn)
|
||||
|
||||
self.new_btn = ImageButton(
|
||||
self.bottom_bar,
|
||||
t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"),
|
||||
btn_norm, btn_purp, self._on_new_or_forfeit_clicked,
|
||||
sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst",
|
||||
)
|
||||
self.bottom_bar.set_buttons(main_btns, overflow_buttons=[self.new_btn])
|
||||
|
||||
self.canvas = tk.Canvas(
|
||||
self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0
|
||||
)
|
||||
self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2))
|
||||
self.animator = CardFlightAnimator(self.ctx.root, self.canvas)
|
||||
self.hover_zoom = CardHoverZoom(
|
||||
self.ctx.root,
|
||||
self.canvas,
|
||||
self.ctx.assets,
|
||||
probe_fn=self._hover_card_probe,
|
||||
can_show_fn=self._can_show_hover_zoom,
|
||||
)
|
||||
|
||||
self.canvas.bind("<Configure>", self._on_canvas_configure)
|
||||
self.canvas.bind("<Destroy>", self._on_canvas_destroy)
|
||||
self.canvas.bind("<ButtonPress-1>", self._on_mouse_down)
|
||||
self.canvas.bind("<B1-Motion>", self._on_mouse_move)
|
||||
self.canvas.bind("<ButtonRelease-1>", self._on_mouse_up)
|
||||
self.canvas.bind("<ButtonPress-3>", self._on_right_click)
|
||||
|
||||
self._bind_root("<Control-z>", lambda _e: self._run_undo_shortcut(False))
|
||||
self._bind_root("<Control-Shift-Z>", lambda _e: self._run_undo_shortcut(True))
|
||||
self._bind_root("<Control-Shift-z>", lambda _e: self._run_undo_shortcut(True))
|
||||
self._bind_root("<KeyPress-h>", lambda _e: self._on_hint())
|
||||
self._bind_root("<KeyPress-H>", lambda _e: self._on_hint())
|
||||
self._bind_root("<FocusIn>", self._schedule_focus_check)
|
||||
self._bind_root("<FocusOut>", self._schedule_focus_check)
|
||||
|
||||
self._update_hud_text()
|
||||
|
||||
def _run_undo_shortcut(self, all_moves: bool) -> str:
|
||||
if self._fx_overlay is not None or self._game_concluded or self._auto_running:
|
||||
return "break"
|
||||
can_act = self.engine.can_undo_all if all_moves else self.engine.can_undo
|
||||
if can_act:
|
||||
if self._modal_overlay is not None:
|
||||
self._close_active_modal()
|
||||
self.ctx.sounds.play("click")
|
||||
(self._on_undo_all if all_moves else self._on_undo)()
|
||||
return "break"
|
||||
|
||||
def _sync_buttons(self):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
locked = self._is_ui_locked()
|
||||
self.undo_btn.set_enabled((not locked) and self.engine.can_undo)
|
||||
self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all)
|
||||
self.hint_btn.set_enabled(not locked)
|
||||
if self.auto_btn is not None:
|
||||
self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete())
|
||||
self.new_btn.set_enabled(
|
||||
(not self._auto_running)
|
||||
and (self._fx_overlay is None)
|
||||
and (self._modal_overlay is None)
|
||||
)
|
||||
new_lbl = (
|
||||
t("sol_btn_forfeit")
|
||||
if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded)
|
||||
else t("sol_btn_new_deal")
|
||||
)
|
||||
prev_w = self.new_btn.pixel_width
|
||||
self.new_btn.set_text(new_lbl)
|
||||
if self.new_btn.pixel_width != prev_w:
|
||||
self.bottom_bar.relayout()
|
||||
self._update_hud_text()
|
||||
|
||||
def _status_after_move(self) -> str:
|
||||
return ""
|
||||
|
||||
def _after_player_move(self):
|
||||
self.status_var.set(self._status_after_move())
|
||||
self._checkpoint_ticks = 0
|
||||
self.redraw()
|
||||
if self.engine.won:
|
||||
SolitaireOutcomeFlow.handle_victory(self)
|
||||
return
|
||||
self._save_progress()
|
||||
self._check_deadlock_and_prompt()
|
||||
|
||||
def _check_deadlock_and_prompt(self):
|
||||
if not self._is_ui_locked() and not self.engine.has_any_meaningful_move():
|
||||
SolitaireOutcomeFlow.show_deadlock_modal(self)
|
||||
|
||||
def _on_undo(self):
|
||||
if self._is_ui_locked():
|
||||
return
|
||||
self._clear_hint()
|
||||
|
||||
def _done():
|
||||
self.status_var.set("")
|
||||
self._checkpoint_ticks = 0
|
||||
self._save_progress()
|
||||
self.redraw()
|
||||
|
||||
self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=_done)
|
||||
|
||||
def _on_undo_all(self):
|
||||
if self._is_ui_locked():
|
||||
return
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
self._clear_hint()
|
||||
if self.engine.undo_all():
|
||||
self.status_var.set("")
|
||||
self._checkpoint_ticks = 0
|
||||
self._save_progress()
|
||||
self.redraw()
|
||||
|
||||
def _clear_hint(self):
|
||||
if self._hint_job is not None:
|
||||
try:
|
||||
self.ctx.root.after_cancel(self._hint_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._hint_job = None
|
||||
self._active_hint = None
|
||||
|
||||
def _on_hint(self):
|
||||
if self._is_ui_locked():
|
||||
return
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
self._clear_hint()
|
||||
self.engine.start_timer_if_needed()
|
||||
self._update_hud_text()
|
||||
hint = self.engine.get_hint()
|
||||
if not hint:
|
||||
self.status_var.set(t("sol_no_hint_msg"))
|
||||
self._check_deadlock_and_prompt()
|
||||
return
|
||||
self.status_var.set("")
|
||||
self._active_hint = hint
|
||||
self.redraw()
|
||||
self._hint_job = self.ctx.root.after(1600, self._expire_hint)
|
||||
|
||||
def _expire_hint(self):
|
||||
self._hint_job = None
|
||||
self._active_hint = None
|
||||
if self._canvas_alive() and self._fx_overlay is None:
|
||||
self.redraw()
|
||||
|
||||
def _start_auto_complete(self):
|
||||
if (
|
||||
not self.HAS_AUTOCOMPLETE_BTN
|
||||
or not self.engine.can_auto_complete()
|
||||
or self._is_ui_locked()
|
||||
):
|
||||
return
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
self._clear_hint()
|
||||
self.engine.push_undo()
|
||||
self._save_progress()
|
||||
self._auto_running = True
|
||||
self._sync_buttons()
|
||||
self._step_auto_complete()
|
||||
|
||||
def _step_auto_complete(self):
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
|
||||
def after_step():
|
||||
if not self._canvas_alive():
|
||||
return
|
||||
self.redraw()
|
||||
if not self.engine.won:
|
||||
self._auto_job = self.ctx.root.after(
|
||||
self.AUTO_STEP_DELAY_MS, self._step_auto_complete
|
||||
)
|
||||
else:
|
||||
self._auto_running, self._auto_job = False, None
|
||||
SolitaireOutcomeFlow.handle_victory(self)
|
||||
|
||||
if self._run_animated_action(
|
||||
lambda: bool(self.engine.auto_complete_step(record_undo=False)),
|
||||
duration_ms=self.AUTO_FLIGHT_MS,
|
||||
after_cb=after_step,
|
||||
):
|
||||
self.ctx.sounds.play("click")
|
||||
else:
|
||||
self._auto_running, self._auto_job = False, None
|
||||
self.redraw()
|
||||
if self.engine.won:
|
||||
SolitaireOutcomeFlow.handle_victory(self)
|
||||
else:
|
||||
self._save_progress()
|
||||
|
||||
def _start_fresh_deal(self):
|
||||
self._game_concluded = False
|
||||
self._reset_engine_for_new_deal()
|
||||
self._check_window_focus()
|
||||
self._save_progress()
|
||||
self.status_var.set("")
|
||||
self.ctx.sounds.play("deal")
|
||||
self.redraw()
|
||||
|
||||
def _on_new_or_forfeit_clicked(self):
|
||||
if (
|
||||
self._auto_running
|
||||
or self._modal_overlay is not None
|
||||
or self._fx_overlay is not None
|
||||
):
|
||||
return
|
||||
if self.animator:
|
||||
self.animator.flush()
|
||||
if self.engine.won or self._game_concluded or self.engine.moves == 0:
|
||||
self._start_fresh_deal()
|
||||
return
|
||||
SolitaireOutcomeFlow.show_forfeit_modal(self)
|
||||
|
||||
def _reset_engine_for_new_deal(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def _recompute_and_draw(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def redraw(self, exclude_source=None, hidden_card_keys=None):
|
||||
raise NotImplementedError
|
||||
|
||||
def _snapshot_card_positions(self) -> dict:
|
||||
raise NotImplementedError
|
||||
|
||||
def _ordered_moved_cards(self, moved_keys: set) -> list[SolitaireCard]:
|
||||
raise NotImplementedError
|
||||
|
||||
def _hover_card_probe(self, x: int, y: int) -> dict | None:
|
||||
raise NotImplementedError
|
||||
|
||||
def _hit_test(self, x: int, y: int) -> dict | None:
|
||||
raise NotImplementedError
|
||||
|
||||
def _handle_click(self, info: dict):
|
||||
raise NotImplementedError
|
||||
|
||||
def _smart_auto_move(self, info: dict):
|
||||
raise NotImplementedError
|
||||
|
||||
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
|
||||
raise NotImplementedError
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -2,7 +2,7 @@
|
|||
# games/solitaire/freecell/models/freecell_engine.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.solitaire.base.solitaire_core import (
|
||||
from games.solitaire.base.table.solitaire_core import (
|
||||
SolitaireBaseEngine,
|
||||
SolitaireCard,
|
||||
is_alternating_descending,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import heapq
|
|||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
|
||||
from games.solitaire.base.table.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
|
||||
from resources.code_res.game_constants import SUITS
|
||||
|
||||
_IS_RED = tuple((c // 13) in (1, 2) for c in range(52))
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -2,402 +2,38 @@
|
|||
# games/solitaire/freecell/views/freecell_menu_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tkinter as tk
|
||||
|
||||
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
|
||||
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
|
||||
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
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_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
FREECELL_VARIANTS,
|
||||
SOLITAIRE_DIFFICULTIES,
|
||||
SOLO_FORFEIT_XP_RATIO,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from resources.code_res.game_constants import FREECELL_VARIANTS
|
||||
|
||||
GAME_FOLDER_ID = "solitaire/freecell"
|
||||
GAME_TITLE_KEY = "game_title_freecell"
|
||||
DEFAULT_VARIANT_KEY = "freecell_std"
|
||||
|
||||
|
||||
class FreeCellMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self._modal_overlay: tk.Widget | None = None
|
||||
self._return_bind_id: str | None = None
|
||||
self._photo_refs: list = []
|
||||
class FreeCellMenuView(SolitaireMenuBase):
|
||||
GAME_FOLDER_ID = GAME_FOLDER_ID
|
||||
GAME_TITLE_KEY = GAME_TITLE_KEY
|
||||
TOPBAR_KEY = "fc_menu_topbar"
|
||||
SUBTITLE_KEY = "fc_menu_subtitle"
|
||||
CONTROLS_HINT_KEY = "fc_controls_hint"
|
||||
|
||||
def _clear_modal(self):
|
||||
if self._return_bind_id is not None:
|
||||
try:
|
||||
self.ctx.root.unbind("<Return>", self._return_bind_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._return_bind_id = None
|
||||
if self._modal_overlay is not None:
|
||||
try:
|
||||
self._modal_overlay.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
self._modal_overlay = None
|
||||
DIFF_SETTING_PREFIX = "freecell_diff"
|
||||
DEFAULT_VARIANT_KEY = "freecell_std"
|
||||
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
|
||||
|
||||
def show(
|
||||
self,
|
||||
status_msg: str = "",
|
||||
status_is_ok: bool = False,
|
||||
ask_resume_popup: bool = False,
|
||||
):
|
||||
self._clear_modal()
|
||||
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.ctx.refresh_game_progress()
|
||||
MODE_LABEL_KEY = "fc_variant_info_lbl"
|
||||
DESC_KEY_PREFIX = "fc_desc_"
|
||||
|
||||
diff_setting_key = f"freecell_diff_{pid}"
|
||||
saved_diff_str = Database.load_setting(diff_setting_key, "1")
|
||||
selected_diff = (
|
||||
int(saved_diff_str)
|
||||
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
|
||||
else 1
|
||||
)
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
return FREECELL_VARIANTS
|
||||
|
||||
def open_stats():
|
||||
self._clear_modal()
|
||||
SolitaireStatsView(
|
||||
self.ctx,
|
||||
game_folder=GAME_FOLDER_ID,
|
||||
game_title_key=GAME_TITLE_KEY,
|
||||
on_back=lambda: self.show(),
|
||||
).show()
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("fc_menu_topbar"),
|
||||
on_game_menu=None,
|
||||
on_stats=open_stats,
|
||||
stats_enabled=True,
|
||||
extra_right_text="",
|
||||
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
|
||||
)
|
||||
|
||||
cv = MenuBodyCanvas(self.ctx)
|
||||
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
|
||||
|
||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
||||
saved_meta = self._parse_saved_meta(saved)
|
||||
|
||||
resume_btn = None
|
||||
if saved and saved_meta is not None:
|
||||
resume_btn = ImageButton(
|
||||
cv,
|
||||
t("sol_resume_btn"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=180,
|
||||
height=38,
|
||||
style="fire",
|
||||
)
|
||||
|
||||
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
|
||||
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
|
||||
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
|
||||
|
||||
diff_dd = GothDropdown(
|
||||
cv,
|
||||
self.ctx.assets,
|
||||
values=diff_labels,
|
||||
textvariable=diff_var,
|
||||
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=420,
|
||||
height=40,
|
||||
)
|
||||
|
||||
start_btn = ImageButton(
|
||||
cv,
|
||||
t("sol_start_btn"),
|
||||
btn_fire,
|
||||
btn_fire,
|
||||
lambda: self._on_start_clicked(
|
||||
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
|
||||
),
|
||||
sound_mgr=self.ctx.sounds,
|
||||
width=205,
|
||||
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(26, int(h * 0.06))
|
||||
|
||||
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("fc_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() + 14
|
||||
|
||||
if status_msg:
|
||||
st_ph = self.ctx.assets.get_goth_text_photo(
|
||||
status_msg,
|
||||
FONT_SIZE_BODY,
|
||||
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
|
||||
max_width=box_w,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.append(st_ph)
|
||||
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
|
||||
cur_y += st_ph.height() + 12
|
||||
|
||||
if saved and saved_meta is not None and resume_btn is not None:
|
||||
res_h = 84
|
||||
res_cy = cur_y + res_h // 2
|
||||
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
|
||||
if r_box:
|
||||
self._photo_refs.append(r_box)
|
||||
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
|
||||
|
||||
rt_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
ri_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t(
|
||||
"sol_resume_info",
|
||||
t(f"variant_{saved['variant_key']}"),
|
||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
||||
saved_meta["moves"],
|
||||
saved_meta["score"],
|
||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
||||
),
|
||||
FONT_SIZE_BODY,
|
||||
FONT_COLOR_BODY_DEFAULT,
|
||||
max_width=box_w - resume_btn.pixel_width - 70,
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.extend([rt_ph, ri_ph])
|
||||
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
|
||||
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
|
||||
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
|
||||
cur_y += res_h + 18
|
||||
|
||||
sec_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(sec_ph)
|
||||
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
|
||||
cur_y += sec_ph.height() + 8
|
||||
|
||||
setup_h = 208
|
||||
setup_cy = cur_y + setup_h // 2
|
||||
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
|
||||
if s_box:
|
||||
self._photo_refs.append(s_box)
|
||||
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
|
||||
|
||||
lbl_col = x_left + 32
|
||||
val_col = x_left + 225
|
||||
|
||||
# Zeile 1: Modus
|
||||
r1_y = cur_y + 44
|
||||
m_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t("fc_variant_info_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||
)
|
||||
m_val = self.ctx.assets.get_goth_text_photo(
|
||||
t("variant_freecell_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
|
||||
)
|
||||
m_dsc = self.ctx.assets.get_goth_text_photo(
|
||||
t("fc_desc_freecell_std"),
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
FONT_COLOR_BODY_MUTED,
|
||||
max_width=max(180, box_w - 275 - m_val.width()),
|
||||
align="left",
|
||||
)
|
||||
self._photo_refs.extend([m_lbl, m_val, m_dsc])
|
||||
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
|
||||
cv.create_image(val_col, r1_y, image=m_val, anchor="w", tags="fg")
|
||||
cv.create_image(val_col + m_val.width() + 18, r1_y, image=m_dsc, anchor="w", tags="fg")
|
||||
|
||||
# Zeile 2: Schwierigkeitsgrad
|
||||
r2_y = cur_y + 104
|
||||
d_lbl = self.ctx.assets.get_goth_text_photo(
|
||||
t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
|
||||
)
|
||||
self._photo_refs.append(d_lbl)
|
||||
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
|
||||
|
||||
dd_w = max(240, box_w - 265)
|
||||
if diff_dd._width != dd_w:
|
||||
diff_dd._width = dd_w
|
||||
diff_dd.configure(width=dd_w)
|
||||
diff_dd._render_closed()
|
||||
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
|
||||
|
||||
# Zeile 3: Start
|
||||
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
|
||||
|
||||
hint_ph = self.ctx.assets.get_goth_text_photo(
|
||||
t("fc_controls_hint"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
|
||||
)
|
||||
self._photo_refs.append(hint_ph)
|
||||
cv.create_image(x_left + 6, cur_y + setup_h + 14, image=hint_ph, anchor="nw", 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()))
|
||||
|
||||
if ask_resume_popup and saved and saved_meta is not None:
|
||||
self._show_resume_prompt_modal(saved, saved_meta)
|
||||
|
||||
@staticmethod
|
||||
def _parse_saved_meta(saved: dict | None) -> dict | None:
|
||||
if not saved:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(saved["state_json"])
|
||||
if data.get("won"):
|
||||
return None
|
||||
board = data.get("board", {})
|
||||
if not board or "tableau" not in board or "freecells" not in board:
|
||||
return None
|
||||
return {
|
||||
"moves": max(0, int(data.get("moves", 0))),
|
||||
"score": int(data.get("score", 0)),
|
||||
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
|
||||
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
|
||||
self._clear_modal()
|
||||
|
||||
def resume_now(_event=None):
|
||||
self._clear_modal()
|
||||
self._resume_saved(saved, saved_meta["difficulty"])
|
||||
|
||||
try:
|
||||
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
|
||||
except tk.TclError:
|
||||
self._return_bind_id = None
|
||||
|
||||
info_txt = t(
|
||||
"sol_resume_info",
|
||||
t(f"variant_{saved['variant_key']}"),
|
||||
t(f"sol_diff_short_{saved_meta['difficulty']}"),
|
||||
saved_meta["moves"],
|
||||
saved_meta["score"],
|
||||
Database.format_seconds(saved_meta["elapsed_sec"]),
|
||||
)
|
||||
self._modal_overlay = SolitaireModalDialog(
|
||||
self.ctx,
|
||||
title_txt=t("sol_resume_box_title"),
|
||||
body_txt=info_txt,
|
||||
buttons=[
|
||||
(t("sol_resume_btn"), "fire", resume_now),
|
||||
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||
],
|
||||
)
|
||||
|
||||
def _resume_saved(self, saved: dict, difficulty: int):
|
||||
self._clear_modal()
|
||||
FreeCellTableView(
|
||||
self.ctx,
|
||||
variant_key=saved["variant_key"],
|
||||
difficulty=difficulty,
|
||||
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
|
||||
resume_state_json=saved["state_json"],
|
||||
)
|
||||
|
||||
def _on_start_clicked(
|
||||
self,
|
||||
variant_key: str,
|
||||
difficulty: int,
|
||||
saved: dict | None,
|
||||
saved_meta: dict | None,
|
||||
):
|
||||
if self._modal_overlay is not None:
|
||||
return
|
||||
if saved and saved_meta and saved_meta["moves"] > 0:
|
||||
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
|
||||
return
|
||||
self._launch_fresh_game(variant_key, difficulty)
|
||||
|
||||
def _show_overwrite_confirm_modal(
|
||||
self,
|
||||
new_variant_key: str,
|
||||
new_difficulty: int,
|
||||
saved: dict,
|
||||
saved_meta: dict,
|
||||
):
|
||||
pid = self.ctx.profile["id"]
|
||||
old_v = saved["variant_key"]
|
||||
old_diff = saved_meta["difficulty"]
|
||||
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
|
||||
v_mult = FREECELL_VARIANTS.get(old_v, {"xp_mult": 1.15})["xp_mult"]
|
||||
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
|
||||
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
|
||||
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
|
||||
|
||||
def forfeit_and_start():
|
||||
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
|
||||
Database.record_game_result(
|
||||
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
|
||||
)
|
||||
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
|
||||
self.ctx.refresh_game_progress()
|
||||
self._clear_modal()
|
||||
self._launch_fresh_game(new_variant_key, new_difficulty)
|
||||
|
||||
self._modal_overlay = SolitaireModalDialog(
|
||||
self.ctx,
|
||||
title_txt=t("sol_forfeit_title"),
|
||||
body_txt=t("sol_forfeit_desc", penalty),
|
||||
is_danger=True,
|
||||
buttons=[
|
||||
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
|
||||
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
|
||||
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
|
||||
],
|
||||
)
|
||||
|
||||
def _launch_fresh_game(self, variant_key: str, difficulty: int):
|
||||
pid = self.ctx.profile["id"]
|
||||
Database.save_setting(f"freecell_diff_{pid}", str(difficulty))
|
||||
Database.delete_game_state(pid, GAME_FOLDER_ID)
|
||||
def _launch_table_view(
|
||||
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||
) -> None:
|
||||
FreeCellTableView(
|
||||
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,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue