feat(SCOPONE-0009): complete iteration 0 dealer AI

This commit is contained in:
Giancarmine Salucci
2026-04-08 21:50:40 +02:00
parent c9accb7ae4
commit d0a44d295a
7 changed files with 597 additions and 174 deletions

View File

@@ -1,34 +1,35 @@
# Findings
> Last Updated: 2026-04-02T19:05:00.000Z
> Last Updated: 2026-04-08T19:48:08.000Z
## Summary
Initializer refresh for the current Scopone Scientifico codebase. The existing findings were stale relative to the current worker-backed AI execution path, so the observations below reflect the live source tree.
Initializer refresh for SCOPONE-0009. The cached findings were stale relative to the live source tree, so the observations below reflect the current Phaser, worker, and AI implementation.
## Codebase Observations
- Primary gameplay code lives in 8 TypeScript source files under `src/`; the Android wrapper adds 3 Java files.
- The gameplay runtime now includes three AI transport files in addition to the rules engine: `ai-worker-protocol.ts`, `ai-worker-client.ts`, and `ai.worker.ts`.
- The largest concentration of logic still sits in `src/scenes/GameScene.ts` and `src/game/ai.ts`.
- `src/game/` remains framework-independent and contains the rules engine, score calculation, card tracker, and AI logic.
- The AI now has three distinct difficulty levels: `beginner`, `advanced`, and `master`.
- The `advanced` and `master` tiers use `CardTracker` to reason about unseen cards instead of reading hidden hands directly.
- The `master` tier performs determinization plus alpha-beta search and reports progress back through `AIDecisionProgress`.
- `GameScene` displays AI progress through a top think bar and updates it from worker-forwarded progress messages.
- `AIWorkerClient` degrades cleanly to in-thread `chooseMove()` execution when workers are unavailable or fail.
- Audio remains fully procedural via Web Audio; no audio asset pipeline is present.
- No ESLint or Prettier config is present.
- Primary gameplay code currently lives in 10 TypeScript source files under `src/`; the Android wrapper adds 3 Java files.
- The project is structurally split between framework-free gameplay modules in `src/game/` and Phaser scene code in `src/scenes/`.
- `src/scenes/GameScene.ts` and `src/game/ai.ts` remain the two largest concentrations of application logic.
- The AI transport layer is now a stable three-file path: `ai-worker-protocol.ts`, `ai-worker-client.ts`, and `ai.worker.ts`.
- The AI exposes three difficulty levels: `beginner`, `advanced`, and `master`.
- `advanced` and `master` both use `CardTracker` to reason about unseen cards without directly reading hidden hands.
- The current `master` search profile is `timeBudgetMs: 4600`, `sampleCount: 10`, `maxDepth: 6`, `batchSize: 2`.
- `GameScene` consumes AI progress callbacks to update an on-screen think bar while a worker request is running.
- `AIWorkerClient` fails over pending work to in-thread `chooseMove()` if worker creation, posting, or deserialization fails.
- The Android wrapper targets SDK 36 with `minSdkVersion` 24 and applies immersive mode from the native activity.
- Audio remains procedural via Web Audio; no dedicated audio asset pipeline is present in the source tree.
- No ESLint or Prettier configuration is present.
- The only repository-wide verification command supplied is `npx tsc --noEmit`.
## Potential Improvement Areas
- `GameScene.ts` still centralizes scene layout, input, effects, audio, HUD, and round transitions in one file, which raises maintenance cost.
- `ai.ts` mixes heuristic tiers, inference helpers, determinization, and alpha-beta evaluation in one module.
- Worker message types and fallback behavior are separated cleanly, but the UI still knows about AI progress presentation details directly.
- The `master` profile allows up to 9800 ms of search budget, which may be expensive on slower devices even with batch yielding.
- There is still no dedicated automated test suite for rules or AI behavior beyond type-checking.
- Formatting rules are enforced socially rather than by a linter/formatter toolchain.
- `GameScene.ts` still centralizes layout, turn flow, HUD updates, effects, and audio in one scene class, which raises maintenance cost.
- `ai.ts` still combines heuristic tiers, inference helpers, determinization, and alpha-beta evaluation in one module.
- Worker transport is isolated cleanly, but progress rendering remains coupled to scene-level UI concerns.
- A 4600 ms master search budget may still be noticeable on slower mobile devices even with batch yielding.
- There is no dedicated automated rules or AI test suite beyond type-checking.
- Formatting and style are enforced socially rather than by automated linting or formatting tools.
## Current Rule / Implementation Notes
@@ -36,30 +37,32 @@ Initializer refresh for the current Scopone Scientifico codebase. The existing f
- Direct-match capture has priority over subset-sum capture.
- When multiple direct matches exist, `findCaptures()` returns one single-card option per matching card.
- Subset-sum captures are explored only when no direct match exists.
- Subset-sum captures are considered only when no direct match exists.
- `applyMove()` defaults to the first legal capture if no explicit capture choice is supplied.
- Scope is awarded only when a capture clears the table before the final play of the round.
### AI implementation snapshot
- `beginner` adds randomness around a basic heuristic to remain beatable.
- `beginner` uses a simpler heuristic with noise to remain beatable.
- `advanced` adds race awareness, anti-scopa logic, partner setup, anchor play, and tracker-based probability estimates.
- `master` orders legal moves with a quick evaluator, samples hidden hands, then scores moves with alpha-beta search under a deadline.
- `masterMove()` yields back to the browser between batches so Phaser can repaint the progress UI.
- `master` orders legal moves with a quick evaluator, samples hidden hands, and scores them with alpha-beta search under the active deadline.
- Progress is reported through `AIDecisionProgress` so the scene can keep the think bar responsive.
### Worker execution snapshot
- `GameScene` creates a fresh `AIWorkerClient` on scene creation and disposes it on shutdown.
- `AIWorkerClient` serializes a tracker snapshot instead of sending a live `CardTracker` instance across the worker boundary.
- `ai.worker.ts` reconstructs tracker state with `CardTracker.fromSnapshot()` before calling `chooseMove()`.
- Progress, results, and serialized worker errors all travel through `ai-worker-protocol.ts`.
- If worker initialization, posting, or message deserialization fails, pending requests are rerun with the in-thread AI path.
- `GameScene` creates `AIWorkerClient` during `create()` and disposes it on both `shutdown` and `destroy`.
- `AIWorkerClient` serializes `CardTracker` state through `toSnapshot()` instead of attempting to transfer the class instance.
- `ai.worker.ts` rebuilds tracker state with `CardTracker.fromSnapshot()` before calling `chooseMove()`.
- Progress, result, and serialized error payloads all travel through `ai-worker-protocol.ts`.
- If worker execution becomes unavailable, pending requests are rerun with the in-thread AI path rather than being dropped.
### Scene / UI implementation snapshot
- `BootScene` loads atlas assets and presents a simple loading bar.
- `MenuScene` exposes difficulty selection before match start.
- `GameScene` records every played card and captured table card in `CardTracker`.
- The HUD continuously displays cards, denari, settebello, primiera, scope, and total points for both teams.
- Round-end and game-over flows are managed in-scene rather than through separate overlay components.
- `GameScene` tracks played and captured cards in `CardTracker` as the round evolves.
- The scene owns score HUD rendering, player labels, status text, think-bar rendering, and procedural particle effects.
- Round-end and match-end flows remain managed inside the scene instead of separate overlay components.
## Research Performed
@@ -106,4 +109,11 @@ Initializer refresh for the current Scopone Scientifico codebase. The existing f
- The current implementation does not use Phaser `TimerEvent` progress helpers.
- Instead, `chooseMove()` emits its own normalized progress payload through `AIDecisionProgress`.
- `GameScene.updateThinkBar()` renders remaining time from that callback.
- The yielding behavior in `masterMove()` is necessary so the browser can repaint while search batches continue.
- The yielding behavior in the master search path is necessary so the browser can repaint while search batches continue.
### SCOPONE-0009: Phaser scene lifecycle notes (2026-04-08)
- Source: Context7 `/websites/phaser_io_api-documentation`, query `Phaser 3.87 Scene lifecycle create restart shutdown destroy event listeners scene restart preserving external state`.
- Phaser dispatches `shutdown` when a scene stops being active but may be re-used later; resource cleanup that should also cover final teardown can additionally listen to `destroy`.
- The current `GameScene` pattern of registering one-shot shutdown and destroy handlers is aligned with Phaser guidance for worker disposal and UI cleanup.
- Dealer rotation and next-round state changes can stay inside the existing in-scene orchestration without requiring a different Phaser lifecycle primitive.