Compare commits

...

10 Commits
beta_5 ... main

Author SHA1 Message Date
thw 31b28652db Release v0.8.0-beta: Watten, tutorial framework, soul profiles & UI font selector 2026-11-25 22:55:44 +01:00
thw 8acff1058a feat: add 10er raus, Pyramid & TriPeaks Solitaire, custom game icons and Linux DB path fix 2026-11-24 20:50:08 +01:00
thw c5e303db9f release(v0.6.0-beta): modularize codebase (<500 LOC/file), unify stats hub & refine win FX
Release v0.6.0-beta:
- Strikte Modularisierung (<500 Zeilen pro Datei, 1 Klasse pro Modul, pyscn Health Score 97/100).
- Gemeinsame Basis-Klassen extrahiert: SolitaireMenuBase, SolitaireTableController, SolitaireSessionGuard, SolitaireCanvasInput, SolitaireOutcomeFlow, LuckPouchMenuBase, CasinoArenaBase & CasinoResultDialogBase.
- UnifiedStatsView: kategorisierter Statistik-Hub (Glück, Solitaire, Bayerische Spiele, Gesellschaft) ohne Gesamt-Ansicht.
- PokerResultDialog auf das Gothic-Canvas-Rahmendesign gehoben.
- EndgameFxOverlay: Feuerwerksraketen entfernt, direkter Spawn von Fledermaus- und Kürbis-Explosionen.
2026-11-22 23:11:52 +01:00
thw 9492b92e80 refactor(arch,ui,stats): modularize codebase (<500 LOC/file), unify stats hub & refine win FX
Großes Architektur-, Deduplizierungs- & UI-Release:
- Strikte Modularisierung (<500 Zeilen pro Datei, 1 Klasse pro Modul, pyscn Health Score 97/100).
- Gemeinsame Basis-Klassen extrahiert: SolitaireMenuBase, SolitaireTableController, SolitaireSessionGuard, SolitaireCanvasInput, SolitaireOutcomeFlow, LuckPouchMenuBase, CasinoArenaBase & CasinoResultDialogBase.
- UnifiedStatsView: kategorisierter Statistik-Hub (Glück, Solitaire, Bayerische Spiele, Gesellschaft) ohne Äpfel-mit-Birnen-Gesamtansicht.
- PokerResultDialog auf das Gothic-Canvas-Rahmendesign gehoben.
- EndgameFxOverlay: Feuerwerksraketen entfernt, direkter Spawn von Fledermaus- und Kürbis-Explosionen.
2026-11-22 23:07:57 +01:00
thw 42bf545b35 feat(settings,db,auth,ui): add portable DB relocation, online account login, full-screen SettingsView & error overlay
Architektur-, UI- & Aufräum-Update:
- DbLocator + Database: freie Speicherortwahl beim Erstnutzer, Live-Laden & atomarer Umzug (SQLite Backup API) inkl. Selbst-Speicherung des Pfads in settings.
- OnlineSessionClient & LoginView: Modus-Weiche zwischen lokalem Profil und Online-Einzelaccount (URL inkl. Port oder IP + Port, REST/JSON & TCP/JSON).
- SettingsView: AudioSettingsDialog durch vollflächige, responsive 1-/2-Spalten-Ansicht ersetzt (inkl. verlustfreiem In-Game-Modus) und redundante Sprach-Buttons entfernt.
- ErrorReportOverlay: globaler Crash-Handler für unbehandelte Exceptions mit Copy-to-Clipboard und crash_errors.log.
- i18n & Cleanup: nicht unterstützte Sonderzeichen/Glyphen aus allen SQL-Dateien entfernt und verwaiste Altdateien bereinigt.
2026-11-22 04:26:44 +01:00
thw 22aef15efc feat(blackjack,poker): integrate EndgameFxOverlay, fix split-pot tie handling, and reveal showdown bot cards
Blackjack & Poker Endgame-Integration:
- EndgameFxOverlay vor BlackjackResultDialog (inkl. Instant-777-Sieg) und PokerResultDialog eingebunden.
- Echten Split-Pot ohne Netto-Gewinn/Verlust in Poker sauber als Unentschieden (player_won = None) behandelt, sodass keine fehlerhafte Niederlagen-Animation auslöst.
- Aufgedeckte Bot-Hole-Cards im Poker-Showdown direkt in den Tisch-Boxen während der Vorschalt-Animation eingeblendet und Hand-Referenz-Button im Showdown ausgeblendet.
- play_fx=False bei Sprachwechsel und Resume-Ständen gesetzt, um doppelte Animationen zu verhindern.
2026-11-22 00:28:06 +01:00
thw 88f957b5ed chore: sync LICENSE.md removal from public repo 2026-11-22 00:13:15 +01:00
thw 547c13ce7f feat(solitaire,ui): add Z-order card hover peek, single-tap move setting, ModalVeil, and EndgameFxOverlay
Solitaire UX & Bedienhilfen:
- CardHoverZoom (games/solitaire/base/card_hover_zoom.py) eingeführt: Hebt offene Karten beim Überfahren dezent an und vergrößert sie leicht unter Beibehaltung der exakten Z-Order im Stapel, sodass aufliegende Folgekarten sichtbar bleiben (inkl. 3er-Ablagefächer in Klondike und blockierter Zwischenkarten in FreeCell/Spider).
- Persistente Einstellung "Einfacher Klick zum Schieben" / "Single tap to move" (games/solitaire/base/solitaire_tap_prefs.py) ergänzt: Kurze Einzelklicks (<= 0.28s) führen automatisch Züge aus, während längeres Halten ignoriert wird und Drag & Drop uneingeschränkt erhalten bleibt.
- AudioSettingsDialog (view/dialogs/audio_settings_dialog.py) um den neuen GothSwitch erweitert, Layout auf 768p-Kompatibilität (DLG_H = 656) optimiert und alle Dialogtexte sauber auf base_i18n (01_allgemein.sql) umgestellt.
- FreeCellTableView, KlondikeTableView und SpiderTableView auf CardHoverZoom, Single-Tap-Steuerung, zentrale GothTopbar-Statistik-Endpunkte und SolitaireBottomBar-Overflow-Buttons aktualisiert.

Überarbeitetes Spielende & Modal-Architektur:
- ModalVeil (view/widgets/modal_veil.py) implementiert: Dunkelt das gesperrte Spielfeld halbtransparent ab, hebt aktive Dialoge garantiert über alle UI-Leisten und blockiert Eingaben sowie Tastenkürzel im Hintergrund.
- EndgameFxOverlay (view/widgets/endgame_fx_overlay.py) implementiert: Spielt vor dem Ergebnis-Dialog auf dem gesperrten Tisch Alpha-Kanal-Animationen ab (Sieg: firework_start.gif unten links + zufällig verteilte bat_explosion.gif / pumpkin_explosion.gif; Niederlage: zufällig verteilte foul_pumpkin.gif) und wechselt erst per Klick zum Result-Screen.
- ResourceManager und AssetManager um den Pfad resources/images/win_lose/, RGBA-GIF-Sequenz-Caching inkl. Original-Frame-Dauern, abgedunkelte Veil-Texturen und Startup-Preloading erweitert.
- Eingebettete GIF-Animationen aus SolitaireModalDialog, BlackjackResultDialog und PokerResultDialog vollständig entfernt und alle drei Ergebnis-Fenster auf ModalVeil umgestellt.
2026-11-22 00:02:21 +01:00
kuro 9ef9318a51 Delete LICENSE 2026-11-21 02:09:34 +00:00
kuro 4afd260bab Delete LICENSE.md 2026-11-21 02:09:17 +00:00
231 changed files with 20423 additions and 13966 deletions

674
LICENSE
View File

@ -1,674 +0,0 @@
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>.

View File

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

View File

@ -1,7 +1,7 @@
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(1, 0, 0, 0),
prodvers=(1, 0, 0, 0),
filevers=(0, 6, 0, 0),
prodvers=(0, 6, 0, 0),
mask=0x3f,
flags=0x0,
OS=0x40004,
@ -16,12 +16,12 @@ VSVersionInfo(
[
StringStruct('CompanyName', 'Kuro'),
StringStruct('FileDescription', 'The Goth Cardgame Collection'),
StringStruct('FileVersion', '1.0.0.0'),
StringStruct('FileVersion', '0.6.0.0'),
StringStruct('InternalName', 'TheGothCardgameCollection'),
StringStruct('LegalCopyright', 'Copyright (C) 2026 Kuro'),
StringStruct('OriginalFilename', 'TheGothCardgameCollection.exe'),
StringStruct('ProductName', 'The Goth Cardgame Collection'),
StringStruct('ProductVersion', '1.0.0.0')
StringStruct('ProductVersion', '0.6.0-beta')
]
)
]),

View File

@ -3,7 +3,6 @@
from __future__ import annotations
from models.database import Database
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.unified_stats_view import UnifiedStatsView
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_topbar import GothTopbar, format_compact_user_badge
@ -12,7 +11,7 @@ __all__ = ["AppContext", "GothTopbar", "UnifiedStatsView", "format_compact_user_
class AppContext:
"""Schlanker Spiel-Kontext; Topbar und Statistik laufen zentral über eigene Widgets."""
"""Schlanker Spiel-Kontext; Topbar, Einstellungen und Statistik laufen zentral."""
def __init__(self, controller, game_folder: str):
self._ctrl = controller
@ -39,11 +38,9 @@ class AppContext:
def open_settings(self, on_lang_refresh=None):
GothDropdown.close_any_open_popup()
AudioSettingsDialog.open(
self.root,
self.assets,
self.sounds,
on_toggle_lang=lambda: self.toggle_language(on_lang_refresh),
self._ctrl.show_settings(
in_game_overlay=True,
on_ingame_lang_refresh=on_lang_refresh,
)
def open_audio_settings(self):
@ -54,7 +51,6 @@ class AppContext:
endpoint = self.game_folder if game_endpoint is None else game_endpoint
UnifiedStatsView.open(self, game_endpoint=endpoint, on_back=on_back)
# Alias für etwaige bestehende Aufrufe
open_global_stats = open_stats
def toggle_language(self, refresh_callback=None):

View File

@ -1,12 +1,19 @@
# -*- coding: utf-8 -*-
# controller/app_controller.py
from __future__ import annotations
from pathlib import Path
from controller.app_context import AppContext
from controller.game_loader import GameLoader
from games.solitaire.base.solitaire_tap_prefs import invalidate_tap_prefs_cache
from models.database import Database
from models.db_locator import DbLocator
from models.online_session import OnlineSessionClient
from models.sound_manager import SoundManager
import resources.code_res.i18n as i18n
from resources.code_res.i18n import t
from view.widgets.image_button import set_button_hover_help_enabled
class AppController:
@ -17,16 +24,58 @@ class AppController:
i18n.set_lang(Database.load_setting("language", "DE"))
self.loader = GameLoader(root_dir)
self.sounds = SoundManager(root_dir / "resources" / "sounds")
self.active_profile = None
self.online_session = OnlineSessionClient()
self.is_online_mode: bool = False
self.active_profile: dict | None = None
self.view = None
def bind_view(self, view):
self.view = view
self.view._app_controller = self
def can_modify_user_db(self) -> bool:
"""Sperrt das Laden/Umziehen der lokalen DB im Online-Modus oder während Devil's Deal."""
if self.is_online_mode:
return False
if self.active_profile and self.has_active_devils_lock():
return False
return True
def _reload_runtime_preferences_from_db(self):
"""Synchronisiert Sprache, Audio & Schalter-Settings nach einem Datenbank-Wechsel."""
lang = Database.load_setting("language", "DE")
i18n.set_lang(lang)
invalidate_tap_prefs_cache()
hover_raw = Database.load_setting("ui_button_hover_help", "")
if hover_raw != "":
set_button_hover_help_enabled(
str(hover_raw).strip().lower() in ("1", "true", "yes", "on"),
persist=False,
)
amb_raw = Database.load_setting("ambiance_volume", "")
if amb_raw != "":
try:
self.sounds.set_ambiance_volume(float(amb_raw), persist=False)
except Exception:
pass
sfx_raw = Database.load_setting("menu_volume", "")
if sfx_raw != "":
try:
self.sounds.set_menu_volume(float(sfx_raw), persist=False)
except Exception:
pass
if self.view is not None:
self.view.title(t("app_title"))
def toggle_language(self, custom_refresh=None):
new_lang = i18n.next_lang()
Database.save_setting("language", new_lang)
self.view.title(t("app_title"))
if self.view is not None:
self.view.title(t("app_title"))
if custom_refresh is not None:
custom_refresh()
elif self.active_profile:
@ -34,34 +83,134 @@ class AppController:
else:
self.start()
def start(self):
def start(self, status_msg: str = "", is_error: bool = False, login_mode: str = "local"):
self.sounds.play_menu_music()
profiles = Database.get_profiles()
last_prof = Database.load_setting("last_profile_name", "")
self.view.show_login(profiles, preselect_name=last_prof)
self.view.show_login(
profiles,
preselect_name=last_prof,
status_msg=status_msg,
is_error=is_error,
login_mode=login_mode,
)
def do_login(self, name: str):
if not name:
return
self.online_session.disconnect()
self.is_online_mode = False
Database.save_setting("last_profile_name", name)
self.active_profile = Database.get_or_create_profile(name)
self.show_main_menu()
def do_create_profile(self, name: str):
if not name:
def do_create_profile(self, name: str, first_user_db_dir: str | None = None):
clean_name = name.strip()
if not clean_name:
return
Database.save_setting("last_profile_name", name)
self.active_profile = Database.get_or_create_profile(name)
self.online_session.disconnect()
self.is_online_mode = False
if first_user_db_dir and len(Database.get_profiles()) == 0:
try:
Database.relocate_for_first_user(Path(first_user_db_dir))
except Exception as exc:
self.start(
status_msg=t("db_err_move_failed", str(exc)),
is_error=True,
login_mode="local",
)
return
Database.save_setting("last_profile_name", clean_name)
self.active_profile = Database.get_or_create_profile(clean_name)
self.show_main_menu()
def do_online_login(
self,
addr_mode: str,
raw_url: str,
raw_ip: str,
raw_port: str,
username: str,
password: str,
) -> tuple[bool, str]:
clean_user = username.strip()
DbLocator.save_online_prefs(addr_mode, raw_url, raw_ip, raw_port, clean_user)
ok, err_msg = self.online_session.authenticate(
addr_mode=addr_mode,
raw_url=raw_url,
raw_ip=raw_ip,
raw_port=raw_port,
username=clean_user,
password=password,
)
if not ok:
return False, err_msg
self.is_online_mode = True
local_mirror = dict(Database.get_or_create_profile(clean_user))
local_mirror["is_online"] = True
local_mirror["online_endpoint"] = self.online_session.endpoint_label
self.active_profile = local_mirror
self.show_main_menu()
return True, ""
def load_user_data_from_file(self, db_file_path: str) -> tuple[bool, str]:
if not self.can_modify_user_db():
return False, t("db_err_locked_devils")
ok, info = Database.switch_user_database(Path(db_file_path))
if not ok:
msg = t("db_err_invalid_file") if info == "invalid_file" else t("db_err_move_failed", info)
return False, msg
self._reload_runtime_preferences_from_db()
self.online_session.disconnect()
self.is_online_mode = False
self.active_profile = None
profiles = Database.get_profiles()
last_prof = Database.load_setting("last_profile_name", "")
ok_msg = t("db_load_ok", info)
if self.view is not None:
self.view.show_login(profiles, preselect_name=last_prof, status_msg=ok_msg, is_error=False)
return True, ok_msg
def move_user_data_to_folder(self, target_dir_path: str) -> tuple[bool, str]:
if not self.can_modify_user_db():
return False, t("db_err_locked_devils")
ok, info = Database.move_user_database(Path(target_dir_path))
if not ok:
return False, t("db_err_move_failed", info)
if self.active_profile and not self.is_online_mode:
refreshed = Database.get_profile_by_id(self.active_profile["id"])
if refreshed:
self.active_profile = refreshed
return True, t("db_move_ok", info)
def logout_to_login(self):
self.sounds.play_menu_music()
last_prof = self.active_profile["name"] if self.active_profile else Database.load_setting("last_profile_name", "")
last_prof = (
self.active_profile["name"]
if (self.active_profile and not self.is_online_mode)
else Database.load_setting("last_profile_name", "")
)
was_online = self.is_online_mode
self.online_session.disconnect()
self.is_online_mode = False
self.active_profile = None
self.view.show_login(Database.get_profiles(), preselect_name=last_prof)
self.view.show_login(
Database.get_profiles(),
preselect_name=last_prof,
login_mode="online" if was_online else "local",
)
def get_locked_devils_game_folder(self) -> str | None:
if not self.active_profile:
if not self.active_profile or self.is_online_mode:
return None
pid = self.active_profile["id"]
if Database.get_active_devils_bj_account(pid) is not None:
@ -85,26 +234,69 @@ class AppController:
self.launch_game(g)
return
def show_main_menu(self):
def show_main_menu(self, category: str | None = None):
self.sounds.play_menu_music()
if self.active_profile:
pid = self.active_profile["id"]
self.active_profile = Database.get_profile_by_id(pid)
fresh = Database.get_profile_by_id(pid)
if fresh:
fresh = dict(fresh)
fresh["overall_progress"] = Database.get_profile_overall_progress(pid)
if self.is_online_mode:
fresh["is_online"] = True
fresh["online_endpoint"] = self.online_session.endpoint_label
self.active_profile = fresh
if self.has_active_devils_lock():
self.view.show_main_menu(self.active_profile, [], devils_resume_only=True)
else:
games = self.loader.discover_games()
for g in games:
g["progress"] = Database.get_game_progress(pid, g["folder"])
self.view.show_main_menu(self.active_profile, games, devils_resume_only=False)
self.view.main_menu_view.show(
self.active_profile, games, devils_resume_only=False, category=category
)
def show_statistics(self):
if self.has_active_devils_lock():
if self.has_active_devils_lock() or not self.active_profile:
return
self.sounds.play_menu_music()
if self.active_profile:
self.active_profile = Database.get_profile_by_id(self.active_profile["id"])
self.view.show_statistics(self.active_profile)
fresh = Database.get_profile_by_id(self.active_profile["id"])
if fresh:
if self.is_online_mode:
fresh = dict(fresh)
fresh["is_online"] = True
fresh["online_endpoint"] = self.online_session.endpoint_label
self.active_profile = fresh
ctx = AppContext(self, game_folder="")
from view.unified_stats_view import UnifiedStatsView
UnifiedStatsView.open(ctx, game_endpoint=None, on_back=None)
def show_settings(
self,
on_back=None,
in_game_overlay: bool = False,
on_ingame_lang_refresh=None,
feedback_txt: str = "",
feedback_err: bool = False,
):
if not in_game_overlay:
self.sounds.play_menu_music()
if self.view is not None:
self.view.show_settings(
on_back=on_back,
in_game_overlay=in_game_overlay,
on_ingame_lang_refresh=on_ingame_lang_refresh,
feedback_txt=feedback_txt,
feedback_err=feedback_err,
)
def show_profile(self, on_back=None):
if self.has_active_devils_lock() or not self.active_profile:
return
self.sounds.play_menu_music()
if self.view is not None:
self.view.show_profile(on_back=on_back)
def launch_game(self, game_entry: dict):
self.view.clear_window(apply_global_bg=True)

View File

@ -0,0 +1,283 @@
# -*- 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,
PLAYING_CARD_SIZE,
)
from resources.code_res.i18n import t
BJ_DEALER_CARD_SIZE = (86, 125)
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 und Spielerhände (inkl. Split) auf das Arena-Canvas."""
@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
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_w, dc_h = BJ_DEALER_CARD_SIZE
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=BJ_DEALER_CARD_SIZE)
if c_idx == 1 and not reveal_dealer
else view.ctx.assets.get_card_photo(card.image_filename, size=BJ_DEALER_CARD_SIZE)
)
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, BJ_DEALER_CARD_SIZE, visible_step=38, max_width=340
)
pot_txt = t("bj_pot_banner", view.engine.pot).split("|")[0].strip()
pot_cy = min(
felt_bot - 22,
max(d_cards_cy + dc_h // 2 + 34, (d_cards_cy + dc_h // 2 + felt_bot) // 2),
)
pot_size = max(16, FONT_SIZE_BODY + 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(230, pot_ph.width() + 64), max(40, pot_ph.height() + 18)
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, 240, 40, frame_style="gold")
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_size, ACCENT_GOLD)
@staticmethod
def draw_bots_at_corners(
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
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)
frame_style = "gold" if is_turn else "purple"
status_border = ERROR_FG if is_out else None
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)
if reveal_opponents and bot.hand:
b_val, _ = HandEvaluator.evaluate(bot.hand)
if bot.folded:
info_txt = t("bj_rank_folded", b_val)
elif bot.busted:
info_txt = t("bj_rank_busted", b_val)
else:
info_txt = t("bj_bot_showdown_val", b_val, bot.bet_in_pot)
elif bot.status_text:
info_txt = bot.status_text
elif bot.hand:
info_txt = t("bj_bot_cards_hidden", len(bot.hand), bot.bet_in_pot)
else:
info_txt = ""
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=frame_style, status_border=status_border)
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 = []
for card in bot.hand:
photo = (
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)
)
if photo:
view._photo_refs.append(photo)
bot_photos.append(photo)
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_player_hands(cls, view, cw: int, player_zone_top: int, player_zone_bot: int) -> None:
hands = view.engine.player_hands
if not hands:
return
avail_h = max(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(88, min(base_h, avail_h - 52)) / max(1, base_h)
card_sz = (max(60, int(round(base_w * scale))), int(round(base_h * scale)))
p_photos = []
for card in h.cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
p_photos.append(photo)
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(14, FONT_SIZE_BODY - 1)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
step = 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 240
box_w = max(300, min(560, max(fan_w + 96, txt_w + 72)))
box_h = min(avail_h, card_sz[1] + 52)
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 - 11, p_photos, card_sz, visible_step=step, max_width=box_w - 44
)
view._place_goth_photo_or_fallback(cw // 2, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col)
return
# Split-Hände nebeneinander
base_w, base_h = BJ_SPLIT_CARD_SIZE
scale = max(80, min(base_h, avail_h - 48)) / max(1, base_h)
card_sz = (max(54, int(round(base_w * scale))), int(round(base_h * scale)))
box_h = min(avail_h, card_sz[1] + 48)
lbl_sz = max(13, FONT_SIZE_BODY - 2)
prepared_splits = []
max_box_w = 228
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)
txt_w = lbl_ph.width() if lbl_ph is not None else 180
sp_fan_w = card_sz[0] + max(0, len(h.cards) - 1) * 28
max_box_w = max(max_box_w, max(228, min(320, max(sp_fan_w + 64, txt_w + 60))))
prepared_splits.append((h, is_active, is_out, lbl_txt, lbl_col, lbl_ph))
n_hands = len(hands)
slot_gap = max(max_box_w + 14, min(310, (cw - 360) // max(1, n_hands)))
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 = []
for card in h.cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
sp_photos.append(photo)
if sp_photos:
view._draw_fanned_cards_on_canvas(
h_cx, zone_cy - 10, sp_photos, card_sz, visible_step=28, max_width=max_box_w - 36
)
view._place_goth_photo_or_fallback(h_cx, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col)

View File

@ -2,515 +2,76 @@
# games/blackjack/views/blackjack_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from games.blackjack.views.blackjack_stats_view import BlackjackStatsView
from games.blackjack.views.blackjack_table_view import BlackjackTableView
from view.widgets.menu_body_canvas import MenuBodyCanvas
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
BJ_INITIAL_ANTE,
BJ_MAX_BOTS,
BJ_STARTING_GOLD,
BJ_VARIANTS,
DEVILS_DEAL_GOLD_REWARD,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_DISABLED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
GOLD_MAX_ACCOUNTS,
GOLD_MIN_TABLE_ENTRY,
XP_TO_GOLD_AMOUNT,
)
from resources.code_res.i18n import t
from view.widgets.bot_setup_widget import BotSetupWidget
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
GAME_FOLDER_ID = "blackjack"
class BlackjackMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
class BlackjackMenuView(LuckPouchMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
LAST_ACC_SETTING_PREFIX = "last_bj_account"
STARTING_GOLD = BJ_STARTING_GOLD
MAX_BOTS = BJ_MAX_BOTS
REQUIRES_MIN_ONE_BOT = False
DEVILS_DEFAULT_VARIANT = "bj_classic"
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
KEY_TOPBAR = "bj_menu_topbar"
KEY_HEADER_GOLD = "bj_header_gold"
KEY_SEC1_TITLE = "bj_sec1_title"
KEY_BOTS_TITLE = "bj_bots_sec_title"
KEY_SEC3_TITLE = "bj_sec3_title"
KEY_GOLD_DISPLAY = "bj_gold_display_lbl"
KEY_DEFAULT_ACC_NAME = "bj_default_acc_name"
KEY_ERR_DUPLICATE = "bj_err_duplicate_name"
devils_acc = Database.get_active_devils_bj_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
if saved is not None:
BlackjackTableView(
self.ctx,
variant_key=saved["variant_key"],
bj_account_id=devils_acc["id"],
bot_configs=[],
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
resume_state_json=saved["state_json"],
)
return
def _get_active_devils_account(self, pid: int):
return Database.get_active_devils_bj_account(pid)
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
bj_prog = self.ctx.refresh_game_progress()
def _get_accounts(self, pid: int):
return Database.get_blackjack_accounts(pid)
dyn_xp_cost = bj_prog["xp_exchange_cost"]
is_divine = bj_prog["is_divine_punishment"]
at_floor = bj_prog["at_divine_floor"]
devils_deal_open = bj_prog["devils_deal_unlocked"]
def _get_account(self, acc_id: int):
return Database.get_blackjack_account(acc_id)
setting_key = f"last_bj_account_{pid}"
accounts = Database.get_blackjack_accounts(pid)
has_accounts = len(accounts) > 0
def _create_account(self, pid: int, name: str):
return Database.create_blackjack_account(pid, name)
if preselect_id is None and has_accounts:
saved_id_str = Database.load_setting(setting_key, "")
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
def _delete_account(self, acc_id: int):
Database.delete_blackjack_account(acc_id)
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
def _exchange_xp(self, pid: int, acc_id: int):
return Database.exchange_xp_for_bj_gold(pid, acc_id)
active_acc = None
if has_accounts:
active_acc = accounts[0]
if preselect_id is not None:
for a in accounts:
if a["id"] == preselect_id:
active_acc = a
break
Database.save_setting(setting_key, str(active_acc["id"]))
def _variants_dict(self) -> dict[str, dict]:
return BJ_VARIANTS
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
def _min_entry_for_variant(self, _v_key: str, _cfg: dict) -> int:
return GOLD_MIN_TABLE_ENTRY
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
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 _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,
)
state_msg = {"text": status_msg, "ok": status_is_ok}
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
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 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()))

View File

@ -0,0 +1,307 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_showdown_presenter.py
from __future__ import annotations
import time
from games.blackjack.models.bot_seat import BlackjackBotSeat
from games.blackjack.models.hand_evaluator import HandEvaluator
from models.card import Card
from models.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']}")

View File

@ -1,132 +0,0 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_stats_view.py
from __future__ import annotations
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_HEADING_SUB,
FONT_SIZE_BODY,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from view.widgets.stats_board_widget import StatsBoardWidget
GAME_FOLDER_ID = "blackjack"
class BlackjackStatsView:
"""Rahmenlose Statistik-Ansicht für die einzelnen Blackjack-Goldbeutel."""
def __init__(self, context, on_back_to_bj_menu):
self.ctx = context
self.on_back_to_bj_menu = on_back_to_bj_menu
self._photo_refs: list = []
def show(self, selected_acc_id: int | None = None):
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pid = self.ctx.profile["id"]
accounts = Database.get_blackjack_accounts(pid)
if not accounts:
self.on_back_to_bj_menu(None)
return
active_acc = accounts[0]
if selected_acc_id is not None:
for a in accounts:
if a["id"] == selected_acc_id:
active_acc = a
break
self.ctx.build_game_topbar(
self.ctx.root,
t("bj_stats_view_topbar"),
on_game_menu=lambda: self.on_back_to_bj_menu(active_acc["id"]),
extra_right_text=t("bj_header_gold", active_acc["account_name"], active_acc["gold"]),
on_lang_refresh=lambda: self.show(active_acc["id"]),
)
cv = MenuBodyCanvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
acc_btns: list[tuple[ImageButton, int]] = []
for acc in accounts:
is_sel = (acc["id"] == active_acc["id"])
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
b = ImageButton(
cv,
btn_lbl,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
sound_mgr=self.ctx.sounds,
width=180,
height=38,
style="fire" if is_sel else "amethyst",
)
acc_btns.append((b, b.pixel_width))
bj_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
bj_filter_map = {t("bj_filter_all_tables"): None}
for v in bj_variants:
bj_filter_map[v["translated_name"]] = v["id"]
board = StatsBoardWidget(
cv,
title=t("bj_stats_acc_title", active_acc["account_name"]),
filter_map=bj_filter_map,
fetch_callback=lambda vid: Database.get_bj_account_stats_overview(active_acc["id"], vid),
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1060, w - 2 * pad_x)
left_edge = (w - content_w) // 2
sel_h = 114
sel_top = max(24, int(h * 0.05))
sel_cy = sel_top + sel_h // 2
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
if sel_box:
self._photo_refs.append(sel_box)
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t("bj_stats_select_acc_lbl"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(lbl_ph)
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
cur_bx = left_edge + 26
for b_wgt, bw in acc_btns:
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
cur_bx += bw + 10
board_top = sel_top + sel_h + 22
board_h = max(238, min(270, h - board_top - 32))
cv.create_window(
w // 2,
board_top + board_h // 2,
window=board,
width=content_w,
height=board_h,
anchor="center",
tags="fg",
)
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,244 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_turn_driver.py
from __future__ import annotations
from games.blackjack.models.bot_seat import BlackjackBotSeat
from games.blackjack.models.hand_evaluator import HandEvaluator
from games.blackjack.views.blackjack_showdown_presenter import BlackjackShowdownPresenter
from models.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.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)
)

View File

@ -2,134 +2,42 @@
# 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.image_button import ImageButton
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
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.
"""
class BlackjackResultDialog(CasinoResultDialogBase):
"""Gothic-Showdown-Overlay für Blackjack auf Basis von CasinoResultDialogBase."""
def __init__(
self,
parent,
assets,
sounds,
result_data: dict,
on_next_round,
on_back_to_menu,
):
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
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 = (
(116 if has_gif else 54)
58
+ (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
)
# 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
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
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
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
reason_txt = self.data.get("reason_text", "")
if reason_txt:
r_ph = self.assets.get_goth_text_photo(
@ -145,178 +53,78 @@ class BlackjackResultDialog(tk.Canvas):
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 hands_list:
sec_ph = self.assets.get_goth_text_photo(
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(sec_ph)
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
cur_y += 22
if not hands_list:
return cur_y
max_cols = 3
rows = (len(hands_list) + max_cols - 1) // max_cols
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
seat_h = 128 if rows > 1 else 136
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
if win_box:
self._photo_refs.append(win_box)
if std_box:
self._photo_refs.append(std_box)
for idx, entry in enumerate(hands_list):
r_i, c_i = divmod(idx, max_cols)
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
row_total_w = in_row * seat_w + (in_row - 1) * 10
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
is_win = entry.get("is_winner", False)
is_dead = entry.get("busted", False) or entry.get("folded", False)
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
o_col = (
FONT_COLOR_TITLE_MAIN
if is_win
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
)
o_ph = self.assets.get_goth_text_photo(
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
)
self._photo_refs.append(o_ph)
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
# Ü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,
sec_ph = self.assets.get_goth_text_photo(
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(xp_ph)
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
self._photo_refs.append(sec_ph)
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
cur_y += 22
# 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
max_cols = 3
rows = (len(hands_list) + max_cols - 1) // max_cols
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
seat_h = 128 if rows > 1 else 136
btn_y = h - 34
can_next = self.data.get("can_continue", True)
can_menu = self.data.get("can_leave_menu", True)
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
if win_box:
self._photo_refs.append(win_box)
if std_box:
self._photo_refs.append(std_box)
if can_next and can_menu:
b_next = ImageButton(
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
self._handle_next, sound_mgr=self.sounds, width=205, height=38, style="fire"
for idx, entry in enumerate(hands_list):
r_i, c_i = divmod(idx, max_cols)
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
row_total_w = in_row * seat_w + (in_row - 1) * 10
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
is_win = entry.get("is_winner", False)
is_dead = entry.get("busted", False) or entry.get("folded", False)
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
o_col = (
FONT_COLOR_TITLE_MAIN if is_win
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
)
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
self._handle_menu, sound_mgr=self.sounds, width=175, height=38, style="amethyst"
o_ph = self.assets.get_goth_text_photo(
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
)
self.create_window(42, btn_y, window=b_next, anchor="w")
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
elif can_next:
b_next = ImageButton(
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
self._handle_next, sound_mgr=self.sounds, width=215, height=38, style="fire"
self._photo_refs.append(o_ph)
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
c_photos = [
ph for img_name in entry.get("card_images", [])
if (ph := self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)) is not None
]
self._photo_refs.extend(c_photos)
if c_photos:
cw_c, ch_c = SHOWDOWN_MINI_CARD_SIZE
n_c = len(c_photos)
step = 24
if n_c > 1 and (cw_c + (n_c - 1) * step) > (seat_w - 28):
step = max(14, (seat_w - 28 - cw_c) // (n_c - 1))
fan_w = cw_c + (n_c - 1) * step if n_c > 1 else cw_c
start_cx, card_top = sx - fan_w // 2, sy - ch_c // 2 + 2
for ci, cph in enumerate(c_photos):
self.create_image(start_cx + ci * step, card_top, image=cph, anchor="nw")
rk_col = (
FONT_COLOR_STATUS_WIN if is_win
else (FONT_COLOR_STATUS_LOSS if is_dead else FONT_COLOR_BODY_DEFAULT)
)
self.create_window(cx, btn_y, window=b_next, anchor="center")
elif can_menu:
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_fire, btn_fire,
self._handle_menu, sound_mgr=self.sounds, width=195, height=38, style="fire"
rk_ph = self.assets.get_goth_text_photo(
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
)
self.create_window(cx, btn_y, window=b_menu, anchor="center")
self._photo_refs.append(rk_ph)
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
def _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()
return cur_y + rows * (seat_h + 6) + 6

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

View File

View File

View File

@ -0,0 +1,265 @@
# -*- coding: utf-8 -*-
# games/party/watten/models/watten_ai.py
from __future__ import annotations
import random
from games.party.watten.models.watten_engine import WattenEngine, WattenSeat
from games.party.watten.models.watten_rules import (
NATURAL_STRENGTH,
WATTEN_RANKS_32,
evaluate_trick_winner,
is_guade,
is_kritische,
is_schlag,
is_trump_card,
trick_card_power,
)
from models.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),
)

View File

@ -0,0 +1,344 @@
# -*- coding: utf-8 -*-
# games/party/watten/models/watten_engine.py
from __future__ import annotations
from dataclasses import dataclass, field
import random
from games.party.watten.models.watten_rules import (
WATTEN_RANKS_32,
evaluate_trick_winner,
get_legal_cards_for_trick,
is_trump_card,
)
from models.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

View File

@ -0,0 +1,156 @@
# -*- coding: utf-8 -*-
# games/party/watten/models/watten_rules.py
from __future__ import annotations
from models.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)

View File

@ -0,0 +1,181 @@
# -*- coding: utf-8 -*-
# games/party/watten/models/watten_tutorials.py
from __future__ import annotations
from view.tutorial.tutorial_models import TutorialStep, TutorialUnit
def build_watten_tutorial_units() -> list[TutorialUnit]:
"""Liefert die 4 geführten Praxis-Lektionen für Oberbayerisches Watten."""
unit_1 = TutorialUnit(
unit_id="u1_basics_kritische",
title_key="wt_tut_u1_title",
subtitle_key="wt_tut_u1_sub",
badge_text="I",
steps=[
TutorialStep(
title_key="wt_tut_u1_s1_title",
body_key="wt_tut_u1_s1_body",
mode="info",
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
team_points=(0, 0),
current_stake=2,
),
TutorialStep(
title_key="wt_tut_u1_s2_title",
body_key="wt_tut_u1_s2_body",
mode="card",
my_hand=[("E", "A"), ("B", "10"), ("H", "K"), ("S", "7"), ("E", "7")],
highlight_cards=[("H", "K"), ("S", "7"), ("E", "7")],
allowed_cards=[("H", "K")],
wrong_hint_key="wt_tut_u1_s2_wrong",
),
TutorialStep(
title_key="wt_tut_u1_s3_title",
body_key="wt_tut_u1_s3_body",
mode="card",
my_hand=[("E", "A"), ("B", "10"), ("S", "7"), ("E", "7"), ("H", "9")],
trick_cards=[(1, "E", "7")],
allowed_cards=[("S", "7")],
schlag_rank="O",
trump_suit="B",
wrong_hint_key="wt_tut_u1_s3_wrong",
),
],
)
unit_2 = TutorialUnit(
unit_id="u2_schlag_trumpf_guade",
title_key="wt_tut_u2_title",
subtitle_key="wt_tut_u2_sub",
badge_text="II",
steps=[
TutorialStep(
title_key="wt_tut_u2_s1_title",
body_key="wt_tut_u2_s1_body",
mode="choice",
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
highlight_cards=[("B", "O"), ("E", "O")],
choices=[
("ask_o", "wt_tut_choice_ober", True),
("ask_8", "wt_tut_choice_acht", False),
],
wrong_hint_key="wt_tut_u2_s1_wrong",
),
TutorialStep(
title_key="wt_tut_u2_s2_title",
body_key="wt_tut_u2_s2_body",
mode="card",
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
highlight_cards=[("B", "O")],
allowed_cards=[("B", "O")],
schlag_rank="O",
trump_suit="B",
wrong_hint_key="wt_tut_u2_s2_wrong",
),
TutorialStep(
title_key="wt_tut_u2_s3_title",
body_key="wt_tut_u2_s3_body",
mode="info",
my_hand=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9"), ("H", "8")],
highlight_cards=[("B", "O"), ("E", "O"), ("B", "A"), ("B", "9")],
schlag_rank="O",
trump_suit="B",
),
],
)
unit_3 = TutorialUnit(
unit_id="u3_first_round_trumps",
title_key="wt_tut_u3_title",
subtitle_key="wt_tut_u3_sub",
badge_text="III",
steps=[
TutorialStep(
title_key="wt_tut_u3_s1_title",
body_key="wt_tut_u3_s1_body",
mode="card",
my_hand=[("E", "8"), ("E", "9"), ("H", "A"), ("B", "U"), ("S", "10")],
trick_cards=[(1, "E", "A"), (2, "H", "10"), (3, "E", "K")],
allowed_cards=[("B", "U")],
schlag_rank="10",
trump_suit="B",
wrong_hint_key="wt_tut_u3_s1_wrong",
),
TutorialStep(
title_key="wt_tut_u3_s2_title",
body_key="wt_tut_u3_s2_body",
mode="card",
my_hand=[("H", "8"), ("H", "9"), ("B", "8"), ("S", "A"), ("E", "K")],
trick_cards=[(1, "H", "O")],
allowed_cards=[("B", "8")],
schlag_rank="O",
trump_suit="B",
wrong_hint_key="wt_tut_u3_s2_wrong",
),
TutorialStep(
title_key="wt_tut_u3_s3_title",
body_key="wt_tut_u3_s3_body",
mode="card",
my_hand=[("H", "K"), ("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
trick_cards=[(1, "S", "O")],
allowed_cards=[("E", "8"), ("S", "9"), ("H", "10"), ("E", "U")],
highlight_cards=[("E", "8")],
schlag_rank="O",
trump_suit="B",
wrong_hint_key="wt_tut_u3_s3_wrong",
),
],
)
unit_4 = TutorialUnit(
unit_id="u4_ausschaffen_gespannt",
title_key="wt_tut_u4_title",
subtitle_key="wt_tut_u4_sub",
badge_text="IV",
steps=[
TutorialStep(
title_key="wt_tut_u4_s1_title",
body_key="wt_tut_u4_s1_body",
mode="choice",
my_hand=[("H", "K"), ("S", "7"), ("B", "O"), ("B", "A"), ("E", "A")],
highlight_cards=[("H", "K"), ("S", "7"), ("B", "O")],
schlag_rank="O",
trump_suit="B",
team_points=(4, 4),
current_stake=2,
choices=[
("raise", "wt_btn_ausschaffen_ tutorial", True),
("quiet", "wt_tut_choice_stay_2", False),
],
wrong_hint_key="wt_tut_u4_s1_wrong",
),
TutorialStep(
title_key="wt_tut_u4_s2_title",
body_key="wt_tut_u4_s2_body",
mode="choice",
my_hand=[("E", "8"), ("E", "9"), ("S", "8"), ("H", "7"), ("H", "9")],
schlag_rank="K",
trump_suit="B",
team_points=(6, 4),
current_stake=2,
choices=[
("fold", "wt_btn_fold_hand", True),
("hold", "wt_tut_choice_hold_bad", False),
],
wrong_hint_key="wt_tut_u4_s2_wrong",
),
TutorialStep(
title_key="wt_tut_u4_s3_title",
body_key="wt_tut_u4_s3_body",
mode="info",
my_hand=[("H", "K"), ("B", "A"), ("E", "10"), ("S", "O"), ("H", "A")],
schlag_rank="O",
trump_suit="B",
team_points=(9, 7),
current_stake=3,
),
],
)
return [unit_1, unit_2, unit_3, unit_4]

View File

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

View File

View File

@ -0,0 +1,351 @@
# -*- 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.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 Partner/Gegner, das Ansage- & Stichzentrum sowie die Spielerhand mit Rollen-Badges."""
@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 + 60, tx2 - 60
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))
# Sitz 1 = West (Gegner), Sitz 2 = Nord (Partner!), Sitz 3 = Ost (Gegner)
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_ph = view.ctx.assets.get_card_back_photo(
size=WT_BOT_BACK_SIZE, theme=BAVARIAN_CARD_THEME
)
if back_ph is not None:
view._photo_refs.append(back_ph)
name_sz = max(14, FONT_SIZE_BODY - 1)
sub_sz = max(12, FONT_SIZE_SMALL_MIN)
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:
step_b = 8
bx0 = bx - box_w // 2 + 12
by0 = by - WT_BOT_BACK_SIZE[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 + 28
max_tw = box_w - 92
else:
txt_cx = bx
max_tw = box_w - 24
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, sub_sz - 1, MUTED_FG, max_tw)
a_ph = view._make_goth_photo(act_txt, sub_sz, FG_COLOR, max_tw)
view._place_goth_photo_or_fallback(txt_cx, by - 23, n_ph, seat.name, name_sz, n_col)
view._place_goth_photo_or_fallback(txt_cx, by - 1, r_ph, role_line, sub_sz - 1, MUTED_FG)
view._place_goth_photo_or_fallback(txt_cx, by + 22, a_ph, act_txt, sub_sz, FG_COLOR)
return (top_cy + box_h // 2, left_cx + box_w // 2, right_cx - box_w // 2)
@staticmethod
def draw_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
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
center_cx = cw // 2
# 1. Ansage- & Stich-Infotafel oben links auf dem Tischfilz
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 "?"
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")
l1 = f"{t('wt_lbl_schlag')}: {schlag_txt}"
l2 = f"{t('wt_lbl_trumpf')}: {trump_txt}"
l3 = t("wt_lbl_tricks_pair", eng.team_tricks[0], eng.team_tricks[1])
for dy, txt, col in (
(-21, l1, ACCENT_GOLD),
(0, l2, FONT_COLOR_TITLE_MAIN),
(21, l3, 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)
# 2. Punktestand- & Einsatz-Tafel oben rechts auf dem Tischfilz
score_x = min(right_obs_x - 112, tx2 - 148)
score_y = felt_top + 42
gesp_0 = eng.is_team_gespannt(0)
gesp_1 = eng.is_team_gespannt(1)
view._draw_framed_panel(
score_x,
score_y,
206,
78,
frame_style="gold" if (gesp_0 or gesp_1) else "purple",
)
s1 = t("wt_lbl_match_pts", eng.team_points[0], eng.team_points[1])
s2 = t("wt_lbl_cur_stake", eng.current_stake)
s3 = (
t("wt_lbl_gespannt_warn")
if (gesp_0 or gesp_1)
else t("wt_lbl_target_11")
)
for dy, txt, col in (
(-21, s1, FONT_COLOR_TITLE_MAIN),
(0, s2, ACCENT_GOLD),
(21, s3, 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)
# 3. 4 Stich-Ablageplätze kreuzförmig in der Tischmitte (Süd=0, West=1, Nord=2, Ost=3)
tw, th = WT_TRICK_CARD_SIZE
slot_offsets = {
0: (0, 32), # Spieler (unten)
1: (-86, 0), # Gegner West (links)
2: (0, -32), # Partner Nord (oben)
3: (86, 0), # Gegner Ost (rechts)
}
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 - 64,
center_cy - 44,
center_cx + 64,
center_cy + 44,
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=WT_TRICK_CARD_SIZE, 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
border_w = 3 if seat_id == win_seat else 1
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=border_w,
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]
eff_top = max(230, player_zone_top - WT_HAND_TOP_EXTEND_PX)
avail_h = max(168, player_zone_bot - eff_top)
zone_cy = (eff_top + player_zone_bot) // 2
base_w, base_h = PLAYING_CARD_SIZE
target_h = max(116, min(WT_MAX_HAND_CARD_H, avail_h - 44))
scale = target_h / max(1, base_h)
card_w = max(78, int(round(base_w * scale)))
card_h = int(round(base_h * scale))
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()
n_cards = len(human.hand)
step = card_w + 14
span_w = card_w + max(0, n_cards - 1) * step if n_cards else card_w
my_role = ""
if eng.dealer_seat == 0:
my_role = f" ({t('wt_tag_dealer')})"
elif eng.ansager_seat == 0:
my_role = f" ({t('wt_tag_ansager')})"
lbl_txt = f"{t('wt_your_hand_lbl')}{my_role}"
lbl_sz = max(13, FONT_SIZE_BODY - 2)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, FONT_COLOR_TITLE_MAIN)
txt_w = lbl_ph.width() if lbl_ph is not None else 280
box_w = max(420, min(cw - 72, max(span_w + 80, txt_w + 68)))
box_h = min(avail_h + 6, card_h + 48)
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 - (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",
)
# Dezentes Rollen-Badge oben auf der Karte (Max, Belli, Spitz, Guade, Schlag, Trumpf)
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 + 4,
cy_top + card_h - 21,
cx_left + card_w - 4,
cy_top + card_h - 4,
fill="#0d0914",
outline=b_col,
width=1,
tags="fg",
)
view.arena_canvas.create_text(
cx_left + card_w // 2,
cy_top + card_h - 12,
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

View File

@ -0,0 +1,296 @@
# -*- 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.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.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.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
GAME_FOLDER_ID = "party/watten"
GAME_TITLE_KEY = "game_title_watten"
class WattenMenuView:
"""Vorauswahl-Menü für Oberbayerisches Watten inkl. interaktivem 4-Kapitel-Tutorial."""
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 = 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
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=226,
height=38,
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)
def_lvl = 2
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, def_lvl
entry = GothEntry(
cv,
self.ctx.assets,
width=230,
height=36,
textvariable=tk.StringVar(value=b_name),
)
l_var = tk.StringVar(value=t(f"bot_level_{b_lvl}"))
dd = GothDropdown(
cv,
self.ctx.assets,
values=ai_labels,
textvariable=l_var,
sound_mgr=self.ctx.sounds,
width=270,
height=36,
)
self._bot_entries.append(entry)
self._bot_lvl_vars.append(l_var)
self._bot_dds.append(dd)
def start_match():
bots = self._collect_and_save_bots()
WattenTableView(
self.ctx,
variant_key="watten_std",
bot_configs=bots,
on_back_to_menu=self.show,
)
start_btn = ImageButton(
cv,
t("wt_start_btn"),
btn_fire,
btn_fire,
start_match,
sound_mgr=self.ctx.sounds,
width=210,
height=40,
style="fire",
)
seat_role_keys = (
"wt_menu_seat_west", # idx 0 -> Sitz 1 (Gegner Links)
"wt_menu_seat_partner", # idx 1 -> Sitz 2 (Partner Oben!)
"wt_menu_seat_east", # idx 2 -> Sitz 3 (Gegner Rechts)
)
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(20, int(h * 0.045))
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("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() + 16
# 1. Regelwerk & Lehrmeister-Tutorial-Box
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 + 6, cur_y, image=s1_ph, anchor="nw", tags="fg")
cur_y += s1_ph.height() + 6
r_box_h = 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 - 285,
align="left",
)
self._photo_refs.extend([v_ph, d_ph])
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 + 16
# 2. Partner & Gegner konfigurieren
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 + 6, cur_y, image=s2_ph, anchor="nw", tags="fg")
cur_y += s2_ph.height() + 6
b_box_h = 236
b_cy = cur_y + b_box_h // 2
b_box = self.ctx.assets.get_box_photo("box_big", (box_w, b_box_h))
if b_box:
self._photo_refs.append(b_box)
cv.create_image(cx, b_cy, image=b_box, anchor="center", tags="fg")
dd_w = max(210, box_w - 460)
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")
cv.create_window(x_left + 168, ry, window=self._bot_entries[idx], anchor="w", tags="fg")
dd = self._bot_dds[idx]
if dd._width != dd_w:
dd._width = dd_w
dd.configure(width=dd_w)
dd._render_closed()
cv.create_window(x_left + 416, ry, window=dd, anchor="w", tags="fg")
cv.create_window(
x_left + box_w - 32, cur_y + b_box_h - 36, window=start_btn, anchor="e", tags="fg"
)
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))

View File

@ -0,0 +1,150 @@
# -*- coding: utf-8 -*-
# games/party/watten/views/watten_result_dialog.py
from __future__ import annotations
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
from view.widgets.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")

View File

@ -0,0 +1,565 @@
# -*- 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_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,
WattenEngine,
)
from games.party.watten.models.watten_rules import WATTEN_RANKS_32
from games.party.watten.views.watten_arena_renderer import WattenArenaRenderer
from games.party.watten.views.watten_result_dialog import WattenResultDialog
from models.bavarian_deck import BavarianCard
from models.progression import Progression
from resources.code_res.game_constants import (
BAVARIAN_SUITS,
WT_BOT_TURN_DELAY_MS,
WT_TRICK_CLEAR_DELAY_MS,
WT_VARIANTS,
)
from resources.code_res.i18n import t
from view.widgets.casino_arena_base import CasinoArenaBase
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "party/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)
# --- Steuerung & Phasen-Buttons für den menschlichen Spieler (Sitz 0) ---
def _sync_turn_controls(self):
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
return
eng = self.engine
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
if eng.phase == PHASE_MATCH_DONE:
self.status_var.set("")
self._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"
self.status_var.set(t(msg_key, eng.hand_points_awarded))
nxt_btn = ImageButton(
self.bottom_bar,
t("wt_btn_next_hand"),
btn_fire,
btn_fire,
self._start_next_hand,
sound_mgr=self.ctx.sounds,
width=188,
height=32,
style="fire",
)
self._set_bottom_buttons([nxt_btn], overflow_buttons=[self._menu_btn])
return
if self._visible_completed_trick or eng.turn_seat != 0:
if not self._visible_completed_trick:
actor = eng.seats[eng.turn_seat].name
self.status_var.set(t("wt_status_waiting_for", actor))
self._set_bottom_buttons([], overflow_buttons=[self._menu_btn])
return
# Menschlicher Spieler ist am Zug:
if eng.phase in (PHASE_SCHOENERE_ASK, PHASE_ANSAGE_SCHLAG):
self.status_var.set(t("wt_status_pick_schlag"))
rank_btns = [
ImageButton(
self.bottom_bar,
rk,
btn_norm,
btn_purp,
lambda r=rk: self._on_human_schlag(r),
sound_mgr=self.ctx.sounds,
width=54,
height=30,
style="amethyst",
)
for rk in WATTEN_RANKS_32
]
ovf = [self._menu_btn]
if eng.phase == PHASE_SCHOENERE_ASK:
ovf.insert(
0,
ImageButton(
self.bottom_bar,
t("wt_btn_ask_schoenere"),
btn_fire,
btn_fire,
self._on_human_ask_schoenere,
sound_mgr=self.ctx.sounds,
width=136,
height=30,
style="fire",
),
)
self._set_bottom_buttons(rank_btns, overflow_buttons=ovf)
return
if eng.phase == PHASE_SCHOENERE_REPLY:
self.status_var.set(t("wt_status_reply_schoenere", eng.seats[eng.ansager_seat].name))
b_yes = ImageButton(
self.bottom_bar, t("wt_btn_schoenere_yes"), btn_fire, btn_fire,
lambda: self._on_human_reply_schoenere(True),
sound_mgr=self.ctx.sounds, width=164, height=32, style="fire",
)
b_no = ImageButton(
self.bottom_bar, t("wt_btn_schoenere_no"), btn_norm, btn_purp,
lambda: self._on_human_reply_schoenere(False),
sound_mgr=self.ctx.sounds, width=164, height=32, style="amethyst",
)
self._set_bottom_buttons([b_yes, b_no], overflow_buttons=[self._menu_btn])
return
if eng.phase == PHASE_ANSAGE_TRUMPF:
self.status_var.set(t("wt_status_pick_trumpf", t(f"bav_rank_{eng.schlag_rank}")))
suit_btns = [
ImageButton(
self.bottom_bar,
t(f"bav_suit_{s}"),
btn_fire,
btn_fire,
lambda su=s: self._on_human_trumpf(su),
sound_mgr=self.ctx.sounds,
width=116,
height=32,
style="fire",
)
for s in BAVARIAN_SUITS
]
self._set_bottom_buttons(suit_btns, overflow_buttons=[self._menu_btn])
return
if eng.phase == PHASE_AUSSCHAFFEN_REPLY:
self.status_var.set(t("wt_status_opp_raised", eng.proposed_stake, eng.current_stake))
b_hold = ImageButton(
self.bottom_bar,
t("wt_btn_hold_stake", eng.proposed_stake),
btn_fire,
btn_fire,
lambda: self._on_human_reply_ausschaffen(True),
sound_mgr=self.ctx.sounds,
width=176,
height=32,
style="fire",
)
b_fold = ImageButton(
self.bottom_bar,
t("wt_btn_fold_hand"),
btn_norm,
btn_purp,
lambda: self._on_human_reply_ausschaffen(False),
sound_mgr=self.ctx.sounds,
width=168,
height=32,
style="amethyst",
)
self._set_bottom_buttons([b_hold, b_fold], overflow_buttons=[self._menu_btn])
return
if eng.phase == PHASE_TRICK_PLAY:
playable = eng.get_playable_cards(0)
if len(playable) < len(eng.seats[0].hand):
self.status_var.set(t("wt_status_trump_compulsion"))
else:
self.status_var.set(t("wt_status_your_turn_card"))
prim: list[ImageButton] = []
if eng.can_seat_ausschaffen(0):
prim.append(
ImageButton(
self.bottom_bar,
t("wt_btn_ausschaffen", eng.current_stake + 1),
btn_fire,
btn_fire,
self._on_human_ausschaffen,
sound_mgr=self.ctx.sounds,
width=186,
height=32,
style="fire",
)
)
self._set_bottom_buttons(prim, overflow_buttons=[self._menu_btn])
# --- Menschliche Klick-Aktionen ---
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
# --- Spielfluss & KI-Züge ---
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, self._execute_bot_step
)
def _execute_bot_step(self):
self._turn_job = None
if not self._canvas_alive() or self.engine.turn_seat == 0:
return
eng = self.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)
self._render_table()
self._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:
self.ctx.sounds.play("deal")
self._render_table()
self._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)
self.ctx.sounds.play("click")
self._render_table()
self._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)
self.ctx.sounds.play("click")
self._render_table()
self._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)
self.ctx.sounds.play("click" if hold else "stand")
self._render_table()
self._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)
self.ctx.sounds.play("stand")
self._render_table()
self._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)
self.ctx.sounds.play("click")
self._handle_post_card_play(res)
# --- Match-Abschluss & XP ---
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),
)

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,178 @@
# -*- coding: utf-8 -*-
# games/party/zehner_raus/views/zehner_raus_result_dialog.py
from __future__ import annotations
from resources.code_res.game_constants import (
BAVARIAN_CARD_THEME,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_SMALL_MIN,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
from view.widgets.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

View File

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

View File

@ -0,0 +1,324 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_arena_renderer.py
from __future__ import annotations
import tkinter as tk
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
ERROR_FG,
FG_COLOR,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
MUTED_FG,
PLAYING_CARD_SIZE,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from games.poker.models.poker_evaluator import PokerEvaluator
from models.database import Database
from models.progression import Progression
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 auf das Arena-Canvas."""
@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] + 24
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)
if show_bot_cards:
c_w, c_h = PK_BOT_SHOWDOWN_CARD
step_x = 22
fan_left, fan_top = bx - box_w // 2 + 16, 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=PK_BOT_SHOWDOWN_CARD)
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 + 4
view._place_goth_photo_or_fallback(txt_cx, by - 24, 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 + 24, st_ph, st_txt, sub_sz, st_col)
else:
view._place_goth_photo_or_fallback(bx, by - 23, title_ph, title_txt, name_sz, title_col)
view._place_goth_photo_or_fallback(bx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
view._place_goth_photo_or_fallback(bx, by + 23, st_ph, st_txt, sub_sz, st_col)
return top_center_bottom
@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
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(148, felt_bot - felt_top)
base_cw, base_ch = PK_OVAL_BOARD_CARD
scale = max(84, min(base_ch, avail_h - 58)) / max(1, base_ch)
card_w, card_h = max(58, int(round(base_cw * scale))), int(round(base_ch * scale))
card_sz = (card_w, card_h)
gap = max(8, int(card_w * 0.13))
start_x = t_cx - (5 * card_w + 4 * gap) // 2
board_cy = felt_top + card_h // 2 + max(4, (avail_h - card_h - 52) // 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 - 20, max(board_cy + card_h // 2 + 28, (board_cy + card_h // 2 + felt_bot) // 2))
pot_sz = max(15, FONT_SIZE_BODY)
pot_ph = view._make_goth_photo(pot_txt, pot_sz, FONT_COLOR_TITLE_MAIN)
if pot_ph is not None:
bw, bh = max(230, pot_ph.width() + 64), max(38, 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, 240, 38, 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
avail_h = max(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(88, min(base_h, avail_h - 52)) / max(1, base_h)
card_w, card_h = max(60, int(round(base_w * scale))), int(round(base_h * scale))
card_sz = (card_w, card_h)
p_photos = []
for card in human.hole_cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
p_photos.append(photo)
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(14, FONT_SIZE_BODY - 1)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
cards_gap = 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 250
box_w = max(300, min(540, max(cards_span_w + 96, txt_w + 72)))
box_h = min(avail_h, card_h + 52)
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 - 11) - 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 - 20, 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
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,
}

View File

@ -2,26 +2,9 @@
# games/poker/views/poker_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from games.poker.views.poker_stats_view import PokerStatsView
from games.poker.views.poker_table_view import PokerTableView
from view.widgets.menu_body_canvas import MenuBodyCanvas
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
DEVILS_DEAL_GOLD_REWARD,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_DISABLED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
GOLD_MAX_ACCOUNTS,
PK_MAX_BOTS,
PK_STARTING_GOLD,
@ -29,491 +12,71 @@ from resources.code_res.game_constants import (
XP_TO_GOLD_AMOUNT,
)
from resources.code_res.i18n import t
from view.widgets.bot_setup_widget import BotSetupWidget
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
GAME_FOLDER_ID = "poker"
class PokerMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
class PokerMenuView(LuckPouchMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
LAST_ACC_SETTING_PREFIX = "last_pk_account"
STARTING_GOLD = PK_STARTING_GOLD
MAX_BOTS = PK_MAX_BOTS
REQUIRES_MIN_ONE_BOT = True
DEVILS_DEFAULT_VARIANT = "poker_holdem"
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
KEY_TOPBAR = "pk_menu_topbar"
KEY_HEADER_GOLD = "pk_header_gold"
KEY_SEC1_TITLE = "pk_sec1_title"
KEY_BOTS_TITLE = "pk_bots_sec_title"
KEY_SEC3_TITLE = "pk_sec3_title"
KEY_GOLD_DISPLAY = "pk_gold_display_lbl"
KEY_DEFAULT_ACC_NAME = "pk_default_acc_name"
KEY_ERR_DUPLICATE = "pk_err_duplicate_name"
devils_acc = Database.get_active_devils_pk_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
if saved is not None:
PokerTableView(
self.ctx,
variant_key=saved["variant_key"],
pk_account_id=devils_acc["id"],
bot_configs=[],
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
resume_state_json=saved["state_json"],
)
return
def _default_bot_configs(self) -> dict[int, tuple[str, int]]:
return {
0: (t("bot_default_name", 1), 1),
1: (t("bot_default_name", 2), 2),
}
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pk_prog = self.ctx.refresh_game_progress()
def _get_active_devils_account(self, pid: int):
return Database.get_active_devils_pk_account(pid)
dyn_xp_cost = pk_prog["xp_exchange_cost"]
is_divine = pk_prog["is_divine_punishment"]
at_floor = pk_prog["at_divine_floor"]
devils_deal_open = pk_prog["devils_deal_unlocked"]
def _get_accounts(self, pid: int):
return Database.get_poker_accounts(pid)
setting_key = f"last_pk_account_{pid}"
accounts = Database.get_poker_accounts(pid)
has_accounts = len(accounts) > 0
def _get_account(self, acc_id: int):
return Database.get_poker_account(acc_id)
if preselect_id is None and has_accounts:
saved_id_str = Database.load_setting(setting_key, "")
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
def _create_account(self, pid: int, name: str):
return Database.create_poker_account(pid, name)
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
def _delete_account(self, acc_id: int):
Database.delete_poker_account(acc_id)
active_acc = None
if has_accounts:
active_acc = accounts[0]
if preselect_id is not None:
for a in accounts:
if a["id"] == preselect_id:
active_acc = a
break
Database.save_setting(setting_key, str(active_acc["id"]))
def _exchange_xp(self, pid: int, acc_id: int):
return Database.exchange_xp_for_pk_gold(pid, acc_id)
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
def _variants_dict(self) -> dict[str, dict]:
return PK_VARIANTS
def _min_entry_for_variant(self, _v_key: str, cfg: dict) -> int:
return cfg["min_entry"]
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
return t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"])
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 _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,
)
state_msg = {"text": status_msg, "ok": status_is_ok}
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
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 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("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()))

View File

@ -1,204 +1,129 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_result_dialog.py
import tkinter as tk
from __future__ import annotations
from models.card import Card
from resources.code_res.game_constants import (
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_SMALL_MIN,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
POPUP_GIF_SIZE = (145, 80)
POPUP_HOLE_CARD_SIZE = (48, 70)
POPUP_HOLE_CARD_SIZE = (46, 68)
POPUP_BOARD_CARD_SIZE = (44, 64)
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
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
)
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))
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
board_raw = self.data.get("board_cards", [])
if board_raw:
b_row = tk.Frame(reveal_box, bg=CELL_BG)
b_row.pack(pady=(0, 6))
tk.Label(
b_row, text=f"{t('pk_board_title')}:",
font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=CELL_BG
).pack(side="left", padx=(0, 8))
b_box_h = 76
b_cy = cur_y + b_box_h // 2
b_box = self.assets.get_box_photo("box_gold_double", (w - 56, b_box_h))
if b_box:
self._photo_refs.append(b_box)
self.create_image(cx, b_cy, image=b_box, anchor="center")
for s_suit, s_rank in board_raw:
c_obj = Card(s_suit, s_rank)
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_BOARD_CARD_SIZE)
if ph:
self._card_photos.append(ph)
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
seats_row.pack()
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
is_win = entry["is_winner"]
folded = entry["folded"]
border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a")
s_card = tk.Frame(
seats_row, bg="#191521", padx=8, pady=5,
highlightthickness=2 if is_win else 1, highlightbackground=border_c
lbl_ph = self.assets.get_goth_text_photo(
f"{t('pk_board_title')}:", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, align="left"
)
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
self._photo_refs.append(lbl_ph)
name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH)
tk.Label(
s_card, text=entry["name"],
font=("Georgia", 9, "bold"), fg=name_col, bg="#191521"
).pack()
c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2)
c_frame.pack(pady=3)
for s_suit, s_rank in entry["cards"]:
c_obj = Card(s_suit, s_rank)
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_HOLE_CARD_SIZE)
b_photos = []
for s_suit, s_rank in board_raw:
ph = self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_BOARD_CARD_SIZE)
if ph:
self._card_photos.append(ph)
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=1)
self._photo_refs.append(ph)
b_photos.append(ph)
combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR)
tk.Label(
s_card, text=entry["combo_text"],
font=("Helvetica", 8, "bold"), fg=combo_col, bg="#191521",
wraplength=112, justify="center"
).pack()
cw_b, ch_b = POPUP_BOARD_CARD_SIZE
cards_w = len(b_photos) * cw_b + max(0, len(b_photos) - 1) * 6
total_w = lbl_ph.width() + 14 + cards_w
start_x = cx - total_w // 2
# --- 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))
self.create_image(start_x, b_cy, image=lbl_ph, anchor="w")
cx_card = start_x + lbl_ph.width() + 14
for bph in b_photos:
self.create_image(cx_card, b_cy - ch_b // 2, image=bph, anchor="nw")
cx_card += cw_b + 6
p_net = self.data["player_net"]
if p_net > 0:
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
elif p_net < 0:
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
else:
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
cur_y += b_box_h + 8
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
seats = self.data.get("seat_showdown", [])
if not seats:
return cur_y
for extra_line in self.data.get("other_gains", []):
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
max_cols = 3
rows = (len(seats) + max_cols - 1) // max_cols
seat_w = min(244, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(seats))))
seat_h = 126 if rows > 1 else 132
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
if win_box:
self._photo_refs.append(win_box)
if std_box:
self._photo_refs.append(std_box)
tk.Label(
info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]),
font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG,
).pack(pady=1)
for idx, entry in enumerate(seats):
r_i, c_i = divmod(idx, max_cols)
in_row = min(max_cols, len(seats) - r_i * max_cols)
row_total_w = in_row * seat_w + (in_row - 1) * 10
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
if self.data.get("new_level_title"):
tk.Label(
info_box, text=self.data["new_level_title"],
font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=CELL_BG,
).pack(pady=(3, 0))
is_win, folded = entry["is_winner"], entry["folded"]
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
# --- Buttons ---
btn_row = tk.Frame(self, bg=MODAL_BG)
btn_row.pack(fill="x", pady=(4, 0))
n_col = FONT_COLOR_TITLE_MAIN if is_win else (FONT_COLOR_BODY_MUTED if folded else FONT_COLOR_HEADING_SUB)
n_ph = self.assets.get_goth_text_photo(entry["name"], FONT_SIZE_SMALL_MIN + 1, n_col, max_width=seat_w - 24)
self._photo_refs.append(n_ph)
self.create_image(sx, sy - seat_h // 2 + 19, image=n_ph, anchor="center")
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))
cw_h, ch_h = POPUP_HOLE_CARD_SIZE
h_photos = [
ph for s_suit, s_rank in entry["cards"]
if (ph := self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_HOLE_CARD_SIZE))
]
self._photo_refs.extend(h_photos)
if h_photos:
span_w = len(h_photos) * cw_h + max(0, len(h_photos) - 1) * 6
hx = sx - span_w // 2
for hph in h_photos:
self.create_image(hx, sy - ch_h // 2 + 1, image=hph, anchor="nw")
hx += cw_h + 6
if self.data.get("can_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")
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")
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()
return cur_y + rows * (seat_h + 6) + 6

View File

@ -1,132 +0,0 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_stats_view.py
from __future__ import annotations
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_HEADING_SUB,
FONT_SIZE_BODY,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from view.widgets.stats_board_widget import StatsBoardWidget
GAME_FOLDER_ID = "poker"
class PokerStatsView:
"""Rahmenlose Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
def __init__(self, context, on_back_to_pk_menu):
self.ctx = context
self.on_back_to_pk_menu = on_back_to_pk_menu
self._photo_refs: list = []
def show(self, selected_acc_id: int | None = None):
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pid = self.ctx.profile["id"]
accounts = Database.get_poker_accounts(pid)
if not accounts:
self.on_back_to_pk_menu(None)
return
active_acc = accounts[0]
if selected_acc_id is not None:
for a in accounts:
if a["id"] == selected_acc_id:
active_acc = a
break
self.ctx.build_game_topbar(
self.ctx.root,
t("pk_stats_view_topbar"),
on_game_menu=lambda: self.on_back_to_pk_menu(active_acc["id"]),
extra_right_text=t("pk_header_gold", active_acc["account_name"], active_acc["gold"]),
on_lang_refresh=lambda: self.show(active_acc["id"]),
)
cv = MenuBodyCanvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
acc_btns: list[tuple[ImageButton, int]] = []
for acc in accounts:
is_sel = (acc["id"] == active_acc["id"])
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
b = ImageButton(
cv,
btn_lbl,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
sound_mgr=self.ctx.sounds,
width=180,
height=38,
style="fire" if is_sel else "amethyst",
)
acc_btns.append((b, b.pixel_width))
pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
pk_filter_map = {t("pk_filter_all_tables"): None}
for v in pk_variants:
pk_filter_map[v["translated_name"]] = v["id"]
board = StatsBoardWidget(
cv,
title=t("bj_stats_acc_title", active_acc["account_name"]),
filter_map=pk_filter_map,
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid),
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1060, w - 2 * pad_x)
left_edge = (w - content_w) // 2
sel_h = 114
sel_top = max(24, int(h * 0.05))
sel_cy = sel_top + sel_h // 2
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
if sel_box:
self._photo_refs.append(sel_box)
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t("bj_stats_select_acc_lbl"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(lbl_ph)
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
cur_bx = left_edge + 26
for b_wgt, bw in acc_btns:
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
cur_bx += bw + 10
board_top = sel_top + sel_h + 22
board_h = max(238, min(270, h - board_top - 32))
cv.create_window(
w // 2,
board_top + board_h // 2,
window=board,
width=content_w,
height=board_h,
anchor="center",
tags="fg",
)
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,270 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_turn_driver.py
from __future__ import annotations
import time
from games.poker.models.poker_seat import PokerSeat
from games.poker.views.poker_arena_renderer import PokerArenaRenderer
from models.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.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,
)

View File

@ -2,60 +2,104 @@
# games/solitaire/base/card_animator.py
from __future__ import annotations
import random
import time
import tkinter as tk
from typing import Callable
from typing import Callable, Iterable
from PIL import Image, ImageTk
class CardFlightAnimator:
"""
Schneller, nicht-blockierender Canvas-Animator für gleitende Kartenbewegungen.
Nutzt Canvas-Tag-Verschiebung (canvas.move) ohne teures Neu-Rendern des Hintergrunds.
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 # ~70 FPS Zielrate auf Tkinter
FRAME_MS = 14
FALL_STEP_MS = 16
SHAKE_OFFSETS_PX: tuple[int, ...] = (-7, 7, -5, 5, -3, 3, 0)
SHAKE_STEP_MS = 26
def __init__(self, root: tk.Misc, canvas: tk.Canvas):
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 laufende Timer sofort ab (z. B. beim Schließen des Fensters)."""
"""Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab."""
if self._job is not None:
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
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 Animation sofort sauber im Zielzustand,
damit schnelle Klickfolgen des Spielers niemals ausgebremst werden.
"""
"""Beendet eine laufende Flug-Animation sofort sauber im Zielzustand."""
if not self.is_active:
return
cb = self._on_done
self.cancel()
if self._job is not None:
try:
self.root.after_cancel(self._job)
except Exception:
pass
self._job = None
if self._canvas_alive_safe():
self.canvas.delete("anim_flight")
self._flights.clear()
self._on_done = None
if callable(cb):
cb()
# ------------------------------------------------------------------
# 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste)
# ------------------------------------------------------------------
def start(
self,
flights: list[dict],
@ -63,29 +107,12 @@ class CardFlightAnimator:
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 not flights or not self._canvas_alive():
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):
@ -112,15 +139,15 @@ class CardFlightAnimator:
"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))))
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
@ -129,19 +156,13 @@ class CardFlightAnimator:
def _step(self):
self._job = None
try:
if not self.canvas.winfo_exists():
self._flights.clear()
self._on_done = None
return
except Exception:
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)))
# Cubic Ease-Out: spritziger Start, weiches Einrasten am Zielstapel
ease = 1.0 - ((1.0 - t_raw) ** 3)
for fl in self._flights:
@ -170,3 +191,162 @@ class CardFlightAnimator:
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)

View File

@ -0,0 +1,266 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/card_hover_zoom.py
from __future__ import annotations
import tkinter as tk
from typing import Callable
from games.solitaire.base.solitaire_card import SolitaireCard
from 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

View File

@ -0,0 +1,374 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_canvas_input.py
from __future__ import annotations
import time
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.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)

View File

@ -0,0 +1,417 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_menu_base.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
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,
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
class SolitaireMenuBase:
"""
Gemeinsame Vorauswahl-Menü-Basisklasse für alle Solitaire-Spiele
(Klondike, FreeCell, Spider, Pyramid, TriPeaks):
Kapselt Fortsetzen-Banner, Aufgabe-Bestätigung, Varianten-Toggles & Schwierigkeits-Auswahl.
"""
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=180, height=38, 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=self.TOGGLE_BTN_WIDTH, height=36,
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=420, height=40,
)
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()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(24, int(h * 0.055))
title_ph = self.ctx.assets.get_goth_text_photo(
t(self.GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, 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() + 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(
self._format_resume_info(saved, saved_meta),
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 = 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")
dsc_txt = t(f"{self.DESC_KEY_PREFIX}{selected_variant}")
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_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 + 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)
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)

View File

@ -15,12 +15,13 @@ from resources.code_res.game_constants import (
)
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.modal_veil import ModalVeil
class SolitaireModalDialog(tk.Canvas):
"""
Rahmenloses Gothic-Modal auf background_vertical.jpg + box_big.png
für Wiederaufnahme-, Aufgeben-, Deadlock- und Sieg-Dialoge (inkl. win.gif) in Solitaire.
Rahmenloses Gothic-Modal (ohne eingebettetes GIF), das über allen UI-Elementen
schwebt, das Spielfeld dahinter abdunkelt und alle übrigen Buttons sperrt.
"""
def __init__(
@ -30,12 +31,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 = "",
gif_key: str = "", # abwärtskompatibel ignoriert (Animation läuft vorab)
):
GothDropdown.close_any_open_popup()
frames = ctx.assets.get_gif_frames(gif_key, size=(150, 84)) if gif_key else []
_ = gif_key
dlg_w = 590 if len(buttons) >= 3 else 500
dlg_h = 355 if frames else 268
dlg_h = 268
super().__init__(
ctx.root,
@ -49,28 +50,10 @@ 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.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))
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)
def _build_scene(
self,
@ -78,7 +61,6 @@ 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
@ -94,15 +76,7 @@ class SolitaireModalDialog(tk.Canvas):
self._photo_refs.append(box_ph)
self.create_image(w // 2, h // 2, image=box_ph, anchor="center")
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
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)

View File

@ -0,0 +1,253 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_outcome_flow.py
from __future__ import annotations
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from models.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.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()

View File

@ -0,0 +1,243 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_session_guard.py
from __future__ import annotations
import tkinter as tk
from games.solitaire.base.solitaire_canvas_input import SolitaireCanvasInput
from models.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

View File

@ -1,215 +0,0 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_stats_view.py
from __future__ import annotations
from view.widgets.menu_body_canvas import MenuBodyCanvas
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
STAT_FIELD_KEYS,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
"klondike_1": "kl_draw_toggle_1",
"klondike_3": "kl_draw_toggle_3",
"spider_1suit": "sp_suit_toggle_1",
"spider_2suit": "sp_suit_toggle_2",
"spider_4suit": "sp_suit_toggle_4",
}
class SolitaireStatsView:
"""Rahmenlose Solitaire-Statistik-Ansicht mit direktem Varianten-Umschalter."""
def __init__(self, context, game_folder: str, game_title_key: str, on_back):
self.ctx = context
self.game_folder = game_folder
self.game_title_key = game_title_key
self.on_back = on_back
self._active_variant_id: int | None = None
self._photo_refs: list = []
def show(self, preselect_variant_id: int | None = None):
pid = self.ctx.profile["id"]
self._active_variant_id = preselect_variant_id
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
prog = Database.get_game_progress(pid, self.game_folder)
game_name = t(self.game_title_key)
self.ctx.build_game_topbar(
self.ctx.root,
t("stats_view_topbar", game_name),
on_game_menu=self.on_back,
on_stats=None,
stats_enabled=False,
on_lang_refresh=lambda: self.show(preselect_variant_id=self._active_variant_id),
)
cv = MenuBodyCanvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
variants = Database.get_variants_for_filter(self.game_folder)
tab_btns: list[tuple[ImageButton, int]] = []
if len(variants) > 1:
tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
for v in variants:
v_key = v["variant_key"]
short_lbl = (
t(SHORT_VARIANT_TAB_KEYS[v_key])
if v_key in SHORT_VARIANT_TAB_KEYS
else v["translated_name"]
)
tabs.append((v["id"], short_lbl))
for vid, tab_text in tabs:
is_sel = (self._active_variant_id == vid)
bw = 118 if vid is None else 156
b = ImageButton(
cv,
tab_text,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda target_vid=vid: self._switch_tab(target_vid),
sound_mgr=self.ctx.sounds,
width=bw,
height=36,
style="fire" if is_sel else "amethyst",
)
tab_btns.append((b, bw))
active_title = t("stats_all_variants_of_game", game_name)
for v in variants:
if v["id"] == self._active_variant_id:
active_title = v["translated_name"]
break
stats = Database.get_stats_overview(
pid,
variant_id=self._active_variant_id,
folder_path=self.game_folder if self._active_variant_id is None else None,
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1020, w - 2 * pad_x)
left_x = (w - content_w) // 2
# 1. Obere Rang- & Umschalter-Box in box_gold_double
hdr_h = 74
hdr_top = max(24, int(h * 0.05))
hdr_cy = hdr_top + hdr_h // 2
hdr_box = self.ctx.assets.get_box_photo("box_gold_double", (content_w, hdr_h))
if hdr_box:
self._photo_refs.append(hdr_box)
cv.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg")
tabs_total_w = sum(bw + 8 for _, bw in tab_btns)
rank_ph = self.ctx.assets.get_goth_text_photo(
t(
"stats_game_rank_info",
game_name,
prog["title"],
prog["level"],
prog["current_xp"],
prog["needed_xp"],
),
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_TITLE_MAIN,
max_width=max(200, content_w - tabs_total_w - 64),
align="left",
)
self._photo_refs.append(rank_ph)
cv.create_image(left_x + 26, hdr_cy, image=rank_ph, anchor="w", tags="fg")
rx = left_x + content_w - 24
for b_wgt, bw in reversed(tab_btns):
cv.create_window(rx, hdr_cy, window=b_wgt, anchor="e", tags="fg")
rx -= (bw + 8)
# 2. Haupttafel in box_big mit 2x4 box_purple Zellen
board_top = hdr_top + hdr_h + 18
board_h = max(260, min(330, h - board_top - 32))
board_cy = board_top + board_h // 2
outer_box = self.ctx.assets.get_box_photo("box_big", (content_w, board_h))
if outer_box:
self._photo_refs.append(outer_box)
cv.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg")
sub_ph = self.ctx.assets.get_goth_text_photo(
t("stats_game_board_title", active_title),
size_px=FONT_SIZE_HEADING - 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(sub_ph)
cv.create_image(left_x + 28, board_top + 34, image=sub_ph, anchor="w", tags="fg")
grid_top = board_top + 66
grid_h = board_h - 88
cols, rows = 4, 2
gap_x, gap_y = 14, 12
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
cell_h = (grid_h - (rows - 1) * gap_y) // rows
cell_frame = self.ctx.assets.get_box_photo("box_purple", (cell_w, cell_h))
if cell_frame:
self._photo_refs.append(cell_frame)
for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS):
r, c = divmod(idx, cols)
cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2
cy = grid_top + r * (cell_h + gap_y) + cell_h // 2
if cell_frame:
cv.create_image(cx, cy, image=cell_frame, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t(label_i18n_key), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=cell_w - 24, align="center",
)
if field_key == "won":
v_col = FONT_COLOR_STATUS_WIN
elif field_key == "lost":
v_col = FONT_COLOR_STATUS_LOSS
elif "streak" in field_key or field_key == "win_pct":
v_col = FONT_COLOR_HEADING_SUB
else:
v_col = FONT_COLOR_BODY_DEFAULT
val_ph = self.ctx.assets.get_goth_text_photo(
str(stats.get(field_key, "--")), FONT_SIZE_HEADING - 2, v_col,
max_width=cell_w - 24, align="center",
)
self._photo_refs.extend([lbl_ph, val_ph])
cv.create_image(cx, cy - cell_h // 4 + 2, image=lbl_ph, anchor="center", tags="fg")
cv.create_image(cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", tags="fg")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))
def _switch_tab(self, variant_id: int | None):
if variant_id == self._active_variant_id:
return
self.show(preselect_variant_id=variant_id)

View File

@ -0,0 +1,387 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_table_controller.py
from __future__ import annotations
import tkinter as tk
from games.solitaire.base.card_animator import CardFlightAnimator
from games.solitaire.base.card_hover_zoom import CardHoverZoom
from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_outcome_flow import SolitaireOutcomeFlow
from games.solitaire.base.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.endgame_fx_overlay import EndgameFxOverlay
from view.widgets.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 = SolitaireBottomBar(
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

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_tap_prefs.py
from __future__ import annotations
from models.database import Database
TAP_TO_MOVE_SETTING_KEY = "sol_single_tap_to_move"
SINGLE_TAP_MAX_HOLD_SEC = 0.28
_single_tap_cache: bool | None = None
def 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

View File

@ -2,110 +2,90 @@
# games/solitaire/base/solitaire_theme.py
from __future__ import annotations
import warnings
from pathlib import Path
import tkinter as tk
import warnings
from PIL import Image, ImageChops, ImageDraw, ImageTk
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
def _pick_largest_rgba_frame(candidates, loader_fn) -> Image.Image | None:
best_img: Image.Image | None = None
best_area = -1
for item in candidates:
try:
frame = loader_fn(item).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
return best_img
def extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
"""Liest den höchstauflösenden RGBA-Frame aus einer .ico-Datei."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
best_img = None
best_area = -1
ico_helper = getattr(ico, "ico", None)
best_img = None
if ico_helper is not None and hasattr(ico_helper, "sizes"):
for sz in ico_helper.sizes():
try:
frame = ico_helper.getimage(sz).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
if best_img is None:
for idx in range(getattr(ico, "n_frames", 1)):
try:
ico.seek(idx)
frame = ico.copy().convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
best_img = _pick_largest_rgba_frame(
range(getattr(ico, "n_frames", 1)),
lambda idx: (ico.seek(idx), ico.copy())[1],
)
return best_img if best_img is not None else ico.convert("RGBA")
except Exception:
return None
def _scan_badge_axis(primary_len: int, secondary_len: int, probe_pixel_fn) -> list[int]:
min_span = int(secondary_len * 0.38)
valid: list[int] = []
for p in range(primary_len):
cnt = sum(2 for s in range(0, secondary_len, 2) if probe_pixel_fn(p, s))
if cnt >= min_span:
valid.append(p)
return valid
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
"""
Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben)
ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus.
"""
w, h = img.size
px = img.load()
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
if a < 40:
return False
# Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren
if r > 228 and g > 228 and b > 228:
return False
return True
return a >= 40 and not (r > 228 and g > 228 and b > 228)
# Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks
# (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!)
min_row_span = int(w * 0.38)
valid_rows: list[int] = []
for y in range(h):
cnt = 0
for x in range(0, w, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_row_span:
valid_rows.append(y)
valid_rows = _scan_badge_axis(h, w, lambda y, x: is_badge_pixel(*px[x, y]))
valid_cols = _scan_badge_axis(w, h, lambda x, y: is_badge_pixel(*px[x, y]))
min_col_span = int(h * 0.38)
valid_cols: list[int] = []
for x in range(w):
cnt = 0
for y in range(0, h, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_col_span:
valid_cols.append(x)
cropped = (
img.crop((valid_cols[0], valid_rows[0], valid_cols[-1] + 1, valid_rows[-1] + 1))
if (valid_rows and valid_cols)
else img
)
if valid_rows and valid_cols:
top, bottom = valid_rows[0], valid_rows[-1] + 1
left, right = valid_cols[0], valid_cols[-1] + 1
cropped = img.crop((left, top, right, bottom))
else:
cropped = img
# Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren
side = max(cropped.width, cropped.height)
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
mask_big = Image.new("L", (side * 2, side * 2), 0)
draw = ImageDraw.Draw(mask_big)
radius = int(side * 2 * 0.195)
pad = int(side * 2 * 0.008)
draw.rounded_rectangle(
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
radius=radius,
radius=int(side * 2 * 0.195),
fill=255,
)
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
r_ch, g_ch, b_ch, a_ch = square.split()
square.putalpha(ImageChops.multiply(a_ch, mask))
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
return square
@ -119,24 +99,19 @@ def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk
return _ICON_TK_CACHE[cache_key]
if icon_path not in _ICON_PIL_CACHE:
raw = _extract_best_ico_pil(icon_path)
raw = extract_best_ico_pil(icon_path)
if raw is None:
return None
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(resized)
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
_ICON_TK_CACHE[cache_key] = photo
return photo
class SolitaireTableBgRenderer:
"""
Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas
und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen.
"""
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
# Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen)
FRAME_X_RATIO = 0.075
FRAME_TOP_RATIO = 0.095
FRAME_BOT_RATIO = 0.090
@ -145,8 +120,7 @@ class SolitaireTableBgRenderer:
self.res_mgr = res_mgr
self._raw_pil: Image.Image | None = None
self._loaded = False
self._cached_size: tuple[int, int] = (0, 0)
self._cached_photo: ImageTk.PhotoImage | None = None
self._slice_photo: ImageTk.PhotoImage | None = None
def _ensure_pil(self) -> Image.Image | None:
if not self._loaded:
@ -161,13 +135,13 @@ class SolitaireTableBgRenderer:
return self._raw_pil
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
if self._ensure_pil() is None:
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
ix = max(36, int(canvas_w * self.FRAME_X_RATIO))
itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO))
ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO))
return ix, itop, ibot
return (
max(36, int(canvas_w * self.FRAME_X_RATIO)),
max(28, int(canvas_h * self.FRAME_TOP_RATIO)),
max(26, int(canvas_h * self.FRAME_BOT_RATIO)),
)
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
if canvas_w < 80 or canvas_h < 80:
@ -177,8 +151,7 @@ class SolitaireTableBgRenderer:
if assets is None:
return
rw = max(canvas_w, root.winfo_width())
rh = max(canvas_h, root.winfo_height())
rw, rh = max(canvas_w, root.winfo_width()), max(canvas_h, root.winfo_height())
ox = max(0, min(rw - canvas_w, canvas.winfo_rootx() - root.winfo_rootx()))
oy = max(0, min(rh - canvas_h, canvas.winfo_rooty() - root.winfo_rooty()))
new_photo = assets.get_bg_patch_photo(rw, rh, ox, oy, canvas_w, canvas_h)

View File

@ -1,178 +0,0 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_victory_dialog.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_TITLE_LG,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
class SolitaireVictoryDialog(tk.Canvas):
"""
Rahmenloses Gothic-Sieg-Overlay für Solitaire auf background_vertical.jpg + box_big.png
mit animiertem win_gif und PIL-Old-London-Typografie.
"""
DLG_W = 500
DLG_H = 365
def __init__(
self,
ctx,
score: int,
moves: int,
dur: float,
difficulty: int,
xp_earned: int,
old_lvl: int,
new_lvl: int,
on_play_again,
on_to_menu,
):
GothDropdown.close_any_open_popup()
super().__init__(
ctx.root,
width=self.DLG_W,
height=self.DLG_H,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
self.ctx = ctx
self._photo_refs: list[ImageTk.PhotoImage] = []
self._gif_job: str | None = None
self._gif_item: int | None = None
self.place(relx=0.5, rely=0.52, anchor="center")
self.bind("<Destroy>", self._on_destroy)
self._build_scene(
score, moves, dur, difficulty, xp_earned, old_lvl, new_lvl, on_play_again, on_to_menu
)
def _on_destroy(self, _event=None):
if self._gif_job is not None:
try:
self.after_cancel(self._gif_job)
except Exception:
pass
self._gif_job = None
def _build_scene(
self,
score: int,
moves: int,
dur: float,
difficulty: int,
xp_earned: int,
old_lvl: int,
new_lvl: int,
on_play_again,
on_to_menu,
):
w, h = self.DLG_W, self.DLG_H
cx = w // 2
assets = self.ctx.assets
bg_src = assets.raw_bg_vertical or assets.raw_bg_horizontal or assets.raw_bg
if bg_src is not None:
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
self._photo_refs.append(bg_ph)
self.create_image(0, 0, image=bg_ph, anchor="nw")
box_ph = assets.get_box_photo("box_big", (w - 6, h - 6))
if box_ph:
self._photo_refs.append(box_ph)
self.create_image(cx, h // 2, image=box_ph, anchor="center")
cur_y = 26
frames = assets.get_gif_frames("win_gif", size=(155, 86))
if frames:
self._gif_item = self.create_image(cx, cur_y + 43, image=frames[0], anchor="center")
cur_y += 96
if len(frames) > 1:
self._step_gif(frames, 0)
else:
cur_y += 18
t_ph = assets.get_goth_text_photo(
t("sol_win_title"), FONT_SIZE_TITLE_LG - 2, FONT_COLOR_TITLE_MAIN, max_width=w - 60
)
self._photo_refs.append(t_ph)
self.create_image(cx, cur_y + t_ph.height() // 2, image=t_ph, anchor="center")
cur_y += t_ph.height() + 10
sum_txt = t(
"sol_win_summary",
score,
moves,
Database.format_seconds(dur),
t(f"sol_diff_short_{difficulty}"),
).replace("•", "-")
s_ph = assets.get_goth_text_photo(
sum_txt, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=w - 68
)
self._photo_refs.append(s_ph)
self.create_image(cx, cur_y + s_ph.height() // 2, image=s_ph, anchor="center")
cur_y += s_ph.height() + 10
xp_ph = assets.get_goth_text_photo(
t("bj_popup_xp_earned", xp_earned), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, max_width=w - 68
)
self._photo_refs.append(xp_ph)
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
cur_y += xp_ph.height() + 8
if new_lvl > old_lvl:
lvl_ph = assets.get_goth_text_photo(
t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)),
FONT_SIZE_BODY + 1,
FONT_COLOR_STATUS_WIN,
max_width=w - 64,
)
self._photo_refs.append(lvl_ph)
self.create_image(cx, cur_y + lvl_ph.height() // 2, image=lvl_ph, anchor="center")
btn_norm = assets.raw_btn_default
btn_purp = assets.raw_btn_purple
btn_fire = assets.raw_btn_fire or btn_purp
b_again = ImageButton(
self, t("sol_play_again_btn"), btn_fire, btn_fire,
on_play_again, sound_mgr=self.ctx.sounds, width=178, height=38, style="fire"
)
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
on_to_menu, sound_mgr=self.ctx.sounds, width=178, height=38, style="amethyst"
)
gap = 12
tot_w = b_again.pixel_width + b_menu.pixel_width + gap
sx = (w - tot_w) // 2
self.create_window(sx + b_again.pixel_width // 2, h - 44, window=b_again, anchor="center")
self.create_window(
sx + b_again.pixel_width + gap + b_menu.pixel_width // 2,
h - 44,
window=b_menu,
anchor="center",
)
def _step_gif(self, frames: list, idx: int):
if not self.winfo_exists() or self._gif_item is None:
return
self.itemconfigure(self._gif_item, image=frames[idx % len(frames)])
self._gif_job = self.after(90, self._step_gif, frames, (idx + 1) % len(frames))

View File

@ -2,402 +2,38 @@
# games/solitaire/freecell/views/freecell_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
FREECELL_VARIANTS,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import FREECELL_VARIANTS
GAME_FOLDER_ID = "solitaire/freecell"
GAME_TITLE_KEY = "game_title_freecell"
DEFAULT_VARIANT_KEY = "freecell_std"
class FreeCellMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class FreeCellMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "fc_menu_topbar"
SUBTITLE_KEY = "fc_menu_subtitle"
CONTROLS_HINT_KEY = "fc_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "freecell_diff"
DEFAULT_VARIANT_KEY = "freecell_std"
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "fc_variant_info_lbl"
DESC_KEY_PREFIX = "fc_desc_"
diff_setting_key = f"freecell_diff_{pid}"
saved_diff_str = Database.load_setting(diff_setting_key, "1")
selected_diff = (
int(saved_diff_str)
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
else 1
)
def _variants_dict(self) -> dict[str, dict]:
return FREECELL_VARIANTS
def open_stats():
self._clear_modal()
SolitaireStatsView(
self.ctx,
game_folder=GAME_FOLDER_ID,
game_title_key=GAME_TITLE_KEY,
on_back=lambda: self.show(),
).show()
self.ctx.build_game_topbar(
self.ctx.root,
t("fc_menu_topbar"),
on_game_menu=None,
on_stats=open_stats,
stats_enabled=True,
extra_right_text="",
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = MenuBodyCanvas(self.ctx)
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
saved_meta = self._parse_saved_meta(saved)
resume_btn = None
if saved and saved_meta is not None:
resume_btn = ImageButton(
cv,
t("sol_resume_btn"),
btn_fire,
btn_fire,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds,
width=180,
height=38,
style="fire",
)
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_dd = GothDropdown(
cv,
self.ctx.assets,
values=diff_labels,
textvariable=diff_var,
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
sound_mgr=self.ctx.sounds,
width=420,
height=40,
)
start_btn = ImageButton(
cv,
t("sol_start_btn"),
btn_fire,
btn_fire,
lambda: self._on_start_clicked(
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds,
width=205,
height=40,
style="fire",
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(26, int(h * 0.06))
title_ph = self.ctx.assets.get_goth_text_photo(
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
)
sub_ph = self.ctx.assets.get_goth_text_photo(
t("fc_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.extend([title_ph, sub_ph])
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
cur_y += title_ph.height() + 4
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
cur_y += sub_ph.height() + 14
if status_msg:
st_ph = self.ctx.assets.get_goth_text_photo(
status_msg,
FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
max_width=box_w,
align="left",
)
self._photo_refs.append(st_ph)
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
cur_y += st_ph.height() + 12
if saved and saved_meta is not None and resume_btn is not None:
res_h = 84
res_cy = cur_y + res_h // 2
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
if r_box:
self._photo_refs.append(r_box)
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
rt_ph = self.ctx.assets.get_goth_text_photo(
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
ri_ph = self.ctx.assets.get_goth_text_photo(
t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
FONT_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT,
max_width=box_w - resume_btn.pixel_width - 70,
align="left",
)
self._photo_refs.extend([rt_ph, ri_ph])
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
cur_y += res_h + 18
sec_ph = self.ctx.assets.get_goth_text_photo(
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(sec_ph)
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
cur_y += sec_ph.height() + 8
setup_h = 208
setup_cy = cur_y + setup_h // 2
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
if s_box:
self._photo_refs.append(s_box)
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
lbl_col = x_left + 32
val_col = x_left + 225
# Zeile 1: Modus
r1_y = cur_y + 44
m_lbl = self.ctx.assets.get_goth_text_photo(
t("fc_variant_info_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
m_val = self.ctx.assets.get_goth_text_photo(
t("variant_freecell_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
m_dsc = self.ctx.assets.get_goth_text_photo(
t("fc_desc_freecell_std"),
FONT_SIZE_SMALL_MIN,
FONT_COLOR_BODY_MUTED,
max_width=max(180, box_w - 275 - m_val.width()),
align="left",
)
self._photo_refs.extend([m_lbl, m_val, m_dsc])
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
cv.create_image(val_col, r1_y, image=m_val, anchor="w", tags="fg")
cv.create_image(val_col + m_val.width() + 18, r1_y, image=m_dsc, anchor="w", tags="fg")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 104
d_lbl = self.ctx.assets.get_goth_text_photo(
t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
self._photo_refs.append(d_lbl)
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
dd_w = max(240, box_w - 265)
if diff_dd._width != dd_w:
diff_dd._width = dd_w
diff_dd.configure(width=dd_w)
diff_dd._render_closed()
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
# Zeile 3: Start
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
hint_ph = self.ctx.assets.get_goth_text_photo(
t("fc_controls_hint"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.append(hint_ph)
cv.create_image(x_left + 6, cur_y + setup_h + 14, image=hint_ph, anchor="nw", tags="fg")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@staticmethod
def _parse_saved_meta(saved: dict | None) -> dict | None:
if not saved:
return None
try:
data = json.loads(saved["state_json"])
if data.get("won"):
return None
board = data.get("board", {})
if not board or "tableau" not in board or "freecells" not in board:
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", 0)),
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
}
except Exception:
return None
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
def resume_now(_event=None):
self._clear_modal()
self._resume_saved(saved, saved_meta["difficulty"])
try:
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
except tk.TclError:
self._return_bind_id = None
info_txt = t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
)
self._modal_overlay = SolitaireModalDialog(
self.ctx,
title_txt=t("sol_resume_box_title"),
body_txt=info_txt,
buttons=[
(t("sol_resume_btn"), "fire", resume_now),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
FreeCellTableView(
self.ctx,
variant_key=saved["variant_key"],
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=saved["state_json"],
)
def _on_start_clicked(
self,
variant_key: str,
difficulty: int,
saved: dict | None,
saved_meta: dict | None,
):
if self._modal_overlay is not None:
return
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
self._launch_fresh_game(variant_key, difficulty)
def _show_overwrite_confirm_modal(
self,
new_variant_key: str,
new_difficulty: int,
saved: dict,
saved_meta: dict,
):
pid = self.ctx.profile["id"]
old_v = saved["variant_key"]
old_diff = saved_meta["difficulty"]
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
v_mult = FREECELL_VARIANTS.get(old_v, {"xp_mult": 1.15})["xp_mult"]
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
def forfeit_and_start():
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
Database.record_game_result(
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
)
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
self.ctx.refresh_game_progress()
self._clear_modal()
self._launch_fresh_game(new_variant_key, new_difficulty)
self._modal_overlay = SolitaireModalDialog(
self.ctx,
title_txt=t("sol_forfeit_title"),
body_txt=t("sol_forfeit_desc", penalty),
is_danger=True,
buttons=[
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]
Database.save_setting(f"freecell_diff_{pid}", str(difficulty))
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
FreeCellTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

File diff suppressed because it is too large Load Diff

View File

@ -7,17 +7,13 @@ from games.solitaire.base.solitaire_core import (
SolitaireCard,
is_alternating_descending,
)
from games.solitaire.klondike.models.klondike_hint_analyzer import KlondikeHintAnalyzer
from games.solitaire.klondike.models.klondike_solver import generate_solvable_klondike_deck
from resources.code_res.game_constants import SOLITAIRE_DIFFICULTIES, SUITS
class KlondikeEngine(SolitaireBaseEngine):
"""
Klondike-Spiellogik (Draw 1 & Draw 3) mit:
- garantierter Lösbarkeit
- 3-Zyklen-Stagnationssperre auf dem Stock (rotes X, per Undo auflösbar)
- automatischer Sackgassen-Erkennung (has_any_meaningful_move)
"""
"""Klondike-Spiellogik (Draw 1 & Draw 3) mit garantierter Lösbarkeit & Stagnationssperre."""
NUM_TABLEAU = 7
NUM_FOUNDATIONS = 4
@ -37,8 +33,6 @@ class KlondikeEngine(SolitaireBaseEngine):
self.seed: int | None = seed
self.redeals_used: int = 0
self.redeal_limit: int | None = None
# Zählt volle Stock-Durchläufe ohne jeglichen Spielfortschritt
self.stagnant_cycles: int = 0
self.progress_in_current_cycle: bool = False
@ -96,7 +90,6 @@ class KlondikeEngine(SolitaireBaseEngine):
self.capture_initial_state()
def _mark_board_progress(self):
"""Sobald eine Karte auf dem Spielfeld bewegt wird, wird der Stagnationszähler zurückgesetzt."""
self.stagnant_cycles = 0
self.progress_in_current_cycle = True
@ -117,20 +110,16 @@ class KlondikeEngine(SolitaireBaseEngine):
return True
return False
# --- Regel-Prüfungen ---
def foundation_index_for_suit(self, suit: str) -> int:
return SUITS.index(suit)
def can_move_to_foundation(self, card: SolitaireCard, found_idx: int) -> bool:
if not card.face_up or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
target_suit = SUITS[found_idx]
if card.suit != target_suit:
if card.suit != SUITS[found_idx]:
return False
pile = self.foundations[found_idx]
if not pile:
return card.value == 1
return card.value == pile[-1].value + 1
return (card.value == 1) if not pile else (card.value == pile[-1].value + 1)
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
@ -144,9 +133,7 @@ class KlondikeEngine(SolitaireBaseEngine):
top = dst[-1]
return top.face_up and (top.is_red != head.is_red) and (top.value == head.value + 1)
# --- Stock, Redeal-Limit & 3-Zyklen-Stagnationssperre ---
def is_stagnation_locked(self) -> bool:
"""True, wenn 3 volle Durchläufe des Decks ohne jede Änderung erfolgt sind."""
return (
not self.stock
and bool(self.waste)
@ -162,15 +149,10 @@ class KlondikeEngine(SolitaireBaseEngine):
)
def is_stock_locked(self) -> bool:
"""True, wenn der Stapel nicht mehr neu umgedreht werden darf (Rotes X)."""
return self.is_stagnation_locked() or self.is_redeal_exhausted()
def can_draw_or_recycle(self) -> bool:
if self.stock:
return True
if self.waste and not self.is_stock_locked():
return True
return False
return bool(self.stock) or (bool(self.waste) and not self.is_stock_locked())
def draw_from_stock(self) -> bool:
if self.won:
@ -183,9 +165,6 @@ class KlondikeEngine(SolitaireBaseEngine):
card.face_up = True
self.waste.append(card)
self.moves += 1
# Wenn gerade die letzte Karte eines kompletten ereignislosen Durchlaufs aufgedeckt wurde,
# zählt dieser Zyklus als abgeschlossen -> beim 3. Mal erscheint sofort das rote X!
if not self.stock and not self.progress_in_current_cycle:
self.stagnant_cycles += 1
return True
@ -204,10 +183,8 @@ class KlondikeEngine(SolitaireBaseEngine):
elif self.redeals_used > 3:
self._add_score(self.SCORE_RECYCLE_DRAW3)
return True
return False
# --- Aktionen: Kartenverschiebungen ---
def move_waste_to_foundation(self, found_idx: int | None = None) -> bool:
if self.won or not self.waste:
return False
@ -283,21 +260,17 @@ class KlondikeEngine(SolitaireBaseEngine):
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
f_pile = self.foundations[found_idx]
if not f_pile:
return False
card = f_pile[-1]
if not self.can_move_to_tableau([card], dst_col):
if not f_pile or not self.can_move_to_tableau([f_pile[-1]], dst_col):
return False
self.push_undo()
f_pile.pop()
card = f_pile.pop()
self.tableau[dst_col].append(card)
self.moves += 1
self._mark_board_progress()
self._add_score(self.SCORE_FOUNDATION_TO_TABLEAU)
return True
# --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung ---
def can_auto_complete(self) -> bool:
if self.won or self.stock or self.waste:
return False
@ -306,7 +279,6 @@ class KlondikeEngine(SolitaireBaseEngine):
def auto_complete_step(self, record_undo: bool = False) -> tuple[int, int] | None:
if self.won:
return None
candidates: list[tuple[int, int, int]] = []
for col_idx, col in enumerate(self.tableau):
if not col:
@ -315,7 +287,6 @@ class KlondikeEngine(SolitaireBaseEngine):
f_idx = self.foundation_index_for_suit(card.suit)
if self.can_move_to_foundation(card, f_idx):
candidates.append((card.value, col_idx, f_idx))
if not candidates:
return None
@ -332,166 +303,12 @@ class KlondikeEngine(SolitaireBaseEngine):
self._check_victory()
return best_col, best_f_idx
def _card_can_play_anywhere(self, card: SolitaireCard) -> bool:
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
if self.can_move_to_foundation(probe, self.foundation_index_for_suit(probe.suit)):
return True
return any(self.can_move_to_tableau([probe], dst_col) for dst_col in range(self.NUM_TABLEAU))
def _reachable_stock_waste_cards(self) -> list[SolitaireCard]:
"""Ermittelt alle Karten, die durch Ziehen/Recyclen aktuell noch oben auf dem Waste landen können."""
reachable: list[SolitaireCard] = []
if self.waste:
reachable.append(self.waste[-1])
# 1. Restlichen aktuellen Stock in draw_count-Schritten simulieren
if self.stock:
sim_stk = list(self.stock)
while sim_stk:
step = min(self.draw_count, len(sim_stk))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk.pop()
if top_drawn is not None:
reachable.append(top_drawn)
# 2. Falls danach noch ein Recycle erlaubt wäre, auch den nächsten Zyklus prüfen
will_lock_after_stock = (
bool(self.stock)
and (not self.progress_in_current_cycle)
and (self.stagnant_cycles + 1 >= self.MAX_STAGNANT_CYCLES)
)
can_recycle_next = (
not self.is_stock_locked()
and not will_lock_after_stock
and (self.redeal_limit is None or self.redeals_used < self.redeal_limit)
)
if can_recycle_next and (self.stock or self.waste):
full_cycle = list(self.waste) + list(reversed(self.stock))
sim_stk2 = list(reversed(full_cycle))
while sim_stk2:
step = min(self.draw_count, len(sim_stk2))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk2.pop()
if top_drawn is not None:
reachable.append(top_drawn)
return reachable
def has_any_meaningful_move(self) -> bool:
"""
Prüft, ob noch irgendein sinnvoller Zug existiert.
Reine Endlos-Züge (König von leerer Spalte zu leerer Spalte, grundloses Hin-und-Her-Schieben
von Teil-Runs ohne Freilegung einer verdeckten oder Foundation-fähigen Karte) zählen NICHT.
"""
if self.won:
return True
# 1. Tableau-Spitze -> Foundation
for col_idx, col in enumerate(self.tableau):
if col:
top = col[-1]
if self.can_move_to_foundation(top, self.foundation_index_for_suit(top.suit)):
return True
# 2. Sinnvolle Tableau -> Tableau Züge
for src_col, col in enumerate(self.tableau):
if not col:
continue
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up >= len(col):
continue
# a) Ganzen offenen Stapel bewegen (legt verdeckte Karte frei oder räumt Spalte für anderen König)
whole_run = col[first_up:]
if not (first_up == 0 and whole_run[0].value == 13):
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(whole_run, dst_col):
# Leert es nur eine Spalte (first_up == 0, Karte != K), ist das immer produktiv
return True
# b) Teil-Run splitten, falls die freigelegte Karte darunter direkt auf die Foundation passt
for split_idx in range(first_up + 1, len(col)):
exposed = col[split_idx - 1]
if self.can_move_to_foundation(exposed, self.foundation_index_for_suit(exposed.suit)):
sub_run = col[split_idx:]
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(sub_run, dst_col):
return True
# 3. Erreichbare Karten aus Waste / Stock prüfen
for r_card in self._reachable_stock_waste_cards():
if self._card_can_play_anywhere(r_card):
return True
# 4. Falls der Stock noch ungezogene / recyclebare Karten hat, die der Spieler noch selbst aufdecken darf,
# erst dann als Deadlock melden, wenn entweder gar keine spielbare Karte drin steckt ODER das rote X aktiv ist.
# (Schritt 3 hat bereits geprüft, ob im erreichbaren Stock überhaupt noch eine spielbare Karte liegt!)
# 5. Seltener Rettungszug: Karte von Foundation aufs Tableau holen, um damit sofort eine Tableau-Spitze aufzunehmen
for f_idx, f_pile in enumerate(self.foundations):
if not f_pile or f_pile[-1].value <= 2:
continue
f_card = f_pile[-1]
for dst_col in range(self.NUM_TABLEAU):
if not self.can_move_to_tableau([f_card], dst_col):
continue
# Bringt dieser Rückzug einer anderen Tableau-Karte sofort ein neues Ziel?
for other_col, o_pile in enumerate(self.tableau):
if other_col == dst_col or not o_pile:
continue
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
head = o_pile[o_first_up]
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
return True
return False
return KlondikeHintAnalyzer.has_any_meaningful_move(self)
def get_hint(self) -> dict | None:
if self.waste:
w_card = self.waste[-1]
f_idx = self.foundation_index_for_suit(w_card.suit)
if self.can_move_to_foundation(w_card, f_idx):
return {"type": "waste_to_foundation", "dst": f_idx}
return KlondikeHintAnalyzer.get_hint(self)
for col_idx, col in enumerate(self.tableau):
if col:
t_card = col[-1]
f_idx = self.foundation_index_for_suit(t_card.suit)
if self.can_move_to_foundation(t_card, f_idx):
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
for src_col, col in enumerate(self.tableau):
if not col:
continue
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up_idx >= len(col):
continue
moving = col[first_up_idx:]
if first_up_idx == 0 and moving[0].value == 13:
continue
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(moving, dst_col):
return {
"type": "tableau_to_tableau",
"src_col": src_col,
"card_idx": first_up_idx,
"dst_col": dst_col,
}
if self.waste:
w_card = self.waste[-1]
for dst_col in range(self.NUM_TABLEAU):
if self.can_move_to_tableau([w_card], dst_col):
return {"type": "waste_to_tableau", "dst_col": dst_col}
if self.can_draw_or_recycle():
return {"type": "draw_stock"}
return None
# --- Persistenz ---
def serialize_board(self) -> dict:
return {
"draw_count": self.draw_count,
@ -516,9 +333,5 @@ class KlondikeEngine(SolitaireBaseEngine):
self.progress_in_current_cycle = bool(board.get("progress_in_cycle", 0))
self.stock = [SolitaireCard.from_dict(d) for d in board["stock"]]
self.waste = [SolitaireCard.from_dict(d) for d in board["waste"]]
self.foundations = [
[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]
]
self.tableau = [
[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]
]
self.foundations = [[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]]
self.tableau = [[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]]

View File

@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
# games/solitaire/klondike/models/klondike_hint_analyzer.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireCard
class KlondikeHintAnalyzer:
"""Kapselt Erreichbarkeits-Analyse, Deadlock-Prüfung und Zug-Tipps für KlondikeEngine."""
@staticmethod
def card_can_play_anywhere(eng, card: SolitaireCard) -> bool:
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
if eng.can_move_to_foundation(probe, eng.foundation_index_for_suit(probe.suit)):
return True
return any(eng.can_move_to_tableau([probe], dst_col) for dst_col in range(eng.NUM_TABLEAU))
@staticmethod
def reachable_stock_waste_cards(eng) -> list[SolitaireCard]:
reachable: list[SolitaireCard] = []
if eng.waste:
reachable.append(eng.waste[-1])
if eng.stock:
sim_stk = list(eng.stock)
while sim_stk:
step = min(eng.draw_count, len(sim_stk))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk.pop()
if top_drawn is not None:
reachable.append(top_drawn)
will_lock_after_stock = (
bool(eng.stock)
and (not eng.progress_in_current_cycle)
and (eng.stagnant_cycles + 1 >= eng.MAX_STAGNANT_CYCLES)
)
can_recycle_next = (
not eng.is_stock_locked()
and not will_lock_after_stock
and (eng.redeal_limit is None or eng.redeals_used < eng.redeal_limit)
)
if can_recycle_next and (eng.stock or eng.waste):
full_cycle = list(eng.waste) + list(reversed(eng.stock))
sim_stk2 = list(reversed(full_cycle))
while sim_stk2:
step = min(eng.draw_count, len(sim_stk2))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk2.pop()
if top_drawn is not None:
reachable.append(top_drawn)
return reachable
@classmethod
def has_any_meaningful_move(cls, eng) -> bool:
if eng.won:
return True
for col in eng.tableau:
if col:
top = col[-1]
if eng.can_move_to_foundation(top, eng.foundation_index_for_suit(top.suit)):
return True
for src_col, col in enumerate(eng.tableau):
if not col:
continue
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up >= len(col):
continue
whole_run = col[first_up:]
if not (first_up == 0 and whole_run[0].value == 13):
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(whole_run, dst_col):
return True
for split_idx in range(first_up + 1, len(col)):
exposed = col[split_idx - 1]
if eng.can_move_to_foundation(exposed, eng.foundation_index_for_suit(exposed.suit)):
sub_run = col[split_idx:]
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(sub_run, dst_col):
return True
for r_card in cls.reachable_stock_waste_cards(eng):
if cls.card_can_play_anywhere(eng, r_card):
return True
for f_pile in eng.foundations:
if not f_pile or f_pile[-1].value <= 2:
continue
f_card = f_pile[-1]
for dst_col in range(eng.NUM_TABLEAU):
if not eng.can_move_to_tableau([f_card], dst_col):
continue
for other_col, o_pile in enumerate(eng.tableau):
if other_col == dst_col or not o_pile:
continue
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
head = o_pile[o_first_up]
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
return True
return False
@staticmethod
def get_hint(eng) -> dict | None:
if eng.waste:
w_card = eng.waste[-1]
f_idx = eng.foundation_index_for_suit(w_card.suit)
if eng.can_move_to_foundation(w_card, f_idx):
return {"type": "waste_to_foundation", "dst": f_idx}
for col_idx, col in enumerate(eng.tableau):
if col:
t_card = col[-1]
f_idx = eng.foundation_index_for_suit(t_card.suit)
if eng.can_move_to_foundation(t_card, f_idx):
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
for src_col, col in enumerate(eng.tableau):
if not col:
continue
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up_idx >= len(col):
continue
moving = col[first_up_idx:]
if first_up_idx == 0 and moving[0].value == 13:
continue
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(moving, dst_col):
return {
"type": "tableau_to_tableau",
"src_col": src_col,
"card_idx": first_up_idx,
"dst_col": dst_col,
}
if eng.waste:
w_card = eng.waste[-1]
for dst_col in range(eng.NUM_TABLEAU):
if eng.can_move_to_tableau([w_card], dst_col):
return {"type": "waste_to_tableau", "dst_col": dst_col}
if eng.can_draw_or_recycle():
return {"type": "draw_stock"}
return None

View File

@ -2,437 +2,44 @@
# games/solitaire/klondike/views/klondike_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.klondike.views.klondike_table_view import KlondikeTableView
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,
KLONDIKE_VARIANTS,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import KLONDIKE_VARIANTS
GAME_FOLDER_ID = "solitaire/klondike"
GAME_TITLE_KEY = "game_title_klondike"
class KlondikeMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class KlondikeMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "kl_menu_topbar"
SUBTITLE_KEY = "sol_menu_subtitle"
CONTROLS_HINT_KEY = "kl_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "klondike_diff"
VARIANT_SETTING_PREFIX = "klondike_variant"
DEFAULT_VARIANT_KEY = "klondike_1"
REQUIRED_BOARD_KEYS = ("tableau",)
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "sol_draw_mode_lbl"
VARIANT_TOGGLES = (
("klondike_1", "kl_draw_toggle_1"),
("klondike_3", "kl_draw_toggle_3"),
)
TOGGLE_BTN_WIDTH = 162
DESC_KEY_PREFIX = "kl_desc_"
diff_setting_key = f"klondike_diff_{pid}"
draw_setting_key = f"klondike_variant_{pid}"
def _variants_dict(self) -> dict[str, dict]:
return KLONDIKE_VARIANTS
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
)
selected_variant = Database.load_setting(draw_setting_key, "klondike_1")
if selected_variant not in KLONDIKE_VARIANTS:
selected_variant = "klondike_1"
def open_stats():
self._clear_modal()
variants = Database.get_variants_for_filter(GAME_FOLDER_ID)
pre_id = next((v["id"] for v in variants if v["variant_key"] == selected_variant), None)
SolitaireStatsView(
self.ctx,
game_folder=GAME_FOLDER_ID,
game_title_key=GAME_TITLE_KEY,
on_back=lambda: self.show(),
).show(preselect_variant_id=pre_id)
self.ctx.build_game_topbar(
self.ctx.root,
t("kl_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_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, 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",
)
def switch_draw_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(draw_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
draw_btns: list[ImageButton] = []
for v_key, toggle_lbl_key in (("klondike_1", "kl_draw_toggle_1"), ("klondike_3", "kl_draw_toggle_3")):
is_sel = (selected_variant == v_key)
b = ImageButton(
cv,
t(toggle_lbl_key),
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda k=v_key: switch_draw_mode(k),
sound_mgr=self.ctx.sounds,
width=162,
height=36,
style="fire" if is_sel else "amethyst",
)
draw_btns.append(b)
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(
selected_variant, 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(24, int(h * 0.055))
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("sol_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 = 238
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 + 220
# Zeile 1: Zieh-Modus Toggles + Beschreibung sauber darunter (kein Anstoßen an den rechten Rahmen!)
r1_y = cur_y + 44
dm_lbl = self.ctx.assets.get_goth_text_photo(
t("sol_draw_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
self._photo_refs.append(dm_lbl)
cv.create_image(lbl_col, r1_y, image=dm_lbl, anchor="w", tags="fg")
bx_cur = val_col
for db in draw_btns:
cv.create_window(bx_cur, r1_y, window=db, anchor="w", tags="fg")
bx_cur += db.pixel_width + 10
dsc_txt = t(f"kl_desc_{selected_variant}").replace("•", "-")
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")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 128
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")
# 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("kl_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:
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()
KlondikeTableView(
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 = KLONDIKE_VARIANTS.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, 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"klondike_diff_{pid}", str(difficulty))
Database.save_setting(f"klondike_variant_{pid}", variant_key)
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
KlondikeTableView(
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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,438 +2,46 @@
# games/solitaire/spider_solitaire/views/spider_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView
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,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
SPIDER_VARIANTS,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import SPIDER_VARIANTS
GAME_FOLDER_ID = "solitaire/spider_solitaire"
GAME_TITLE_KEY = "game_title_spider_solitaire"
class SpiderMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class SpiderMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "sp_menu_topbar"
SUBTITLE_KEY = "sp_menu_subtitle"
CONTROLS_HINT_KEY = "sp_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "spider_diff"
VARIANT_SETTING_PREFIX = "spider_variant"
DEFAULT_VARIANT_KEY = "spider_1suit"
DEFAULT_SCORE = 500
REQUIRED_BOARD_KEYS = ("tableau", "stock_deals")
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "sp_suit_mode_lbl"
VARIANT_TOGGLES = (
("spider_1suit", "sp_suit_toggle_1"),
("spider_2suit", "sp_suit_toggle_2"),
("spider_4suit", "sp_suit_toggle_4"),
)
TOGGLE_BTN_WIDTH = 158
DESC_KEY_PREFIX = "sp_desc_"
diff_setting_key = f"spider_diff_{pid}"
var_setting_key = f"spider_variant_{pid}"
def _variants_dict(self) -> dict[str, dict]:
return SPIDER_VARIANTS
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
)
selected_variant = Database.load_setting(var_setting_key, "spider_1suit")
if selected_variant not in SPIDER_VARIANTS:
selected_variant = "spider_1suit"
def open_stats():
self._clear_modal()
variants = Database.get_variants_for_filter(GAME_FOLDER_ID)
pre_id = next((v["id"] for v in variants if v["variant_key"] == selected_variant), None)
SolitaireStatsView(
self.ctx,
game_folder=GAME_FOLDER_ID,
game_title_key=GAME_TITLE_KEY,
on_back=lambda: self.show(),
).show(preselect_variant_id=pre_id)
self.ctx.build_game_topbar(
self.ctx.root,
t("sp_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_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, 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",
)
def switch_suit_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(var_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
suit_btns: list[ImageButton] = []
suit_toggles = (
("spider_1suit", "sp_suit_toggle_1"),
("spider_2suit", "sp_suit_toggle_2"),
("spider_4suit", "sp_suit_toggle_4"),
)
for v_key, lbl_key in suit_toggles:
is_sel = (selected_variant == v_key)
b = 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_suit_mode(k),
sound_mgr=self.ctx.sounds,
width=158,
height=36,
style="fire" if is_sel else "amethyst",
)
suit_btns.append(b)
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(
selected_variant, 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(22, int(h * 0.05))
title_ph = self.ctx.assets.get_goth_text_photo(
t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
)
sub_ph = self.ctx.assets.get_goth_text_photo(
t("sp_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() + 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 = 82
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 + 16
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 = 240
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 + 220
# Zeile 1: 1 / 2 / 4 Farben Toggles + Kurzbeschreibung darunter
r1_y = cur_y + 44
sm_lbl = self.ctx.assets.get_goth_text_photo(
t("sp_suit_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
self._photo_refs.append(sm_lbl)
cv.create_image(lbl_col, r1_y, image=sm_lbl, anchor="w", tags="fg")
bx_cur = val_col
for sb in suit_btns:
cv.create_window(bx_cur, r1_y, window=sb, anchor="w", tags="fg")
bx_cur += sb.pixel_width + 10
dsc_txt = t(f"sp_desc_{selected_variant}").replace("•", "-")
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")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 128
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")
# 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("sp_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 + 12, 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 "stock_deals" not in board:
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", 500)),
"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()
SpiderTableView(
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 = SPIDER_VARIANTS.get(old_v, {"xp_mult": 1.10})["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"spider_diff_{pid}", str(difficulty))
Database.save_setting(f"spider_variant_{pid}", variant_key)
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
SpiderTableView(
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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

67
main.py
View File

@ -22,7 +22,8 @@ from models.database import Database
from resources.code_res.game_constants import APP_ICON_REL_PATH
from view.font_loader import FontLoader
from view.main_window import GothCardCollectionView
from view.window_state import WindowStatePersistence
from view.widgets.error_report_overlay import ErrorReportOverlay
from games.solitaire.base.solitaire_theme import extract_best_ico_pil
# Oben in view/main_window.py:
APP_WM_CLASS = "TheGothCardgameCollection"
@ -87,49 +88,15 @@ def _prepare_os_app_identity():
def _extract_ico_frames(icon_path: Path) -> tuple[Image.Image | None, list[Image.Image]]:
"""Liest das größte Bild aus game_icon.ico (auch wenn es intern PNG/JPEG/BMP-codiert ist)."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
best_img = None
best_area = -1
ico_helper = getattr(ico, "ico", None)
if ico_helper is not None and hasattr(ico_helper, "sizes"):
for sz in ico_helper.sizes():
try:
frame = ico_helper.getimage(sz).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
if best_img is None:
n_frames = getattr(ico, "n_frames", 1)
for idx in range(n_frames):
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
if best_img is None:
best_img = ico.convert("RGBA")
cascade = [
best_img.resize((px, px), Image.Resampling.LANCZOS)
for px in (256, 128, 64, 48, 32, 16)
]
return best_img, cascade
except Exception:
"""Nutzt den zentralen ICO-Frame-Reader und erzeugt die Fenster-Icon-Kaskade."""
best_img = extract_best_ico_pil(icon_path)
if best_img is None:
return None, []
cascade = [
best_img.resize((px, px), Image.Resampling.LANCZOS)
for px in (256, 128, 64, 48, 32, 16)
]
return best_img, cascade
def ensure_crostini_shelf_icon(icon_ico_path: Path, wm_class: str = APP_WM_CLASS) -> None:
@ -353,15 +320,10 @@ def _install_clean_shutdown(app: GothCardCollectionView):
except Exception:
prev_wm_delete_cmd = None
orig_report = getattr(app, "report_callback_exception", None)
def _filtered_callback_exc(exc, val, tb):
if shutting_down or exc is KeyboardInterrupt:
return
if callable(orig_report):
orig_report(exc, val, tb)
app.report_callback_exception = _filtered_callback_exc
ErrorReportOverlay.install_global_hooks(
app,
is_shutting_down_cb=lambda: shutting_down,
)
def graceful_exit(*_args):
nonlocal shutting_down
@ -449,7 +411,6 @@ def main():
FontLoader.bind_to_tk_root(app)
_apply_cross_platform_icon(app, root_path)
WindowStatePersistence(app)
graceful_exit = _install_clean_shutdown(app)

154
models/avatar_composer.py Normal file
View File

@ -0,0 +1,154 @@
# -*- coding: utf-8 -*-
# models/avatar_composer.py
from __future__ import annotations
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter, ImageOps
from models.database import Database
DEFAULT_AVATAR_FILENAME = "default_picture.png"
EMPTY_RING_FILENAME = "empty_ring.png"
CUSTOM_AVATAR_PREFIX = "custom:"
CUSTOM_AVATARS_SUBDIR = "custom_avatars"
AVATAR_EXPORT_SIZE = 384
class AvatarComposer:
"""
Verwaltet Preset-Profilbilder aus resources/images/profile_pictures/ sowie
hochgeladene Nutzerbilder, die rund maskiert unter empty_ring.png gelegt werden.
"""
@staticmethod
def get_presets_dir(res_mgr) -> Path:
return res_mgr.images_dir / "profile_pictures"
@staticmethod
def get_custom_avatars_dir() -> Path:
d = Database.get_user_db_dir() / CUSTOM_AVATARS_SUBDIR
d.mkdir(parents=True, exist_ok=True)
return d
@classmethod
def list_preset_filenames(cls, res_mgr) -> list[str]:
p_dir = cls.get_presets_dir(res_mgr)
if not p_dir.is_dir():
return [DEFAULT_AVATAR_FILENAME]
found: list[str] = []
for p in sorted(p_dir.iterdir(), key=lambda x: x.name.lower()):
if not p.is_file():
continue
low = p.name.lower()
if low == EMPTY_RING_FILENAME or not low.endswith((".png", ".jpg", ".jpeg", ".webp")):
continue
found.append(p.name)
# default_picture.png immer als erstes Element einreihen
if DEFAULT_AVATAR_FILENAME in found:
found.remove(DEFAULT_AVATAR_FILENAME)
found.insert(0, DEFAULT_AVATAR_FILENAME)
elif not found:
found.append(DEFAULT_AVATAR_FILENAME)
return found
@classmethod
def resolve_avatar_path(cls, res_mgr, avatar_ref: str | None) -> Path:
ref = (avatar_ref or "").strip() or DEFAULT_AVATAR_FILENAME
if ref.startswith(CUSTOM_AVATAR_PREFIX):
rel_name = Path(ref[len(CUSTOM_AVATAR_PREFIX):]).name
cand = cls.get_custom_avatars_dir() / rel_name
if cand.is_file():
return cand
p_dir = cls.get_presets_dir(res_mgr)
cand_preset = p_dir / Path(ref).name
if cand_preset.is_file():
return cand_preset
return p_dir / DEFAULT_AVATAR_FILENAME
@classmethod
def load_avatar_pil(cls, res_mgr, avatar_ref: str | None) -> Image.Image:
path = cls.resolve_avatar_path(res_mgr, avatar_ref)
if path.is_file():
try:
return Image.open(path).convert("RGBA")
except Exception:
pass
# Minimaler Fallback-Kreis, falls selbst default_picture.png fehlt
fb = Image.new("RGBA", (256, 256), (0, 0, 0, 0))
d = ImageDraw.Draw(fb)
d.ellipse((16, 16, 240, 240), fill=(26, 20, 38, 255), outline=(212, 175, 55, 255), width=6)
return fb
@classmethod
def import_custom_avatar(
cls, res_mgr, source_image_path: Path, profile_id: int
) -> str:
"""
Schneidet ein beliebiges Nutzerbild quadratisch zu, maskiert es exakt auf den
Innenkreis von empty_ring.png, legt den Ring darüber und speichert es neben user_data.db.
Gibt die neue avatar_ref ('custom:profile_<id>_avatar.png') zurück.
"""
src = Image.open(source_image_path)
src = ImageOps.exif_transpose(src).convert("RGBA")
ring_path = cls.get_presets_dir(res_mgr) / EMPTY_RING_FILENAME
ring_pil: Image.Image | None = None
if ring_path.is_file():
ring_pil = Image.open(ring_path).convert("RGBA").resize(
(AVATAR_EXPORT_SIZE, AVATAR_EXPORT_SIZE), Image.Resampling.LANCZOS
)
sz = AVATAR_EXPORT_SIZE
# Innenöffnung von empty_ring.png liegt bei ca. 78 % Durchmesser (Radius ~0.39)
pad_inner = int(round(sz * 0.105))
inner_d = sz - 2 * pad_inner
portrait = ImageOps.fit(
src, (inner_d, inner_d), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
)
# Weiche Kreismaske, damit kein Pixel über den Außenrand des Rings hinausragt
mask = Image.new("L", (sz, sz), 0)
m_draw = ImageDraw.Draw(mask)
m_draw.ellipse(
(pad_inner, pad_inner, sz - pad_inner, sz - pad_inner), fill=255
)
mask = mask.filter(ImageFilter.GaussianBlur(radius=1.0))
# Dezente dunkle Grundscheibe + zentriertes Porträt + innere Abschattung zum Ring
canvas_img = Image.new("RGBA", (sz, sz), (0, 0, 0, 0))
disc = Image.new("RGBA", (sz, sz), (14, 11, 20, 255))
canvas_img.paste(disc, (0, 0), mask)
layer = Image.new("RGBA", (sz, sz), (0, 0, 0, 0))
layer.paste(portrait, (pad_inner, pad_inner))
composed = Image.composite(layer, canvas_img, mask)
# Leichter innerer Vignetten-Rand für plastischen Übergang unter dem Metallring
vignette = Image.new("RGBA", (sz, sz), (0, 0, 0, 0))
v_draw = ImageDraw.Draw(vignette)
v_draw.ellipse(
(pad_inner + 2, pad_inner + 2, sz - pad_inner - 2, sz - pad_inner - 2),
outline=(8, 5, 14, 155),
width=max(4, sz // 42),
)
vignette = vignette.filter(ImageFilter.GaussianBlur(radius=3.0))
composed = Image.alpha_composite(composed, vignette)
if ring_pil is not None:
composed = Image.alpha_composite(composed, ring_pil)
else:
r_draw = ImageDraw.Draw(composed)
r_draw.ellipse(
(pad_inner, pad_inner, sz - pad_inner, sz - pad_inner),
outline=(212, 175, 55, 255),
width=8,
)
out_name = f"profile_{int(profile_id)}_avatar.png"
out_path = cls.get_custom_avatars_dir() / out_name
composed.save(out_path, format="PNG")
return f"{CUSTOM_AVATAR_PREFIX}{out_name}"

57
models/bavarian_deck.py Normal file
View File

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

View File

@ -1,15 +1,17 @@
# -*- coding: utf-8 -*-
# models/database.py
from __future__ import annotations
import os
import sqlite3
import sys
from pathlib import Path
import resources.code_res.sql_queries as sql
from resources.code_res.game_constants import (
BJ_DEFAULT_BET, BJ_STARTING_GOLD, DEVILS_DEAL_GOLD_REWARD,
GOLD_MAX_ACCOUNTS, INTERNAL_DB_REL_PATH, PK_STARTING_GOLD,
USER_DB_FILENAME, XP_TO_GOLD_AMOUNT
)
from models.db_locator import DbLocator
from models.db_pouch_repo import DbPouchRepo
from models.db_stats_repo import DbStatsRepo
from resources.code_res.game_constants import INTERNAL_DB_REL_PATH, USER_DB_FILENAME
def _resolve_bundle_root() -> Path:
@ -20,15 +22,19 @@ def _resolve_bundle_root() -> Path:
def _resolve_user_data_dir() -> Path:
"""Persistenter Speicherort für user_data.db direkt neben der ausführbaren Datei."""
"""Fallback-Speicherort neben der ausführbaren Datei (niemals /tmp!) bzw. im Benutzerverzeichnis."""
if getattr(sys, "frozen", False):
exe_dir = Path(sys.executable).resolve().parent
# Auf macOS (.app-Bundle) oder schreibgeschützten Pfaden wie /usr/local/bin ausweichen
if ".app/Contents/MacOS" not in str(exe_dir).replace("\\", "/") and os.access(exe_dir, os.W_OK):
raw_exe = os.environ.get("ARGV0") or (sys.argv[0] if sys.argv else sys.executable)
exe_dir = Path(raw_exe).expanduser().resolve().parent
exe_str = str(exe_dir).replace("\\", "/")
if (
".app/Contents/MacOS" not in exe_str
and not exe_str.startswith("/tmp")
and "/_MEI" not in exe_str
and os.access(exe_dir, os.W_OK)
):
return exe_dir
fallback_dir = Path.home() / ".local" / "share" / "TheGothCardgameCollection"
fallback_dir.mkdir(parents=True, exist_ok=True)
return fallback_dir
return DbLocator._default_installed_data_dir()
return Path(__file__).resolve().parent.parent
@ -36,11 +42,33 @@ BUNDLE_ROOT = _resolve_bundle_root()
USER_DATA_DIR = _resolve_user_data_dir()
INTERNAL_DB_PATH = BUNDLE_ROOT / INTERNAL_DB_REL_PATH
USER_DB_PATH = USER_DATA_DIR / USER_DB_FILENAME
USER_DB_PATH = DbLocator.resolve_initial_db_path(USER_DATA_DIR)
class Database:
"""
Zentrale SQLite-Fassade für Verbindung, DB-Speicherort/Umzug, Einstellungen,
Profile und Savegames; delegiert Goldbeutel und Statistiken an Sub-Repositories.
"""
_connection: sqlite3.Connection | None = None
_active_user_db_path: Path = USER_DB_PATH
@classmethod
def get_user_db_path(cls) -> Path:
return cls._active_user_db_path
@classmethod
def get_user_db_dir(cls) -> Path:
return cls._active_user_db_path.parent
@classmethod
def _set_active_path_vars(cls, new_path: Path) -> None:
global USER_DB_PATH, USER_DATA_DIR
resolved = new_path.expanduser().resolve()
cls._active_user_db_path = resolved
USER_DB_PATH = resolved
USER_DATA_DIR = resolved.parent
@classmethod
def conn(cls) -> sqlite3.Connection:
@ -50,11 +78,10 @@ class Database:
f"Interne Stammdaten-DB fehlt: {INTERNAL_DB_PATH}. "
"Bitte zuerst das Seed-SQL mit deinem Query-Executor ausführen!"
)
USER_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(str(USER_DB_PATH))
cls._active_user_db_path.parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(str(cls._active_user_db_path))
c.row_factory = sqlite3.Row
c.execute(sql.PRAGMA_FOREIGN_KEYS)
# Read-Only URI verhindert Schreib-Sperren in schreibgeschützten Bundle-Ordnern
internal_uri = f"{INTERNAL_DB_PATH.resolve().as_uri()}?mode=ro"
try:
c.execute(sql.ATTACH_INTERNAL_DB, (internal_uri,))
@ -66,7 +93,10 @@ class Database:
@classmethod
def close(cls):
if cls._connection is not None:
cls._connection.close()
try:
cls._connection.close()
except Exception:
pass
cls._connection = None
@classmethod
@ -95,14 +125,146 @@ class Database:
row = cls.conn().execute(query, params).fetchone()
return row[0] if row is not None else default
@classmethod
def _persist_self_location_in_db(cls, previous_path: Path | None = None) -> None:
cur_p = cls._active_user_db_path.resolve()
cls.save_setting("user_db_path", str(cur_p))
cls.save_setting("user_db_dir", str(cur_p.parent))
if previous_path is not None:
cls.save_setting("user_db_previous_path", str(previous_path.resolve()))
DbLocator.remember_db_path(cur_p)
@classmethod
def init_db(cls):
cls.conn().executescript(sql.USER_SCHEMA_DDL)
bj_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_BJ_ACCOUNTS)]
if "devils_deal_active" not in bj_cols:
cls.conn().execute(sql.MIGRATE_ADD_DEVILS_ACTIVE)
prof_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_PROFILES)]
if "avatar_ref" not in prof_cols:
cls.conn().execute(sql.MIGRATE_ADD_PROFILE_AVATAR)
cls.conn().commit()
cls._persist_self_location_in_db()
# --- DB-Speicherort, Live-Wechsel & Atomarer Umzug ---
@staticmethod
def validate_sqlite_file(candidate_file: Path) -> bool:
if not candidate_file.is_file():
return False
try:
# Kein ?mode=ro erzwingen, da SQLite bei offenen -wal Dateien sonst unter Linux
# mangels Schreibrecht fuer -shm mit OperationalError abbricht!
with sqlite3.connect(str(candidate_file.resolve())) as test_c:
res = test_c.execute("PRAGMA integrity_check;").fetchone()
if not res or str(res[0]).lower() != "ok":
return False
tables = {
r[0] for r in test_c.execute(
"SELECT name FROM sqlite_master WHERE type='table';"
).fetchall()
}
return (not tables) or ("profiles" in tables and "settings" in tables)
except Exception:
return False
@classmethod
def relocate_for_first_user(cls, target_dir_or_file: Path) -> Path:
target = target_dir_or_file.expanduser().resolve()
if target.is_dir() or target.suffix.lower() != ".db":
target = target / USER_DB_FILENAME
old_path = cls._active_user_db_path.resolve()
if target == old_path:
cls._persist_self_location_in_db()
return target
target.parent.mkdir(parents=True, exist_ok=True)
old_was_empty = (len(cls.get_profiles()) == 0)
cls.close()
cls._set_active_path_vars(target)
cls.init_db()
if old_was_empty and old_path.is_file() and old_path != target:
for suffix in ("", "-wal", "-shm"):
try:
Path(f"{old_path}{suffix}").unlink(missing_ok=True)
except Exception:
pass
return target
@classmethod
def switch_user_database(cls, existing_db_file: Path) -> tuple[bool, str]:
cand = existing_db_file.expanduser().resolve()
if not cls.validate_sqlite_file(cand):
return False, "invalid_file"
prev_path = cls._active_user_db_path.resolve()
# Immer Verbindung sauber schließen & frisch öffnen (auch wenn cand == prev_path),
# damit extern hineinkopierte Dateien garantiert neu eingelesen werden!
cls.close()
try:
cls._set_active_path_vars(cand)
cls.init_db()
cls._persist_self_location_in_db(
previous_path=prev_path if cand != prev_path else None
)
return True, str(cand)
except Exception as exc:
cls.close()
cls._set_active_path_vars(prev_path)
cls.init_db()
return False, str(exc)
@classmethod
def move_user_database(cls, destination_dir: Path) -> tuple[bool, str]:
dst_dir = destination_dir.expanduser().resolve()
dst_dir.mkdir(parents=True, exist_ok=True)
dst_file = (dst_dir / cls._active_user_db_path.name).resolve()
old_file = cls._active_user_db_path.resolve()
if dst_file == old_file:
cls._persist_self_location_in_db()
return True, str(dst_file)
tmp_file = dst_dir / f".{dst_file.name}.moving_tmp"
try:
tmp_file.unlink(missing_ok=True)
src_conn = cls.conn()
src_conn.commit()
with sqlite3.connect(str(tmp_file)) as backup_conn:
src_conn.backup(backup_conn, name="main")
if not cls.validate_sqlite_file(tmp_file):
tmp_file.unlink(missing_ok=True)
return False, "Backup verification failed"
cls.close()
if dst_file.is_file():
dst_file.unlink()
tmp_file.replace(dst_file)
cls._set_active_path_vars(dst_file)
cls.init_db()
cls._persist_self_location_in_db(previous_path=old_file)
for suffix in ("", "-wal", "-shm"):
try:
Path(f"{old_file}{suffix}").unlink(missing_ok=True)
except Exception:
pass
return True, str(dst_file)
except Exception as exc:
try:
tmp_file.unlink(missing_ok=True)
except Exception:
pass
if cls._connection is None:
cls._set_active_path_vars(old_file)
cls.init_db()
return False, str(exc)
# --- Stammdaten, Settings, Profile & Savegames ---
@classmethod
def load_all_translations(cls) -> dict[str, dict[str, str]]:
out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}}
@ -122,7 +284,6 @@ class Database:
def save_setting(cls, key: str, value: str):
cls.execute(sql.UPSERT_SETTING, (key, str(value)))
# --- Profile ---
@classmethod
def get_profiles(cls) -> list[str]:
return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)]
@ -136,117 +297,6 @@ class Database:
def get_profile_by_id(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,))
# --- Spielgebundene Progression ---
@classmethod
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
from models.progression import Progression
cls.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
row = cls.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder))
info = Progression.get_level_info(
row["points"],
profile_id=profile_id,
game_folder=game_folder,
ever_deity=bool(row["ever_reached_deity"]),
)
if info["ever_reached_deity"] and not row["ever_reached_deity"]:
cls.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder))
return info
@classmethod
def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int:
row = cls.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num)))
if not row or row["games_count"] <= 0:
return 0
return int(row["total_xp_earned"] // row["games_count"])
@classmethod
def _record_game_xp_with_history(cls, profile_id: int, game_folder: str, current_level: int, xp_gained: int):
from models.progression import Progression
if xp_gained <= 0:
return
cls.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
cls.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder))
if current_level >= Progression.get_creator_spirit_v_level():
cls.conn().execute(
sql.UPSERT_GAME_LEVEL_XP_HISTORY,
(profile_id, game_folder, int(current_level), int(xp_gained))
)
@classmethod
def add_game_points(cls, profile_id: int, game_folder: str, points: int):
if points <= 0:
return
cur_prog = cls.get_game_progress(profile_id, game_folder)
with cls.conn():
cls._record_game_xp_with_history(profile_id, game_folder, cur_prog["level"], int(points))
cls.get_game_progress(profile_id, game_folder)
@classmethod
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
cur = cls.get_game_progress(profile_id, game_folder)
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
return cls.get_game_progress(profile_id, game_folder)
# --- Spielgebundener THE DEVIL'S DEAL (Blackjack & Poker jeweils autark!) ---
@classmethod
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
from models.progression import Progression
min_lvl = Progression.get_devils_deal_min_level()
eligible = []
for row in cls.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)):
info = Progression.get_level_info(row["points"])
if info["level"] >= min_lvl:
eligible.append({
"id": row["id"],
"name": row["name"],
"level": info["level"],
"title": info["title"],
})
return eligible
@classmethod
def execute_devils_deal(
cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int
) -> tuple[bool, str]:
from resources.code_res.i18n import t
candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)}
victim = candidates.get(sacrifice_profile_id)
if not victim:
return False, ""
if game_folder == "poker":
with cls.conn():
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_poker_account(account_id)
else:
with cls.conn():
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_blackjack_account(account_id)
return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"])
@classmethod
def get_active_devils_bj_account(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,))
@classmethod
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id))
@classmethod
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_PK_ACCOUNT, (profile_id,))
@classmethod
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
cls.execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1 if active else 0, pk_account_id))
# --- Savegames ---
@classmethod
def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str):
cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json))
@ -259,264 +309,157 @@ class Database:
def delete_game_state(cls, profile_id: int, game_folder: str):
cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder))
# --- Blackjack Gold-Konten ---
# --- Delegatoren an DbStatsRepo ---
@classmethod
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,))
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
return DbStatsRepo.get_game_progress(cls, profile_id, game_folder)
@classmethod
def get_blackjack_account(cls, bj_account_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,))
def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int:
return DbStatsRepo.get_recorded_game_level_avg_xp(cls, profile_id, game_folder, level_num)
@classmethod
def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_blackjack_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
cls.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET))
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name))
def add_game_points(cls, profile_id: int, game_folder: str, points: int):
DbStatsRepo.add_game_points(cls, profile_id, game_folder, points)
@classmethod
def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
if last_bet is not None:
cls.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id))
else:
cls.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id))
return cls.get_blackjack_account(bj_account_id)
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
return DbStatsRepo.adjust_game_points(cls, profile_id, game_folder, delta_points, min_floor_xp)
@classmethod
def save_blackjack_last_bet(cls, bj_account_id: int, bet: int):
cls.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id))
@classmethod
def delete_blackjack_account(cls, bj_account_id: int):
cls.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,))
@classmethod
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
return cls._exchange_game_xp_for_gold(profile_id, "blackjack", bj_account_id)
# --- Poker Gold-Konten (autarke Bankroll + eigener XP-Tausch!) ---
@classmethod
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
return cls.fetch_all(sql.SELECT_PK_ACCOUNTS_BY_PROFILE, (profile_id,))
@classmethod
def get_poker_account(cls, pk_account_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_ID, (pk_account_id,))
@classmethod
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_poker_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
cls.execute(sql.INSERT_PK_ACCOUNT, (profile_id, clean_name, PK_STARTING_GOLD))
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_NAME, (profile_id, clean_name))
@classmethod
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
cls.execute(sql.UPDATE_PK_GOLD_ONLY, (int(gold_delta), pk_account_id))
return cls.get_poker_account(pk_account_id)
@classmethod
def delete_poker_account(cls, pk_account_id: int):
cls.execute(sql.DELETE_PK_ACCOUNT, (pk_account_id,))
@classmethod
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
return cls._exchange_game_xp_for_gold(profile_id, "poker", pk_account_id)
@classmethod
def _exchange_game_xp_for_gold(cls, profile_id: int, game_folder: str, account_id: int) -> tuple[bool, str]:
"""Gemeinsame Logik für streng spielgebundenen XP->Gold-Tausch inkl. Divine Punishment."""
from models.progression import Progression
from resources.code_res.i18n import t
prog = cls.get_game_progress(profile_id, game_folder)
if prog.get("at_divine_floor"):
return False, t("bj_err_floor_reached")
cost = prog["xp_exchange_cost"]
is_divine = prog["is_divine_punishment"]
if not is_divine and prog["total_points"] < cost:
return False, t("bj_err_not_enough_xp", prog["total_points"], cost)
if is_divine:
floor_xp = Progression.get_creator_spirit_v_floor_xp()
new_points = max(floor_xp, prog["total_points"] - cost)
actual_deducted = prog["total_points"] - new_points
if actual_deducted <= 0:
return False, t("bj_err_floor_reached")
else:
new_points = max(0, prog["total_points"] - cost)
actual_deducted = cost
with cls.conn():
cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, game_folder))
if game_folder == "poker":
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_poker_account(account_id)
else:
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_blackjack_account(account_id)
updated_prog = cls.get_game_progress(profile_id, game_folder)
if is_divine:
return True, t(
"bj_exchange_divine_success",
XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"]
)
return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted)
# --- Bot Configs & Statistiken ---
@classmethod
def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]:
rows = cls.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder))
return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows}
return DbStatsRepo.load_bot_configs(cls, profile_id, game_folder)
@classmethod
def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]):
data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()]
cls.execute_many(sql.UPSERT_BOT_CONFIG, data)
@classmethod
def _upsert_stat(cls, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float):
q = sql.STATS_SQL[scope]
cur = cls.fetch_one(q["select_one"], (owner_id, variant_id))
dur = max(0.0, duration_sec)
if not cur:
cls.conn().execute(q["insert"], (
owner_id, variant_id,
1 if won else 0, 0 if won else 1,
1 if won else 0, 1 if won else 0,
dur if won else None, dur,
))
else:
c_streak = (cur["current_streak"] + 1) if won else 0
best_t = cur["best_time_sec"]
if won:
best_t = dur if best_t is None else min(best_t, dur)
cls.conn().execute(q["update"], (
cur["games_played"] + 1,
cur["games_won"] + (1 if won else 0),
cur["games_lost"] + (0 if won else 1),
c_streak,
max(cur["longest_streak"], c_streak),
best_t,
cur["total_time_sec"] + dur,
owner_id, variant_id,
))
DbStatsRepo.save_bot_configs(cls, profile_id, game_folder, configs)
@classmethod
def record_game_result(
cls,
profile_id: int,
variant_key: str,
won: bool,
duration_sec: float,
points_gained: int = 0,
bj_account_id: int | None = None,
pk_account_id: int | None = None,
cls, profile_id: int, variant_key: str, won: bool, duration_sec: float,
points_gained: int = 0, bj_account_id: int | None = None, pk_account_id: int | None = None,
) -> tuple[int, int]:
var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,))
if not var_info:
raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}")
variant_id = var_info["id"]
game_folder = var_info["folder_path"]
prog_before = cls.get_game_progress(profile_id, game_folder)
old_lvl = prog_before["level"]
with cls.conn():
if points_gained > 0:
cls._record_game_xp_with_history(profile_id, game_folder, old_lvl, int(points_gained))
cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec)
if bj_account_id is not None:
cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec)
if pk_account_id is not None:
cls._upsert_stat("pk_account", pk_account_id, variant_id, won, duration_sec)
new_lvl = cls.get_game_progress(profile_id, game_folder)["level"]
return old_lvl, new_lvl
return DbStatsRepo.record_game_result(
cls, profile_id, variant_key, won, duration_sec, points_gained, bj_account_id, pk_account_id
)
@classmethod
def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]:
from resources.code_res.i18n import t
rows = (
cls.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,))
if folder_path else cls.fetch_all(sql.SELECT_ALL_VARIANTS)
)
for d in rows:
d["translated_name"] = t(f"variant_{d['variant_key']}")
return rows
@classmethod
def _query_stats(cls, scope: str, owner_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
q = sql.STATS_SQL[scope]
if variant_id is not None:
row = cls.fetch_one(q["select_one"], (owner_id, variant_id))
if not row or row["games_played"] == 0:
return cls._empty_stats()
played, won, lost = row["games_played"], row["games_won"], row["games_lost"]
c_streak, l_streak, best_t, total_t = row["current_streak"], row["longest_streak"], row["best_time_sec"], row["total_time_sec"]
else:
row = (
cls.fetch_one(q["aggregate_folder"], (owner_id, folder_path))
if folder_path is not None
else cls.fetch_one(q["aggregate_all"], (owner_id,))
)
if not row or row["played"] == 0:
return cls._empty_stats()
played, won, lost = row["played"], row["won"], row["lost"]
c_streak, l_streak, best_t, total_t = row["c_streak"], row["l_streak"], row["best_time"], row["total_time"]
return {
"played": played,
"won": won,
"lost": lost,
"win_pct": f"{(won / played * 100.0):.1f} %",
"current_streak": c_streak,
"longest_streak": l_streak,
"best_time": cls.format_seconds(best_t),
"avg_time": cls.format_seconds(total_t / played),
}
return DbStatsRepo.get_variants_for_filter(cls, folder_path)
@classmethod
def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
return cls._query_stats("profile", profile_id, variant_id=variant_id, folder_path=folder_path)
return DbStatsRepo.query_stats(cls, "profile", profile_id, variant_id=variant_id, folder_path=folder_path)
@classmethod
def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict:
return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
return DbStatsRepo.query_stats(cls, "bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
@classmethod
def get_pk_account_stats_overview(cls, pk_account_id: int, variant_id: int | None = None) -> dict:
return cls._query_stats("pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
return DbStatsRepo.query_stats(cls, "pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
@staticmethod
def format_seconds(sec: float | None) -> str:
if sec is None:
return "--:--"
mins, secs = divmod(int(round(sec)), 60)
if mins >= 60:
hrs, mins = divmod(mins, 60)
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
return f"{mins:02d}:{secs:02d}"
format_seconds = staticmethod(DbStatsRepo.format_seconds)
@staticmethod
def _empty_stats() -> dict:
return {
"played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %",
"current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--",
}
# --- Delegatoren an DbPouchRepo ---
@classmethod
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
return DbPouchRepo.get_sacrificeable_profiles(cls, active_profile_id, game_folder)
@classmethod
def execute_devils_deal(cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int) -> tuple[bool, str]:
return DbPouchRepo.execute_devils_deal(cls, active_profile_id, game_folder, sacrifice_profile_id, account_id)
@classmethod
def get_active_devils_bj_account(cls, profile_id: int) -> dict | None:
return DbPouchRepo.get_active_devils_bj_account(cls, profile_id)
@classmethod
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
DbPouchRepo.set_bj_devils_deal_active(cls, bj_account_id, active)
@classmethod
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
return DbPouchRepo.get_active_devils_pk_account(cls, profile_id)
@classmethod
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
DbPouchRepo.set_pk_devils_deal_active(cls, pk_account_id, active)
@classmethod
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
return DbPouchRepo.get_blackjack_accounts(cls, profile_id)
@classmethod
def get_blackjack_account(cls, bj_account_id: int) -> dict | None:
return DbPouchRepo.get_blackjack_account(cls, bj_account_id)
@classmethod
def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict:
return DbPouchRepo.create_blackjack_account(cls, profile_id, account_name)
@classmethod
def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
return DbPouchRepo.update_blackjack_gold(cls, bj_account_id, gold_delta, last_bet)
@classmethod
def save_blackjack_last_bet(cls, bj_account_id: int, bet: int):
DbPouchRepo.save_blackjack_last_bet(cls, bj_account_id, bet)
@classmethod
def delete_blackjack_account(cls, bj_account_id: int):
DbPouchRepo.delete_blackjack_account(cls, bj_account_id)
@classmethod
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "blackjack", bj_account_id)
@classmethod
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
return DbPouchRepo.get_poker_accounts(cls, profile_id)
@classmethod
def get_poker_account(cls, pk_account_id: int) -> dict | None:
return DbPouchRepo.get_poker_account(cls, pk_account_id)
@classmethod
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
return DbPouchRepo.create_poker_account(cls, profile_id, account_name)
@classmethod
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
return DbPouchRepo.update_poker_gold(cls, pk_account_id, gold_delta)
@classmethod
def delete_poker_account(cls, pk_account_id: int):
DbPouchRepo.delete_poker_account(cls, pk_account_id)
@classmethod
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "poker", pk_account_id)
@classmethod
def rename_profile(cls, profile_id: int, new_name: str) -> tuple[bool, str]:
clean = (new_name or "").strip()
if not clean:
return False, "profile_err_empty_name"
if len(clean) > 24:
return False, "profile_err_name_too_long"
existing = cls.fetch_one(sql.SELECT_PROFILE_BY_NAME_NOCASE, (clean,))
if existing is not None and int(existing["id"]) != int(profile_id):
return False, "profile_err_name_taken"
old_row = cls.get_profile_by_id(profile_id)
cls.execute(sql.UPDATE_PROFILE_NAME, (clean, int(profile_id)))
if old_row and cls.load_setting("last_profile_name", "") == old_row["name"]:
cls.save_setting("last_profile_name", clean)
return True, clean
@classmethod
def update_profile_avatar(cls, profile_id: int, avatar_ref: str) -> None:
cls.execute(sql.UPDATE_PROFILE_AVATAR, (str(avatar_ref), int(profile_id)))
@classmethod
def get_profile_overall_progress(cls, profile_id: int) -> dict:
return DbStatsRepo.get_profile_overall_progress(cls, profile_id)

Some files were not shown because too many files have changed in this diff Show More