Compare commits
No commits in common. "main" and "beta_5" have entirely different histories.
|
|
@ -1,96 +0,0 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
|
@ -71,12 +71,6 @@ 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 ----------------------------------------------------
|
||||
|
|
@ -142,14 +136,82 @@ REM ====================================================
|
|||
if "%DO_WIN%"=="1" (
|
||||
echo.
|
||||
echo ---^> [WIN] Baue Windows Single-File .exe...
|
||||
if exist "%PROJECT_ROOT%\dist\windows" rmdir /s /q "%PROJECT_ROOT%\dist\windows"
|
||||
call :BUILD_WIN_TARGET
|
||||
if errorlevel 1 (
|
||||
set "WIN_OK=0"
|
||||
set "ANY_FAILED=1"
|
||||
) else (
|
||||
set "WIN_OK=1"
|
||||
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 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!
|
||||
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 ====================================================
|
||||
|
|
@ -158,14 +220,7 @@ 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 ====================================================
|
||||
|
|
@ -174,47 +229,34 @@ 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 "!WIN_OK!"=="1" if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
|
||||
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 "!UNIX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
|
||||
if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
|
||||
echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^)
|
||||
) else (
|
||||
echo [UNIX] FEHLGESCHLAGEN! ^(VM "%UNIX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||
echo [UNIX] FEHLGESCHLAGEN
|
||||
)
|
||||
)
|
||||
if "%DO_OSX%"=="1" (
|
||||
if "!OSX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\macos\%APP_NAME%" (
|
||||
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! ^(VM "%OSX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
|
||||
echo [OSX] FEHLGESCHLAGEN
|
||||
)
|
||||
)
|
||||
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
|
||||
|
|
@ -223,84 +265,6 @@ 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" (
|
||||
|
|
@ -309,18 +273,11 @@ 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%\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"
|
||||
)
|
||||
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"
|
||||
)
|
||||
exit /b 0
|
||||
|
||||
|
|
@ -365,25 +322,16 @@ 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 [ERROR] VBoxManage.exe nicht gefunden - Linux-VM-Build fehlgeschlagen!
|
||||
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe Linux-VM-Build.
|
||||
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
|
||||
)
|
||||
|
||||
|
|
@ -423,17 +371,13 @@ 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 -not -name '.venv' -exec rm -rf {} +"
|
||||
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 {} +"
|
||||
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% "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 .'"
|
||||
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 ."
|
||||
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Linux-Build in der VM fehlgeschlagen!
|
||||
|
|
@ -441,7 +385,9 @@ if errorlevel 1 (
|
|||
exit /b 1
|
||||
)
|
||||
|
||||
mkdir "%PROJECT_ROOT%\dist\linux" 2>nul
|
||||
if exist "%PROJECT_ROOT%\dist\linux" rmdir /s /q "%PROJECT_ROOT%\dist\linux"
|
||||
mkdir "%PROJECT_ROOT%\dist\linux"
|
||||
|
||||
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 (
|
||||
|
|
@ -449,10 +395,6 @@ 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...
|
||||
|
|
@ -464,14 +406,13 @@ exit /b 0
|
|||
:RUN_OSX_VM_BUILD
|
||||
call :FIND_VBOX
|
||||
if "!VBOX_MANAGE!"=="" (
|
||||
echo [ERROR] VBoxManage.exe nicht gefunden - macOS-VM-Build fehlgeschlagen!
|
||||
echo [SKIP] VBoxManage.exe nicht gefunden - ueberspringe macOS-VM-Build.
|
||||
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
|
||||
)
|
||||
|
||||
|
|
@ -511,35 +452,29 @@ 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 -not -name '.venv_build_macos' -exec rm -rf {} +"
|
||||
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 {} +"
|
||||
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% "/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 .'"
|
||||
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 ."
|
||||
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
|
||||
)
|
||||
|
||||
mkdir "%PROJECT_ROOT%\dist\macos" 2>nul
|
||||
if exist "%PROJECT_ROOT%\dist\macos" rmdir /s /q "%PROJECT_ROOT%\dist\macos"
|
||||
mkdir "%PROJECT_ROOT%\dist\macos"
|
||||
|
||||
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/%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/macos/%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=(0, 6, 0, 0),
|
||||
prodvers=(0, 6, 0, 0),
|
||||
filevers=(1, 0, 0, 0),
|
||||
prodvers=(1, 0, 0, 0),
|
||||
mask=0x3f,
|
||||
flags=0x0,
|
||||
OS=0x40004,
|
||||
|
|
@ -16,12 +16,12 @@ VSVersionInfo(
|
|||
[
|
||||
StringStruct('CompanyName', 'Kuro'),
|
||||
StringStruct('FileDescription', 'The Goth Cardgame Collection'),
|
||||
StringStruct('FileVersion', '0.6.0.0'),
|
||||
StringStruct('FileVersion', '1.0.0.0'),
|
||||
StringStruct('InternalName', 'TheGothCardgameCollection'),
|
||||
StringStruct('LegalCopyright', 'Copyright (C) 2026 Kuro'),
|
||||
StringStruct('OriginalFilename', 'TheGothCardgameCollection.exe'),
|
||||
StringStruct('ProductName', 'The Goth Cardgame Collection'),
|
||||
StringStruct('ProductVersion', '0.6.0-beta')
|
||||
StringStruct('ProductVersion', '1.0.0.0')
|
||||
]
|
||||
)
|
||||
]),
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -2,16 +2,17 @@
|
|||
# controller/app_context.py
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
__all__ = ["AppContext", "GothTopbar", "UnifiedStatsView", "format_compact_user_badge"]
|
||||
|
||||
|
||||
class AppContext:
|
||||
"""Schlanker Spiel-Kontext; Topbar, Einstellungen und Statistik laufen zentral."""
|
||||
"""Schlanker Spiel-Kontext; Topbar und Statistik laufen zentral über eigene Widgets."""
|
||||
|
||||
def __init__(self, controller, game_folder: str):
|
||||
self._ctrl = controller
|
||||
|
|
@ -38,9 +39,11 @@ class AppContext:
|
|||
|
||||
def open_settings(self, on_lang_refresh=None):
|
||||
GothDropdown.close_any_open_popup()
|
||||
self._ctrl.show_settings(
|
||||
in_game_overlay=True,
|
||||
on_ingame_lang_refresh=on_lang_refresh,
|
||||
AudioSettingsDialog.open(
|
||||
self.root,
|
||||
self.assets,
|
||||
self.sounds,
|
||||
on_toggle_lang=lambda: self.toggle_language(on_lang_refresh),
|
||||
)
|
||||
|
||||
def open_audio_settings(self):
|
||||
|
|
@ -51,6 +54,7 @@ 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,19 +1,12 @@
|
|||
# -*- 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 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.database import Database
|
||||
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:
|
||||
|
|
@ -24,58 +17,16 @@ class AppController:
|
|||
i18n.set_lang(Database.load_setting("language", "DE"))
|
||||
self.loader = GameLoader(root_dir)
|
||||
self.sounds = SoundManager(root_dir / "resources" / "sounds")
|
||||
self.online_session = OnlineSessionClient()
|
||||
self.is_online_mode: bool = False
|
||||
self.active_profile: dict | None = None
|
||||
self.active_profile = 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)
|
||||
if self.view is not None:
|
||||
self.view.title(t("app_title"))
|
||||
self.view.title(t("app_title"))
|
||||
if custom_refresh is not None:
|
||||
custom_refresh()
|
||||
elif self.active_profile:
|
||||
|
|
@ -83,134 +34,34 @@ class AppController:
|
|||
else:
|
||||
self.start()
|
||||
|
||||
def start(self, status_msg: str = "", is_error: bool = False, login_mode: str = "local"):
|
||||
def start(self):
|
||||
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,
|
||||
status_msg=status_msg,
|
||||
is_error=is_error,
|
||||
login_mode=login_mode,
|
||||
)
|
||||
self.view.show_login(profiles, preselect_name=last_prof)
|
||||
|
||||
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, first_user_db_dir: str | None = None):
|
||||
clean_name = name.strip()
|
||||
if not clean_name:
|
||||
def do_create_profile(self, name: str):
|
||||
if not name:
|
||||
return
|
||||
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)
|
||||
Database.save_setting("last_profile_name", name)
|
||||
self.active_profile = Database.get_or_create_profile(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 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
|
||||
last_prof = self.active_profile["name"] if self.active_profile else Database.load_setting("last_profile_name", "")
|
||||
self.active_profile = None
|
||||
self.view.show_login(
|
||||
Database.get_profiles(),
|
||||
preselect_name=last_prof,
|
||||
login_mode="online" if was_online else "local",
|
||||
)
|
||||
self.view.show_login(Database.get_profiles(), preselect_name=last_prof)
|
||||
|
||||
def get_locked_devils_game_folder(self) -> str | None:
|
||||
if not self.active_profile or self.is_online_mode:
|
||||
if not self.active_profile:
|
||||
return None
|
||||
pid = self.active_profile["id"]
|
||||
if Database.get_active_devils_bj_account(pid) is not None:
|
||||
|
|
@ -234,69 +85,26 @@ class AppController:
|
|||
self.launch_game(g)
|
||||
return
|
||||
|
||||
def show_main_menu(self, category: str | None = None):
|
||||
def show_main_menu(self):
|
||||
self.sounds.play_menu_music()
|
||||
if self.active_profile:
|
||||
pid = self.active_profile["id"]
|
||||
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
|
||||
|
||||
self.active_profile = Database.get_profile_by_id(pid)
|
||||
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.main_menu_view.show(
|
||||
self.active_profile, games, devils_resume_only=False, category=category
|
||||
)
|
||||
self.view.show_main_menu(self.active_profile, games, devils_resume_only=False)
|
||||
|
||||
def show_statistics(self):
|
||||
if self.has_active_devils_lock() or not self.active_profile:
|
||||
if self.has_active_devils_lock():
|
||||
return
|
||||
self.sounds.play_menu_music()
|
||||
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)
|
||||
if self.active_profile:
|
||||
self.active_profile = Database.get_profile_by_id(self.active_profile["id"])
|
||||
self.view.show_statistics(self.active_profile)
|
||||
|
||||
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.cards.card import Card
|
||||
from models.cards.deck import Deck
|
||||
from models.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.db.database import Database
|
||||
from models.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.
|
|
@ -1,348 +0,0 @@
|
|||
# -*- 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,76 +2,515 @@
|
|||
# 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 models.db.database import Database
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
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.shared_bases.luck_pouch_menu_base import LuckPouchMenuBase
|
||||
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
|
||||
|
||||
GAME_FOLDER_ID = "blackjack"
|
||||
|
||||
|
||||
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"
|
||||
class BlackjackMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self.bot_widget: BotSetupWidget | None = None
|
||||
self._photo_refs: list = []
|
||||
|
||||
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"
|
||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
||||
pid = self.ctx.profile["id"]
|
||||
|
||||
def _get_active_devils_account(self, pid: int):
|
||||
return Database.get_active_devils_bj_account(pid)
|
||||
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_accounts(self, pid: int):
|
||||
return Database.get_blackjack_accounts(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_account(self, acc_id: int):
|
||||
return Database.get_blackjack_account(acc_id)
|
||||
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 _create_account(self, pid: int, name: str):
|
||||
return Database.create_blackjack_account(pid, name)
|
||||
setting_key = f"last_bj_account_{pid}"
|
||||
accounts = Database.get_blackjack_accounts(pid)
|
||||
has_accounts = len(accounts) > 0
|
||||
|
||||
def _delete_account(self, acc_id: int):
|
||||
Database.delete_blackjack_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 _exchange_xp(self, pid: int, acc_id: int):
|
||||
return Database.exchange_xp_for_bj_gold(pid, acc_id)
|
||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
||||
acc_names = list(acc_by_name.keys())
|
||||
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
return BJ_VARIANTS
|
||||
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 _min_entry_for_variant(self, _v_key: str, _cfg: dict) -> int:
|
||||
return GOLD_MIN_TABLE_ENTRY
|
||||
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 _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
|
||||
return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
|
||||
def get_current_acc() -> dict | None:
|
||||
return acc_by_name.get(selected_name_var.get())
|
||||
|
||||
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 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 _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,
|
||||
)
|
||||
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()))
|
||||
|
|
@ -1,307 +0,0 @@
|
|||
# -*- 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']}")
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
# -*- 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
|
|
@ -1,244 +0,0 @@
|
|||
# -*- 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,42 +2,134 @@
|
|||
# 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_HEADING,
|
||||
FONT_SIZE_SMALL_MIN,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
OUTCOME_GIF_SIZE,
|
||||
SUBTLE_BORDER,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
|
||||
|
||||
|
||||
class BlackjackResultDialog(CasinoResultDialogBase):
|
||||
"""Gothic-Showdown-Overlay für Blackjack auf Basis von CasinoResultDialogBase."""
|
||||
class BlackjackResultDialog(tk.Canvas):
|
||||
"""
|
||||
Rahmenloses Gothic-Showdown-Overlay für Blackjack:
|
||||
Hintergrund background_vertical.jpg + box_big.png, Gewinner-Sitze in box_gold_smal.png,
|
||||
übrige Sitze in box_small_purple.png und kompakte Kartenfächer für 768p-Bildschirme.
|
||||
"""
|
||||
|
||||
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
|
||||
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", []))
|
||||
|
||||
has_gif = result_data.get("player_won") is not None
|
||||
extra_lines = len(result_data.get("other_gains", []))
|
||||
dlg_w = max(560, min(830, cols * 250 + 64))
|
||||
dlg_h = (
|
||||
58
|
||||
(116 if has_gif else 54)
|
||||
+ (48 if result_data.get("reason_text") else 8)
|
||||
+ (rows * 140 + 28 if rows else 0)
|
||||
+ 92 + min(2, extra_lines) * 20
|
||||
+ (24 if result_data.get("new_level_title") else 0)
|
||||
+ 62
|
||||
)
|
||||
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||
# Sicherstellen, dass das Dialogfenster auch auf 768p-Displays komplett sichtbar bleibt
|
||||
try:
|
||||
max_h = max(460, parent.winfo_toplevel().winfo_height() - 74)
|
||||
dlg_h = min(dlg_h, max_h)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||
super().__init__(
|
||||
parent,
|
||||
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._gif_job: str | None = None
|
||||
self._gif_item: int | None = None
|
||||
self._photo_refs: list = []
|
||||
|
||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self.tk.call("raise", self._w)
|
||||
self._build_scene()
|
||||
|
||||
def _build_scene(self):
|
||||
w, h = self._dlg_w, self._dlg_h
|
||||
cx = w // 2
|
||||
self._photo_refs.clear()
|
||||
|
||||
# 1. Hintergrund + äußerer Zierrahmen box_big.png
|
||||
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 = 20
|
||||
|
||||
# 2. Win/Lose GIF + Headline
|
||||
p_won = self.data.get("player_won")
|
||||
gif_key = "win_gif" if p_won is True else ("lose_gif" if p_won is False else "")
|
||||
frames = self.assets.get_gif_frames(gif_key, size=(145, 80)) if gif_key else []
|
||||
if frames:
|
||||
self._gif_item = self.create_image(cx, cur_y + 40, image=frames[0], anchor="center")
|
||||
cur_y += 84
|
||||
if len(frames) > 1:
|
||||
self._animate_gif(frames, 0)
|
||||
|
||||
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() + 6
|
||||
|
||||
# 3. Begründung im schmalen Gold-Doppelrahmen
|
||||
reason_txt = self.data.get("reason_text", "")
|
||||
if reason_txt:
|
||||
r_ph = self.assets.get_goth_text_photo(
|
||||
|
|
@ -53,78 +145,178 @@ class BlackjackResultDialog(CasinoResultDialogBase):
|
|||
self.create_image(cx, rb_cy, image=r_ph, anchor="center")
|
||||
cur_y += rb_h + 8
|
||||
|
||||
# 4. Showdown-Karten aller Teilnehmer
|
||||
hands_list = self.data.get("showdown_hands", [])
|
||||
if not hands_list:
|
||||
return cur_y
|
||||
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
|
||||
|
||||
sec_ph = self.assets.get_goth_text_photo(
|
||||
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
|
||||
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")
|
||||
|
||||
# Überlappender Mini-Kartenfächer
|
||||
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
|
||||
|
||||
# 5. Gold- & XP-Abrechnung
|
||||
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,
|
||||
)
|
||||
self._photo_refs.append(sec_ph)
|
||||
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
|
||||
cur_y += 22
|
||||
self._photo_refs.append(xp_ph)
|
||||
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
|
||||
|
||||
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
|
||||
# 6. Untere Buttons
|
||||
btn_norm = self.assets.raw_btn_default
|
||||
btn_purp = self.assets.raw_btn_purple
|
||||
btn_fire = self.assets.raw_btn_fire or btn_purp
|
||||
|
||||
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)
|
||||
btn_y = h - 34
|
||||
can_next = self.data.get("can_continue", True)
|
||||
can_menu = self.data.get("can_leave_menu", True)
|
||||
|
||||
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)
|
||||
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"
|
||||
)
|
||||
o_ph = self.assets.get_goth_text_photo(
|
||||
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
|
||||
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._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(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"
|
||||
)
|
||||
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_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"
|
||||
)
|
||||
self._photo_refs.append(rk_ph)
|
||||
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
|
||||
self.create_window(cx, btn_y, window=b_menu, anchor="center")
|
||||
|
||||
return cur_y + rows * (seat_h + 6) + 6
|
||||
def _animate_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._animate_gif, frames, (idx + 1) % len(frames))
|
||||
|
||||
def close_dialog(self):
|
||||
if self._gif_job:
|
||||
try:
|
||||
self.after_cancel(self._gif_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._gif_job = None
|
||||
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()
|
||||
|
|
@ -1,265 +0,0 @@
|
|||
# -*- 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),
|
||||
)
|
||||
|
|
@ -1,344 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
# -*- 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)
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
# -*- 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]
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
# -*- 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()
|
||||
|
|
@ -1,331 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,303 +0,0 @@
|
|||
# -*- 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()))
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
# -*- 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")
|
||||
|
|
@ -1,323 +0,0 @@
|
|||
# -*- 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),
|
||||
)
|
||||
|
|
@ -1,264 +0,0 @@
|
|||
# -*- 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)
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,166 +0,0 @@
|
|||
# -*- 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,
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
# -*- 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()
|
||||
|
|
@ -1,310 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,293 +0,0 @@
|
|||
# -*- 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()))
|
||||
|
|
@ -1,178 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,314 +0,0 @@
|
|||
# -*- 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.cards.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.cards.deck import Deck
|
||||
from models.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.cards.card import Card
|
||||
from models.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.db.database import Database
|
||||
from models.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.
|
|
@ -1,393 +0,0 @@
|
|||
# -*- 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.buttons.image_button import ImageButton
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
HAND_REFERENCE_EXAMPLES = (
|
||||
(1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))),
|
||||
|
|
|
|||
|
|
@ -2,9 +2,26 @@
|
|||
# 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 models.db.database import Database
|
||||
from view.widgets.menu_body_canvas import MenuBodyCanvas
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
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,
|
||||
|
|
@ -12,71 +29,491 @@ from resources.code_res.game_constants import (
|
|||
XP_TO_GOLD_AMOUNT,
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.shared_bases.luck_pouch_menu_base import LuckPouchMenuBase
|
||||
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
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
|
||||
|
||||
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"
|
||||
class PokerMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self.bot_widget: BotSetupWidget | None = None
|
||||
self._photo_refs: list = []
|
||||
|
||||
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"
|
||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
||||
pid = self.ctx.profile["id"]
|
||||
|
||||
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),
|
||||
}
|
||||
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 _get_active_devils_account(self, pid: int):
|
||||
return Database.get_active_devils_pk_account(pid)
|
||||
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_accounts(self, pid: int):
|
||||
return Database.get_poker_accounts(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_account(self, acc_id: int):
|
||||
return Database.get_poker_account(acc_id)
|
||||
setting_key = f"last_pk_account_{pid}"
|
||||
accounts = Database.get_poker_accounts(pid)
|
||||
has_accounts = len(accounts) > 0
|
||||
|
||||
def _create_account(self, pid: int, name: str):
|
||||
return Database.create_poker_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_poker_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_pk_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 PK_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 cfg["min_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("pk_variant_desc", cfg["sb"], cfg["bb"], 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_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)
|
||||
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 _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,
|
||||
)
|
||||
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()))
|
||||
|
|
@ -1,129 +1,204 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_result_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
from models.cards.card import Card
|
||||
import tkinter as tk
|
||||
from models.card import Card
|
||||
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_SMALL_MIN,
|
||||
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
|
||||
FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.shared_bases.casino_result_dialog_base import CasinoResultDialogBase
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
POPUP_HOLE_CARD_SIZE = (46, 68)
|
||||
POPUP_GIF_SIZE = (145, 80)
|
||||
POPUP_HOLE_CARD_SIZE = (48, 70)
|
||||
POPUP_BOARD_CARD_SIZE = (44, 64)
|
||||
|
||||
|
||||
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):
|
||||
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", []))
|
||||
|
||||
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
|
||||
class PokerResultDialog(tk.Frame):
|
||||
"""Ergebnis-Overlay im einheitlichen BlackjackResultDialog-Stil inkl. Kartenbild-Showdown."""
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
assets,
|
||||
sounds,
|
||||
result_data: dict,
|
||||
on_next_round,
|
||||
on_back_to_menu,
|
||||
):
|
||||
super().__init__(
|
||||
parent, bg=MODAL_BG, padx=26, pady=18,
|
||||
highlightthickness=2, highlightbackground=ACCENT_GOTH
|
||||
)
|
||||
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
|
||||
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._gif_job = None
|
||||
self._card_photos = []
|
||||
|
||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self.lift()
|
||||
self._build()
|
||||
|
||||
def _build(self):
|
||||
self.gif_lbl = tk.Label(self, bg=MODAL_BG, bd=0)
|
||||
self.gif_lbl.pack(pady=(0, 4))
|
||||
|
||||
p_won = self.data.get("player_won")
|
||||
if p_won is True:
|
||||
self._start_gif("win_gif")
|
||||
elif p_won is False:
|
||||
self._start_gif("lose_gif")
|
||||
|
||||
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))
|
||||
|
||||
# --- Karten-Aufdeckung: Gemeinschaftskarten + alle Sitze mit Kartenbildern ---
|
||||
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))
|
||||
|
||||
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
|
||||
board_raw = self.data.get("board_cards", [])
|
||||
if board_raw:
|
||||
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")
|
||||
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))
|
||||
|
||||
lbl_ph = self.assets.get_goth_text_photo(
|
||||
f"{t('pk_board_title')}:", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, align="left"
|
||||
)
|
||||
self._photo_refs.append(lbl_ph)
|
||||
|
||||
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)
|
||||
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._photo_refs.append(ph)
|
||||
b_photos.append(ph)
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
|
||||
|
||||
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
|
||||
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
|
||||
|
||||
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
|
||||
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
|
||||
seats_row.pack()
|
||||
|
||||
cur_y += b_box_h + 8
|
||||
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
|
||||
is_win = entry["is_winner"]
|
||||
folded = entry["folded"]
|
||||
|
||||
seats = self.data.get("seat_showdown", [])
|
||||
if not seats:
|
||||
return cur_y
|
||||
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
|
||||
)
|
||||
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
|
||||
|
||||
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
|
||||
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()
|
||||
|
||||
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)
|
||||
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)
|
||||
if ph:
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=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
|
||||
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()
|
||||
|
||||
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")
|
||||
# --- Gewinn / Verlust & XP Box (identisch zu BlackjackResultDialog) ---
|
||||
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))
|
||||
|
||||
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")
|
||||
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
|
||||
|
||||
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
|
||||
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
|
||||
|
||||
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")
|
||||
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)
|
||||
|
||||
return cur_y + rows * (seat_h + 6) + 6
|
||||
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
|
||||
|
||||
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)
|
||||
|
||||
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))
|
||||
|
||||
# --- Buttons ---
|
||||
btn_row = tk.Frame(self, bg=MODAL_BG)
|
||||
btn_row.pack(fill="x", pady=(4, 0))
|
||||
|
||||
if self.data.get("can_continue", True):
|
||||
ImageButton(
|
||||
btn_row, t("bj_popup_next_round_btn"),
|
||||
self.assets.raw_btn, self.assets.raw_btn_active,
|
||||
self._handle_next, sound_mgr=self.sounds, width=200, height=40, font=("Helvetica", 10, "bold")
|
||||
).pack(side="left", padx=(0, 10))
|
||||
|
||||
if self.data.get("can_leave_menu", True):
|
||||
ImageButton(
|
||||
btn_row, t("bj_popup_to_menu_btn"),
|
||||
self.assets.raw_sel, self.assets.raw_sel_active,
|
||||
self._handle_menu, sound_mgr=self.sounds, width=170, height=40, font=("Helvetica", 10, "bold")
|
||||
).pack(side="right")
|
||||
|
||||
def _start_gif(self, key: str):
|
||||
frames = self.assets.get_gif_frames(key, size=POPUP_GIF_SIZE)
|
||||
if not frames:
|
||||
return
|
||||
|
||||
def _step(idx=0):
|
||||
if not self.gif_lbl.winfo_exists():
|
||||
return
|
||||
self.gif_lbl.configure(image=frames[idx])
|
||||
self._gif_job = self.after(90, _step, (idx + 1) % len(frames))
|
||||
|
||||
_step(0)
|
||||
|
||||
def close_dialog(self):
|
||||
if self._gif_job:
|
||||
try:
|
||||
self.after_cancel(self._gif_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._gif_job = None
|
||||
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()
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
# -*- 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
|
|
@ -1,270 +0,0 @@
|
|||
# -*- 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.
|
|
@ -0,0 +1,172 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,352 +0,0 @@
|
|||
# -*- 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,266 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/cards/card_hover_zoom.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
from games.solitaire.base.cards.solitaire_card import SolitaireCard
|
||||
from resources.code_res.game_constants import ACCENT_GOLD, BORDER_COLOR
|
||||
|
||||
|
||||
class CardHoverZoom:
|
||||
"""
|
||||
Subtile Karten-Hervorhebung im Stil von Microsoft Solitaire:
|
||||
Hebt die Karte unter dem Mauszeiger leicht vergrößert und nach oben versetzt hervor,
|
||||
behält aber strikt die Stapel-Reihenfolge (Z-Order) bei, sodass alle Karten, die in
|
||||
einer Kaskade auf ihr liegen, weiterhin vollständig sichtbar bleiben.
|
||||
"""
|
||||
|
||||
ZOOM_FACTOR = 1.12 # Dezente Verbreitung/Vergrößerung unter den Folgekarten
|
||||
PEEK_UP_PX = 8 # Leichtes Anheben nach oben, damit Wert & Symbol frei herausschauen
|
||||
HOVER_DELAY_MS = 45
|
||||
TAG = "sol_hover_zoom"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
root: tk.Misc,
|
||||
canvas: tk.Canvas,
|
||||
assets,
|
||||
probe_fn: Callable[[int, int], dict | tuple | None],
|
||||
can_show_fn: Callable[[], bool] | None = None,
|
||||
):
|
||||
self._root = root
|
||||
self._canvas = canvas
|
||||
self._assets = assets
|
||||
self._probe_fn = probe_fn
|
||||
self._can_show_fn = can_show_fn
|
||||
|
||||
self._after_job: str | None = None
|
||||
self._active_target_id: tuple | None = None
|
||||
self._pending_info: dict | None = None
|
||||
self._last_pointer_xy: tuple[int, int] | None = None
|
||||
self._zoom_photo_ref = None
|
||||
|
||||
self._canvas.bind("<Motion>", self._on_motion, add="+")
|
||||
self._canvas.bind("<Leave>", self._on_leave, add="+")
|
||||
self._canvas.bind("<ButtonPress-1>", self._on_press_clear, add="+")
|
||||
self._canvas.bind("<ButtonPress-3>", self._on_press_clear, add="+")
|
||||
|
||||
@staticmethod
|
||||
def _normalize_probe(raw: dict | tuple | None) -> dict | None:
|
||||
if raw is None:
|
||||
return None
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, tuple) and len(raw) >= 4:
|
||||
card, cx, cy, base_sz = raw[:4]
|
||||
under_tag = raw[4] if len(raw) >= 5 else None
|
||||
return {
|
||||
"card": card,
|
||||
"x": cx,
|
||||
"y": cy,
|
||||
"size": base_sz,
|
||||
"under_tag": under_tag,
|
||||
}
|
||||
return None
|
||||
|
||||
def cancel(self):
|
||||
"""Räumt Timer und aktive Hervorhebung restlos ab."""
|
||||
self._cancel_timer()
|
||||
self._clear_drawn()
|
||||
self._active_target_id = None
|
||||
self._pending_info = None
|
||||
|
||||
def refresh_after_redraw(self):
|
||||
"""Stellt nach einem Hintergrund-Redraw (z. B. Uhr-Tick) die Hervorhebung sauber wieder her."""
|
||||
if self._active_target_id is None or self._last_pointer_xy is None:
|
||||
return
|
||||
if self._can_show_fn is not None and not self._can_show_fn():
|
||||
self.cancel()
|
||||
return
|
||||
px, py = self._last_pointer_xy
|
||||
info = self._normalize_probe(self._probe_fn(px, py))
|
||||
if info is None:
|
||||
self.cancel()
|
||||
return
|
||||
card: SolitaireCard = info["card"]
|
||||
target_id = (
|
||||
card.suit,
|
||||
card.rank,
|
||||
card.deck_id,
|
||||
info["x"],
|
||||
info["y"],
|
||||
info.get("under_tag"),
|
||||
)
|
||||
if target_id == self._active_target_id:
|
||||
self._render_zoom(info)
|
||||
else:
|
||||
self.cancel()
|
||||
|
||||
def _cancel_timer(self):
|
||||
if self._after_job is not None:
|
||||
try:
|
||||
self._root.after_cancel(self._after_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._after_job = None
|
||||
|
||||
def _clear_drawn(self):
|
||||
try:
|
||||
if self._canvas.winfo_exists():
|
||||
self._canvas.delete(self.TAG)
|
||||
except Exception:
|
||||
pass
|
||||
self._zoom_photo_ref = None
|
||||
|
||||
def _on_leave(self, _event=None):
|
||||
self._last_pointer_xy = None
|
||||
self.cancel()
|
||||
|
||||
def _on_press_clear(self, _event=None):
|
||||
self.cancel()
|
||||
|
||||
def _on_motion(self, event):
|
||||
# Während Drag & Drop niemals einblenden
|
||||
if event.state & 0x0100:
|
||||
self.cancel()
|
||||
return
|
||||
|
||||
self._last_pointer_xy = (event.x, event.y)
|
||||
|
||||
if self._can_show_fn is not None and not self._can_show_fn():
|
||||
self.cancel()
|
||||
return
|
||||
|
||||
info = self._normalize_probe(self._probe_fn(event.x, event.y))
|
||||
if info is None:
|
||||
self.cancel()
|
||||
return
|
||||
|
||||
card: SolitaireCard = info["card"]
|
||||
if not card.face_up:
|
||||
self.cancel()
|
||||
return
|
||||
|
||||
target_id = (
|
||||
card.suit,
|
||||
card.rank,
|
||||
card.deck_id,
|
||||
info["x"],
|
||||
info["y"],
|
||||
info.get("under_tag"),
|
||||
)
|
||||
if target_id == self._active_target_id:
|
||||
return
|
||||
|
||||
self._cancel_timer()
|
||||
self._clear_drawn()
|
||||
self._active_target_id = None
|
||||
self._pending_info = info
|
||||
try:
|
||||
self._after_job = self._root.after(self.HOVER_DELAY_MS, self._show_pending)
|
||||
except Exception:
|
||||
self._after_job = None
|
||||
|
||||
def _show_pending(self):
|
||||
self._after_job = None
|
||||
if self._pending_info is None:
|
||||
return
|
||||
if self._can_show_fn is not None and not self._can_show_fn():
|
||||
self._pending_info = None
|
||||
return
|
||||
if not self._canvas.winfo_exists():
|
||||
return
|
||||
|
||||
info = self._pending_info
|
||||
card: SolitaireCard = info["card"]
|
||||
self._active_target_id = (
|
||||
card.suit,
|
||||
card.rank,
|
||||
card.deck_id,
|
||||
info["x"],
|
||||
info["y"],
|
||||
info.get("under_tag"),
|
||||
)
|
||||
self._render_zoom(info)
|
||||
|
||||
def _render_zoom(self, info: dict):
|
||||
self._clear_drawn()
|
||||
card: SolitaireCard = info["card"]
|
||||
card_x: int = info["x"]
|
||||
card_y: int = info["y"]
|
||||
bw, bh = info["size"]
|
||||
under_tag: str | None = info.get("under_tag")
|
||||
|
||||
if bw < 24 or bh < 32:
|
||||
return
|
||||
|
||||
zw = max(bw + 8, int(round(bw * self.ZOOM_FACTOR)))
|
||||
zh = max(bh + 12, int(round(bh * self.ZOOM_FACTOR)))
|
||||
|
||||
cw = max(1, self._canvas.winfo_width())
|
||||
ch = max(1, self._canvas.winfo_height())
|
||||
|
||||
# Horizontal mittig auf der Spalte, vertikal leicht nach oben gelupft ("Peek"),
|
||||
# damit Rang & Farbe über den aufliegenden Folgekarten klar hervortreten
|
||||
zx = card_x - (zw - bw) // 2
|
||||
if under_tag:
|
||||
zy = card_y - self.PEEK_UP_PX - (zh - bh) // 3
|
||||
else:
|
||||
zy = card_y - (zh - bh) // 2
|
||||
|
||||
pad = 6
|
||||
zx = max(pad, min(max(pad, cw - zw - pad), zx))
|
||||
zy = max(pad, min(max(pad, ch - zh - pad), zy))
|
||||
|
||||
photo = self._assets.get_card_photo(card.filename, size=(zw, zh))
|
||||
if photo is None:
|
||||
return
|
||||
self._zoom_photo_ref = photo
|
||||
|
||||
# 1. Dezenter dunkler Schlagschatten
|
||||
self._canvas.create_rectangle(
|
||||
zx + 4,
|
||||
zy + 5,
|
||||
zx + zw + 4,
|
||||
zy + zh + 5,
|
||||
fill="#07050c",
|
||||
outline="",
|
||||
tags=(self.TAG,),
|
||||
)
|
||||
# 2. Leicht vergrößerte Karte
|
||||
self._canvas.create_image(
|
||||
zx,
|
||||
zy,
|
||||
image=photo,
|
||||
anchor="nw",
|
||||
tags=(self.TAG,),
|
||||
)
|
||||
# 3. Goldener Hervorhebungs-Rahmen
|
||||
self._canvas.create_rectangle(
|
||||
zx - 2,
|
||||
zy - 2,
|
||||
zx + zw + 2,
|
||||
zy + zh + 2,
|
||||
outline=ACCENT_GOLD,
|
||||
width=2,
|
||||
tags=(self.TAG,),
|
||||
)
|
||||
self._canvas.create_rectangle(
|
||||
zx - 3,
|
||||
zy - 3,
|
||||
zx + zw + 3,
|
||||
zy + zh + 3,
|
||||
outline=BORDER_COLOR,
|
||||
width=1,
|
||||
tags=(self.TAG,),
|
||||
)
|
||||
|
||||
# Entscheidend: Liegen in der Kaskade weitere Karten auf dieser Karte,
|
||||
# sortieren wir die Hervorhebung direkt UNTER die nächste Karte ein!
|
||||
if under_tag and self._canvas.find_withtag(under_tag):
|
||||
try:
|
||||
self._canvas.tag_lower(self.TAG, under_tag)
|
||||
except tk.TclError:
|
||||
pass
|
||||
|
|
@ -1,253 +0,0 @@
|
|||
# -*- 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()
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
# -*- 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
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/widgets/bars/goth_desktop_bottombar.py
|
||||
# games/solitaire/base/solitaire_bottom_bar.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
|
@ -12,31 +12,31 @@ from resources.code_res.game_constants import (
|
|||
FONT_SIZE_SMALL_MIN,
|
||||
UI_ACCENT_AMETHYST,
|
||||
)
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088)
|
||||
BG_SAFE_BOTTOM_RATIO = getattr(gc, "BG_SAFE_BOTTOM_RATIO", 0.095)
|
||||
|
||||
|
||||
class DesktopGothBottombar(tk.Canvas):
|
||||
"""Desktop-Fußleiste innerhalb der unteren Safe-Area des Spinnennetz-Rahmens."""
|
||||
class SolitaireBottomBar(tk.Canvas):
|
||||
"""
|
||||
Gerahmte HUD- & Aktionsleiste innerhalb der unteren Safe-Area von background.jpg.
|
||||
Unterstützt kompakte Pipe-Trenner ('|') sowie zwei optionale Overflow-Erweiterungsflächen
|
||||
links (für Text-Segmente mit Präfix '~') und rechts (für sekundäre Aktions-Buttons),
|
||||
die automatisch nur dann eingeblendet werden, wenn der Platz in der Hauptleiste eng wird.
|
||||
"""
|
||||
|
||||
CONTENT_H = 48
|
||||
SUB_TOP_GAP = 3
|
||||
SUB_BAR_H = 38
|
||||
MIN_BOTTOM_INSET = 56
|
||||
|
||||
HUD_TEXT_X_OFFSET = 0
|
||||
HUD_TEXT_Y_OFFSET = 6
|
||||
# Fein-Offsets für den linken HUD-Textblock ("Punkte: 0 | Züge: 0 | ...")
|
||||
HUD_TEXT_X_OFFSET = 0 # Positiv = weiter nach rechts zur Mitte, Negativ = näher an den linken Rahmen
|
||||
HUD_TEXT_Y_OFFSET = 6 # Optische Vertikalzentrierung im Goldrahmen
|
||||
|
||||
def __init__(self, parent, controller_bar):
|
||||
self._bar = controller_bar
|
||||
self.ctx = controller_bar.ctx
|
||||
self.assets = controller_bar.assets
|
||||
self.hud_var = controller_bar.hud_var
|
||||
self.status_var = controller_bar.status_var
|
||||
|
||||
root_h = max(720, self.ctx.root.winfo_height())
|
||||
def __init__(self, parent, ctx, hud_var: tk.StringVar, status_var: tk.StringVar):
|
||||
root_h = max(720, ctx.root.winfo_height())
|
||||
self._bottom_inset = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO))
|
||||
init_h = self.CONTENT_H + self._bottom_inset
|
||||
|
||||
|
|
@ -47,6 +47,12 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
bd=0,
|
||||
highlightthickness=0,
|
||||
)
|
||||
self.ctx = ctx
|
||||
self.assets = ctx.assets
|
||||
self.hud_var = hud_var
|
||||
self.status_var = status_var
|
||||
|
||||
self._buttons: list[ImageButton] = []
|
||||
self._bg_ph: ImageTk.PhotoImage | None = None
|
||||
self._frame_ph: ImageTk.PhotoImage | None = None
|
||||
self._sub_left_frame_ph: ImageTk.PhotoImage | None = None
|
||||
|
|
@ -54,18 +60,48 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
self._txt_refs: list[ImageTk.PhotoImage] = []
|
||||
self._last_btn_split: tuple[tuple[int, ...], tuple[int, ...]] | None = None
|
||||
|
||||
self.hud_var.trace_add("write", lambda *_: self.refresh_texts())
|
||||
self.status_var.trace_add("write", lambda *_: self.refresh_texts())
|
||||
self.bind("<Configure>", self._on_configure)
|
||||
|
||||
@property
|
||||
def desired_height(self) -> int:
|
||||
root_h = max(600, self.ctx.root.winfo_height())
|
||||
self._bottom_inset = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO))
|
||||
return self.CONTENT_H + self._bottom_inset
|
||||
def set_buttons(
|
||||
self,
|
||||
buttons: list[ImageButton],
|
||||
overflow_buttons: list[ImageButton] | None = None,
|
||||
):
|
||||
"""
|
||||
Setzt die aktiven Leisten-Buttons und räumt alte Button-Widgets sauber ab.
|
||||
Buttons in `overflow_buttons` (oder mit Attribut `can_overflow=True`) bleiben
|
||||
solange möglich oben in der Hauptleiste und weichen bei Platzmangel automatisch
|
||||
rechtsbündig in die untere rechte Erweiterungsfläche aus.
|
||||
"""
|
||||
primary_list = list(buttons)
|
||||
extra_list = list(overflow_buttons) if overflow_buttons else []
|
||||
for b in extra_list:
|
||||
setattr(b, "can_overflow", True)
|
||||
|
||||
combined = primary_list + extra_list
|
||||
keep_ids = {id(b) for b in combined}
|
||||
|
||||
for old_b in self._buttons:
|
||||
if id(old_b) not in keep_ids:
|
||||
try:
|
||||
if old_b.winfo_exists():
|
||||
old_b.place_forget()
|
||||
old_b.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._buttons = combined
|
||||
self._last_btn_split = None
|
||||
self.relayout()
|
||||
self.after(20, self.relayout)
|
||||
|
||||
def relayout(self):
|
||||
if not self.winfo_exists():
|
||||
return
|
||||
w, h = self.winfo_width(), self.winfo_height()
|
||||
w = self.winfo_width()
|
||||
h = self.winfo_height()
|
||||
if w >= 120 and h >= 40:
|
||||
self._slice_bg(w, h)
|
||||
self._layout(w, h)
|
||||
|
|
@ -97,23 +133,40 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
self.tag_lower("bb_bg")
|
||||
|
||||
def _on_configure(self, event):
|
||||
if event.widget is not self or self._bar._is_compact:
|
||||
if event.widget is not self:
|
||||
return
|
||||
w, h = max(1, event.width), max(1, event.height)
|
||||
if w < 120:
|
||||
return
|
||||
|
||||
root_h = max(600, self.ctx.root.winfo_height())
|
||||
new_bot = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO))
|
||||
if new_bot != self._bottom_inset:
|
||||
self._bottom_inset = new_bot
|
||||
h = self.CONTENT_H + self._bottom_inset
|
||||
self.configure(height=h)
|
||||
|
||||
self._slice_bg(w, h)
|
||||
self._layout(w, h)
|
||||
|
||||
def _render_seg_photo(self, txt: str) -> ImageTk.PhotoImage:
|
||||
# Dynamische Timer-Segmente (z. B. 00:12) nicht dauerhaft im Text-Cache ablegen
|
||||
if ":" in txt and any(ch.isdigit() for ch in txt) and "'" not in txt:
|
||||
pil_seg = self.assets.render_goth_text_pil(
|
||||
txt,
|
||||
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
uncached=True,
|
||||
)
|
||||
try:
|
||||
pil_seg = self.assets.render_goth_text_pil(
|
||||
txt,
|
||||
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
uncached=True,
|
||||
)
|
||||
except TypeError:
|
||||
pil_seg = self.assets.render_goth_text_pil(
|
||||
txt,
|
||||
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="left",
|
||||
)
|
||||
return ImageTk.PhotoImage(pil_seg)
|
||||
|
||||
return self.assets.get_goth_text_photo(
|
||||
|
|
@ -128,7 +181,10 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
raw_parts = [p.strip() for p in raw_hud.split("|") if p.strip()]
|
||||
|
||||
pipe_ph = self.assets.get_goth_text_photo(
|
||||
"|", size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="center"
|
||||
"|",
|
||||
size_px=FONT_SIZE_SMALL_MIN + 1,
|
||||
color=FONT_COLOR_HEADING_SUB,
|
||||
align="center",
|
||||
)
|
||||
pipe_step = pipe_ph.width() + 12
|
||||
|
||||
|
|
@ -174,23 +230,27 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
top_segs = list(seg_items)
|
||||
sub_segs: list[dict] = []
|
||||
|
||||
alive_btns = [b for b in self._bar._buttons if b.winfo_exists()]
|
||||
alive_btns = [b for b in self._buttons if b.winfo_exists()]
|
||||
top_btns = list(alive_btns)
|
||||
sub_btns: list[ImageButton] = []
|
||||
|
||||
def fits_main() -> bool:
|
||||
sw = self._calc_segs_width(top_segs, pipe_step)
|
||||
bw = self._calc_btns_width(top_btns)
|
||||
return ((sw + min_mid_gap + bw) if (sw > 0 and bw > 0) else (sw + bw)) <= avail_main_w
|
||||
if sw > 0 and bw > 0:
|
||||
return (sw + min_mid_gap + bw) <= avail_main_w
|
||||
return (sw + bw) <= avail_main_w
|
||||
|
||||
guard = 0
|
||||
while not fits_main() and guard < 24:
|
||||
guard += 1
|
||||
moved = False
|
||||
|
||||
for idx in range(len(top_btns) - 1, -1, -1):
|
||||
cand = top_btns[idx]
|
||||
if getattr(cand, "can_overflow", False):
|
||||
if self._calc_btns_width([cand] + sub_btns) <= avail_right_wing or not sub_btns:
|
||||
test_sub = [cand] + sub_btns
|
||||
if self._calc_btns_width(test_sub) <= avail_right_wing or not sub_btns:
|
||||
sub_btns.insert(0, top_btns.pop(idx))
|
||||
moved = True
|
||||
break
|
||||
|
|
@ -200,7 +260,8 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
for idx in range(len(top_segs) - 1, 0, -1):
|
||||
cand_s = top_segs[idx]
|
||||
if cand_s["can_overflow"]:
|
||||
if self._calc_segs_width([cand_s] + sub_segs, pipe_step) <= avail_left_wing or not sub_segs:
|
||||
test_sub_s = [cand_s] + sub_segs
|
||||
if self._calc_segs_width(test_sub_s, pipe_step) <= avail_left_wing or not sub_segs:
|
||||
sub_segs.insert(0, top_segs.pop(idx))
|
||||
moved = True
|
||||
break
|
||||
|
|
@ -222,7 +283,10 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
return top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step
|
||||
|
||||
def _get_bar_box_photo(self, box_key: str, w: int, h: int, scale: float = 0.80):
|
||||
return self.assets.get_box_photo(box_key, (w, h), border_scale=scale)
|
||||
try:
|
||||
return self.assets.get_box_photo(box_key, (w, h), border_scale=scale)
|
||||
except TypeError:
|
||||
return self.assets.get_box_photo(box_key, (w, h))
|
||||
|
||||
def refresh_texts(self):
|
||||
if not self.winfo_exists() or self.winfo_width() < 120:
|
||||
|
|
@ -253,7 +317,8 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
self.delete("bb_txt")
|
||||
self.delete("bb_sub_frame")
|
||||
self._txt_refs.clear()
|
||||
self._sub_left_frame_ph = self._sub_right_frame_ph = None
|
||||
self._sub_left_frame_ph = None
|
||||
self._sub_right_frame_ph = None
|
||||
|
||||
top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step = self._compute_partition(w)
|
||||
self._txt_refs.append(pipe_ph)
|
||||
|
|
@ -265,16 +330,19 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
cy_sub = sub_top + self.SUB_BAR_H // 2
|
||||
txt_cy_sub = cy_sub + self.HUD_TEXT_Y_OFFSET
|
||||
|
||||
# 1. Hauptleisten-Buttons (oben rechts)
|
||||
rx_main = w - side_inset - 16
|
||||
if place_buttons:
|
||||
for btn in reversed(top_btns):
|
||||
bw, bh = btn.pixel_width, btn.pixel_height
|
||||
bw = btn.pixel_width
|
||||
bh = btn.pixel_height
|
||||
btn.place(x=rx_main - bw, y=cy_main - bh // 2, width=bw, height=bh)
|
||||
tk.Widget.tkraise(btn)
|
||||
rx_main -= (bw + 6)
|
||||
else:
|
||||
rx_main -= self._calc_btns_width(top_btns)
|
||||
|
||||
# 2. Rechte Erweiterungsfläche (nur sichtbar, wenn Buttons nach unten ausgelagert wurden)
|
||||
if sub_btns:
|
||||
sub_btns_w = self._calc_btns_width(sub_btns)
|
||||
r_box_w = sub_btns_w + 26
|
||||
|
|
@ -282,12 +350,25 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
r_box_cx = r_box_right - r_box_w // 2
|
||||
|
||||
self.create_rectangle(
|
||||
r_box_right - r_box_w + 4, sub_top + 4, r_box_right - 4, sub_top + self.SUB_BAR_H - 4,
|
||||
fill="#100d17", outline="", tags="bb_sub_frame",
|
||||
r_box_right - r_box_w + 4,
|
||||
sub_top + 4,
|
||||
r_box_right - 4,
|
||||
sub_top + self.SUB_BAR_H - 4,
|
||||
fill="#100d17",
|
||||
outline="",
|
||||
tags="bb_sub_frame",
|
||||
)
|
||||
self._sub_right_frame_ph = self._get_bar_box_photo(
|
||||
"box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72
|
||||
)
|
||||
self._sub_right_frame_ph = self._get_bar_box_photo("box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72)
|
||||
if self._sub_right_frame_ph:
|
||||
self.create_image(r_box_cx, cy_sub, image=self._sub_right_frame_ph, anchor="center", tags="bb_sub_frame")
|
||||
self.create_image(
|
||||
r_box_cx,
|
||||
cy_sub,
|
||||
image=self._sub_right_frame_ph,
|
||||
anchor="center",
|
||||
tags="bb_sub_frame",
|
||||
)
|
||||
|
||||
if place_buttons:
|
||||
rx_sub = r_box_right - 13
|
||||
|
|
@ -299,8 +380,12 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
rx_sub -= (bw + 6)
|
||||
|
||||
if place_buttons:
|
||||
self._last_btn_split = (tuple(id(b) for b in top_btns), tuple(id(b) for b in sub_btns))
|
||||
self._last_btn_split = (
|
||||
tuple(id(b) for b in top_btns),
|
||||
tuple(id(b) for b in sub_btns),
|
||||
)
|
||||
|
||||
# 3. Hauptleisten-Text im freien linken Bereich auf der X-Achse zentrieren
|
||||
min_lx = side_inset + 22
|
||||
right_limit = rx_main - 14
|
||||
st_str = (self.status_var.get() or "").replace("•", "|")
|
||||
|
|
@ -312,13 +397,17 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
if st_str and (right_limit - (min_lx + segs_w)) >= 90:
|
||||
avail_st_w = right_limit - (min_lx + segs_w + (pipe_step if top_segs else 0))
|
||||
st_ph = self.assets.get_goth_text_photo(
|
||||
st_str, size_px=FONT_SIZE_SMALL_MIN, color=UI_ACCENT_AMETHYST,
|
||||
max_width=max(80, avail_st_w), align="left",
|
||||
st_str,
|
||||
size_px=FONT_SIZE_SMALL_MIN,
|
||||
color=UI_ACCENT_AMETHYST,
|
||||
max_width=max(80, avail_st_w),
|
||||
align="left",
|
||||
)
|
||||
total_txt_w += (pipe_step if top_segs else 0) + st_ph.width()
|
||||
|
||||
avail_txt_span = max(0, right_limit - min_lx)
|
||||
if total_txt_w > 0 and avail_txt_span > total_txt_w:
|
||||
# Sanfte Zentrierung im freien Raum links neben den Buttons
|
||||
centered_lx = min_lx + (avail_txt_span - total_txt_w) // 2 + self.HUD_TEXT_X_OFFSET
|
||||
lx = max(min_lx, min(right_limit - total_txt_w, centered_lx))
|
||||
else:
|
||||
|
|
@ -340,6 +429,7 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
self._txt_refs.append(st_ph)
|
||||
self.create_image(lx, txt_cy_main, image=st_ph, anchor="w", tags="bb_txt")
|
||||
|
||||
# 4. Linke Erweiterungsfläche (nur sichtbar, wenn Text-Segmente nach unten ausgelagert wurden)
|
||||
if sub_segs:
|
||||
sub_txt_w = self._calc_segs_width(sub_segs, pipe_step)
|
||||
l_box_w = sub_txt_w + 36
|
||||
|
|
@ -347,12 +437,25 @@ class DesktopGothBottombar(tk.Canvas):
|
|||
l_box_cx = l_box_left + l_box_w // 2
|
||||
|
||||
self.create_rectangle(
|
||||
l_box_left + 4, sub_top + 4, l_box_left + l_box_w - 4, sub_top + self.SUB_BAR_H - 4,
|
||||
fill="#100d17", outline="", tags="bb_sub_frame",
|
||||
l_box_left + 4,
|
||||
sub_top + 4,
|
||||
l_box_left + l_box_w - 4,
|
||||
sub_top + self.SUB_BAR_H - 4,
|
||||
fill="#100d17",
|
||||
outline="",
|
||||
tags="bb_sub_frame",
|
||||
)
|
||||
self._sub_left_frame_ph = self._get_bar_box_photo(
|
||||
"box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72
|
||||
)
|
||||
self._sub_left_frame_ph = self._get_bar_box_photo("box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72)
|
||||
if self._sub_left_frame_ph:
|
||||
self.create_image(l_box_cx, cy_sub, image=self._sub_left_frame_ph, anchor="center", tags="bb_sub_frame")
|
||||
self.create_image(
|
||||
l_box_cx,
|
||||
cy_sub,
|
||||
image=self._sub_left_frame_ph,
|
||||
anchor="center",
|
||||
tags="bb_sub_frame",
|
||||
)
|
||||
|
||||
sub_lx = l_box_cx - sub_txt_w // 2
|
||||
for i, seg in enumerate(sub_segs):
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/cards/solitaire_card.py
|
||||
# games/solitaire/base/solitaire_card.py
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/table/solitaire_core.py
|
||||
# games/solitaire/base/solitaire_core.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
from games.solitaire.base.cards.solitaire_card import (
|
||||
from games.solitaire.base.solitaire_card import (
|
||||
RANK_VALUES,
|
||||
SOLITAIRE_RANKS,
|
||||
SolitaireCard,
|
||||
|
|
@ -1,476 +0,0 @@
|
|||
# -*- 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,5 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/solitaire/base/session/solitaire_modal_dialog.py
|
||||
# games/solitaire/base/solitaire_modal_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
|
|
@ -13,15 +13,14 @@ from resources.code_res.game_constants import (
|
|||
FONT_SIZE_BODY,
|
||||
FONT_SIZE_TITLE_LG,
|
||||
)
|
||||
from view.widgets.dropdown.goth_dropdown import GothDropdown
|
||||
from view.widgets.buttons.image_button import ImageButton
|
||||
from view.widgets.overlays.modal_veil import ModalVeil
|
||||
from view.widgets.goth_dropdown import GothDropdown
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
|
||||
class SolitaireModalDialog(tk.Canvas):
|
||||
"""
|
||||
Rahmenloses Gothic-Modal (ohne eingebettetes GIF), das über allen UI-Elementen
|
||||
schwebt, das Spielfeld dahinter abdunkelt und alle übrigen Buttons sperrt.
|
||||
Rahmenloses Gothic-Modal auf background_vertical.jpg + box_big.png
|
||||
für Wiederaufnahme-, Aufgeben-, Deadlock- und Sieg-Dialoge (inkl. win.gif) in Solitaire.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
|
@ -31,12 +30,12 @@ class SolitaireModalDialog(tk.Canvas):
|
|||
body_txt: str,
|
||||
buttons: list[tuple[str, str, object, bool] | tuple[str, str, object]],
|
||||
is_danger: bool = False,
|
||||
gif_key: str = "", # abwärtskompatibel ignoriert (Animation läuft vorab)
|
||||
gif_key: str = "",
|
||||
):
|
||||
GothDropdown.close_any_open_popup()
|
||||
_ = gif_key
|
||||
frames = ctx.assets.get_gif_frames(gif_key, size=(150, 84)) if gif_key else []
|
||||
dlg_w = 590 if len(buttons) >= 3 else 500
|
||||
dlg_h = 268
|
||||
dlg_h = 355 if frames else 268
|
||||
|
||||
super().__init__(
|
||||
ctx.root,
|
||||
|
|
@ -50,10 +49,28 @@ class SolitaireModalDialog(tk.Canvas):
|
|||
self._dlg_w = dlg_w
|
||||
self._dlg_h = dlg_h
|
||||
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.5, anchor="center")
|
||||
self._build_scene(title_txt, body_txt, buttons, is_danger)
|
||||
self._veil = ModalVeil(ctx.root, ctx.assets, modal_widget=self)
|
||||
self.place(relx=0.5, rely=0.52, anchor="center")
|
||||
self.bind("<Destroy>", self._on_destroy)
|
||||
self._build_scene(title_txt, body_txt, buttons, is_danger, frames)
|
||||
|
||||
def _on_destroy(self, event=None):
|
||||
if event is not None and event.widget is not self:
|
||||
return
|
||||
if self._gif_job is not None:
|
||||
try:
|
||||
self.after_cancel(self._gif_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._gif_job = None
|
||||
|
||||
def _animate_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._animate_gif, frames, (idx + 1) % len(frames))
|
||||
|
||||
def _build_scene(
|
||||
self,
|
||||
|
|
@ -61,6 +78,7 @@ class SolitaireModalDialog(tk.Canvas):
|
|||
body_txt: str,
|
||||
buttons: list,
|
||||
is_danger: bool,
|
||||
frames: list,
|
||||
):
|
||||
w, h = self._dlg_w, self._dlg_h
|
||||
assets = self.ctx.assets
|
||||
|
|
@ -76,7 +94,15 @@ class SolitaireModalDialog(tk.Canvas):
|
|||
self._photo_refs.append(box_ph)
|
||||
self.create_image(w // 2, h // 2, image=box_ph, anchor="center")
|
||||
|
||||
cur_y = 38
|
||||
cur_y = 26
|
||||
if frames:
|
||||
self._gif_item = self.create_image(w // 2, cur_y + 42, image=frames[0], anchor="center")
|
||||
cur_y += 92
|
||||
if len(frames) > 1:
|
||||
self._animate_gif(frames, 0)
|
||||
else:
|
||||
cur_y = 38
|
||||
|
||||
t_col = FONT_COLOR_STATUS_LOSS if is_danger else FONT_COLOR_TITLE_MAIN
|
||||
clean_body = str(body_txt or "").replace("•", "-")
|
||||
t_ph = assets.get_goth_text_photo(title_txt, FONT_SIZE_TITLE_LG - 4, t_col, max_width=w - 64)
|
||||
|
|
@ -0,0 +1,215 @@
|
|||
# -*- 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)
|
||||
|
|
@ -2,92 +2,110 @@
|
|||
# games/solitaire/base/solitaire_theme.py
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
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 _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."""
|
||||
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", UserWarning)
|
||||
with Image.open(icon_path) as ico:
|
||||
ico_helper = getattr(ico, "ico", None)
|
||||
best_img = None
|
||||
best_area = -1
|
||||
ico_helper = getattr(ico, "ico", None)
|
||||
if ico_helper is not None and hasattr(ico_helper, "sizes"):
|
||||
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
|
||||
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
|
||||
if best_img is None:
|
||||
best_img = _pick_largest_rgba_frame(
|
||||
range(getattr(ico, "n_frames", 1)),
|
||||
lambda idx: (ico.seek(idx), ico.copy())[1],
|
||||
)
|
||||
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
|
||||
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:
|
||||
return a >= 40 and not (r > 228 and g > 228 and b > 228)
|
||||
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
|
||||
|
||||
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]))
|
||||
# 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)
|
||||
|
||||
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
|
||||
)
|
||||
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)
|
||||
|
||||
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=int(side * 2 * 0.195),
|
||||
radius=radius,
|
||||
fill=255,
|
||||
)
|
||||
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
|
||||
|
||||
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
|
||||
r_ch, g_ch, b_ch, a_ch = square.split()
|
||||
square.putalpha(ImageChops.multiply(a_ch, mask))
|
||||
return square
|
||||
|
||||
|
||||
|
|
@ -101,19 +119,24 @@ 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)
|
||||
|
||||
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
|
||||
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
|
||||
photo = ImageTk.PhotoImage(resized)
|
||||
_ICON_TK_CACHE[cache_key] = photo
|
||||
return photo
|
||||
|
||||
|
||||
class SolitaireTableBgRenderer:
|
||||
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
|
||||
# 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
|
||||
|
|
@ -122,7 +145,8 @@ class SolitaireTableBgRenderer:
|
|||
self.res_mgr = res_mgr
|
||||
self._raw_pil: Image.Image | None = None
|
||||
self._loaded = False
|
||||
self._slice_photo: ImageTk.PhotoImage | None = None
|
||||
self._cached_size: tuple[int, int] = (0, 0)
|
||||
self._cached_photo: ImageTk.PhotoImage | None = None
|
||||
|
||||
def _ensure_pil(self) -> Image.Image | None:
|
||||
if not self._loaded:
|
||||
|
|
@ -137,15 +161,13 @@ class SolitaireTableBgRenderer:
|
|||
return self._raw_pil
|
||||
|
||||
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
|
||||
if LayoutMode.is_compact(canvas_w, canvas_h):
|
||||
return max(8, int(canvas_w * 0.018)), 6, 8
|
||||
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
|
||||
if self._ensure_pil() is None:
|
||||
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
|
||||
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)),
|
||||
)
|
||||
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
|
||||
|
||||
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
|
||||
if canvas_w < 80 or canvas_h < 80:
|
||||
|
|
@ -155,7 +177,8 @@ class SolitaireTableBgRenderer:
|
|||
if assets is None:
|
||||
return
|
||||
|
||||
rw, rh = max(canvas_w, root.winfo_width()), max(canvas_h, root.winfo_height())
|
||||
rw = max(canvas_w, root.winfo_width())
|
||||
rh = 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)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,178 @@
|
|||
# -*- 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))
|
||||
|
|
@ -1,374 +0,0 @@
|
|||
# -*- 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,387 +0,0 @@
|
|||
# -*- 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.table.solitaire_core import (
|
||||
from games.solitaire.base.solitaire_core import (
|
||||
SolitaireBaseEngine,
|
||||
SolitaireCard,
|
||||
is_alternating_descending,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import heapq
|
|||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from games.solitaire.base.table.solitaire_core import SOLITAIRE_RANKS, SolitaireCard
|
||||
from games.solitaire.base.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,38 +2,402 @@
|
|||
# games/solitaire/freecell/views/freecell_menu_view.py
|
||||
from __future__ import annotations
|
||||
|
||||
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
|
||||
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.freecell.views.freecell_table_view import FreeCellTableView
|
||||
from resources.code_res.game_constants import FREECELL_VARIANTS
|
||||
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
|
||||
|
||||
GAME_FOLDER_ID = "solitaire/freecell"
|
||||
GAME_TITLE_KEY = "game_title_freecell"
|
||||
DEFAULT_VARIANT_KEY = "freecell_std"
|
||||
|
||||
|
||||
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"
|
||||
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 = []
|
||||
|
||||
DIFF_SETTING_PREFIX = "freecell_diff"
|
||||
DEFAULT_VARIANT_KEY = "freecell_std"
|
||||
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
|
||||
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
|
||||
|
||||
MODE_LABEL_KEY = "fc_variant_info_lbl"
|
||||
DESC_KEY_PREFIX = "fc_desc_"
|
||||
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()
|
||||
|
||||
def _variants_dict(self) -> dict[str, dict]:
|
||||
return FREECELL_VARIANTS
|
||||
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 _launch_table_view(
|
||||
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
|
||||
) -> None:
|
||||
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)
|
||||
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
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue