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,21 +1,21 @@
# Architecture
> Last Updated: 2026-04-02T19:05:00.000Z
> Last Updated: 2026-04-08T19:48:08.000Z
## Overview
| Attribute | Value |
|-----------|-------|
| Primary language | TypeScript |
| Secondary language | Java (Capacitor Android shell) |
| Project type | Browser card game with Android packaging |
| Secondary language | Java |
| Project type | Phaser browser game packaged for Android with Capacitor |
| Framework | Phaser 3.87.0 |
| Tooling | Vite 5, TypeScript 5.x, Capacitor 8.3 |
| Runtime layout | 1280 x 720, `Phaser.Scale.FIT`, centered in `#game` |
| Build command | `npm run build` |
| Test command | `npx tsc --noEmit` |
The repository is a TypeScript-first Scopone Scientifico implementation. The web client contains the real game logic and presentation. The Android tree is a Capacitor wrapper with a custom immersive `MainActivity`.
The repository is a TypeScript-first implementation of Scopone Scientifico. Gameplay rules, scoring, inference, and AI live in framework-independent modules under `src/game/`. Phaser scenes under `src/scenes/` own rendering, input, UI, animation, and scene transitions. The `android/` tree is a Capacitor wrapper with a small custom `MainActivity` for immersive full-screen behavior.
## Project Structure
@@ -37,6 +37,8 @@ scopone-phaser/
| `- GameScene.ts
|- public/
|- android/
| |- app/
| `- variables.gradle
|- docs/
|- prompts/
|- package.json
@@ -49,102 +51,102 @@ scopone-phaser/
| Directory | Purpose |
|-----------|---------|
| `src/game/` | Framework-independent rules, scoring, imperfect-information tracking, and AI search |
| `src/scenes/` | Phaser scene lifecycle, UI, animation, effects, and round orchestration |
| `public/` | Static web assets consumed by Phaser loaders |
| `android/` | Capacitor Android project, Gradle config, and immersive activity wrapper |
| `src/game/` | Rules engine, score calculation, imperfect-information tracking, AI heuristics, and master search |
| `src/scenes/` | Phaser scene lifecycle, menus, board rendering, interaction, HUD, audio, and FX |
| `public/` | Atlas metadata and other static assets loaded by Phaser |
| `android/` | Capacitor Android project, Gradle configuration, generated wrapper assets, and the native activity |
| `docs/` | Architecture, code style, findings, and cache metadata |
| `prompts/` | JIRA pipeline artifacts and iteration state |
| `prompts/` | JIRA workflow artifacts and iteration state |
## Design Patterns
No explicit GoF patterns were detected in the source or by semantic search.
Observed architectural patterns in the current codebase:
Observed architectural patterns:
| Pattern | Where it appears |
|---------|------------------|
| Scene-based flow | `BootScene -> MenuScene -> GameScene` via Phaser scene registration |
| Functional core / imperative shell | `src/game/` stays free of Phaser imports, while `src/scenes/` owns rendering and input |
| Clone-before-mutate state transitions | `applyMove()` clones `GameState` before applying move effects |
| Worker offload with fallback | `AIWorkerClient` runs heavy AI inside `ai.worker.ts` and falls back to in-thread `chooseMove()` if worker startup or messaging fails |
| Determinization search | Master AI samples hidden hands before alpha-beta evaluation |
| Message-based progress reporting | Worker and main thread exchange typed request/result/progress messages through `ai-worker-protocol.ts` |
| Functional core / imperative shell | `src/game/` avoids Phaser imports while `src/scenes/` owns runtime side effects |
| Immutable state transitions | `applyMove()` clones `GameState` before mutating round state |
| Worker offload with fallback | `AIWorkerClient` uses `ai.worker.ts` when available and falls back to direct `chooseMove()` otherwise |
| Typed message protocol | `ai-worker-protocol.ts` defines worker request, progress, result, and error shapes |
| Imperfect-information search | `CardTracker` plus determinization sampling support the `master` AI tier |
## Key Components
### `src/main.ts`
- Bootstraps `Phaser.Game`.
- Creates the `Phaser.Game` instance.
- Registers `BootScene`, `MenuScene`, and `GameScene`.
- Installs a one-shot fullscreen request handler on first user interaction.
- Installs a one-shot fullscreen request on first user input when supported.
### `src/game/types.ts`
- Defines the game model: `Card`, `Capture`, `Player`, `GameState`, `TeamScore`, `ScoreBreakdown`.
- Encodes difficulty tiers as `'beginner' | 'advanced' | 'master'`.
- Stores the `PRIMIERA_VALUES` lookup table.
- Defines the core game model: `Card`, `Capture`, `Player`, `GameState`, `TeamScore`, and `ScoreBreakdown`.
- Models constrained domains with unions such as `PlayerIndex` and `Difficulty`.
- Stores `PRIMIERA_VALUES` for end-of-round scoring.
### `src/game/engine.ts` (371 lines)
### `src/game/engine.ts`
- Builds and shuffles the 40-card deck.
- Creates the initial round state for four players.
- Implements capture selection rules: single direct matches take priority; subset sums are considered only when no direct match exists.
- Applies moves immutably, detects scopas, assigns leftover table cards, and computes round scores.
- Creates a round state for four players with dealer-relative opening order.
- Implements capture rules where direct value matches take priority over subset-sum captures.
- Applies moves immutably, awards scope, assigns leftover table cards, and computes round and match scoring.
### `src/game/card-tracker.ts` (89 lines)
### `src/game/card-tracker.ts`
- Tracks seen cards across a round without exposing hidden hands directly.
- Computes unseen cards from `played + myHand + table`.
- Supplies probability helpers used by the AI for value-based inference.
- Tracks cards visible through play and capture events without exposing hidden hands.
- Reconstructs unseen cards from `played + myHand + table`.
- Supplies value and suit residue helpers used by AI inference and probability estimates.
### `src/game/ai.ts`
- Exposes `chooseMove()` as an async entry point.
- Implements three difficulty levels:
- `beginner`: noisy heuristic play.
- `advanced`: stronger heuristics with race awareness, partner setup, and card-tracker inference.
- `master`: determinization plus alpha-beta search with dynamic time budgets, batching, and progress callbacks.
- Uses `yieldToBrowser()` between master-search batches so Phaser can repaint the think bar.
- Exposes `chooseMove()` as the async AI entry point.
- Implements three difficulty tiers: `beginner`, `advanced`, and `master`.
- Uses table-driven search profiles, role-aware heuristics, tracker-based inference, and determinization plus alpha-beta search.
- Configures the current master profile with a 4600 ms budget, 10 samples, depth 6, and batch size 2.
### `src/game/ai-worker-protocol.ts`
- Defines the typed message contract between the main thread and the worker.
- Serializes requests around `GameState`, `Difficulty`, `PlayerIndex`, tracker snapshots, progress, results, and worker-safe errors.
- Defines a single `choose-move` worker request type.
- Defines typed progress, result, and serialized error responses.
- Keeps worker communication schema isolated from UI code.
### `src/game/ai-worker-client.ts`
- Wraps the worker lifecycle behind the same `chooseMove()` API the scene needs.
- Creates module workers with `new Worker(new URL('./ai.worker.ts', import.meta.url), { type: 'module' })`.
- Streams progress callbacks back into `GameScene` and degrades to direct `chooseMove()` execution when workers are unavailable.
- Wraps worker lifecycle and pending-request tracking behind the same `chooseMove()` API that scenes consume.
- Creates the worker as an ES module with `new Worker(new URL('./ai.worker.ts', import.meta.url), { type: 'module' })`.
- Fails over pending requests to in-thread AI execution if worker creation, messaging, or deserialization fails.
### `src/game/ai.worker.ts`
- Rehydrates `CardTracker` from a snapshot, delegates move selection to `chooseMove()`, and posts progress/result/error messages back to the scene thread.
- Keeps the expensive `master` search off the main rendering thread when worker support is available.
- Rehydrates `CardTracker` from a serialized snapshot.
- Delegates move selection to `chooseMove()`.
- Posts progress, result, or serialized error messages back to the main thread.
### `src/scenes/BootScene.ts`
- Loads the card atlas and card-back texture.
- Shows a simple progress bar and transitions into the menu.
- Loads the card atlas and card back.
- Displays a simple loading bar.
- Transitions into `MenuScene` after asset load.
### `src/scenes/MenuScene.ts`
- Renders the title screen and rules summary.
- Lets the player choose `beginner`, `advanced`, or `master` difficulty.
- Starts `GameScene` with the selected difficulty in scene data.
- Renders the title, rules summary, and difficulty selection.
- Starts `GameScene` with the chosen difficulty.
### `src/scenes/GameScene.ts`
- Owns the match loop, HUD, think bar, card interaction, animation, FX, audio, and round transitions.
- Uses `CardTracker` to record played and captured cards after each move.
- Instantiates `AIWorkerClient`, bridges async AI progress into a visible top-of-screen think bar, and disposes worker resources on scene shutdown.
- Handles end-of-round overlays and full-match restart flow.
- Owns match flow, dealing, selection, capture resolution, AI turn orchestration, score HUD, status UI, think bar, particles, and procedural audio.
- Instantiates and disposes `AIWorkerClient` on scene lifecycle events.
- Updates `CardTracker` after play and capture events so AI inference remains derived from visible information.
### `android/app/src/main/java/com/phaser/scopa/MainActivity.java`
- Extends `BridgeActivity`.
- Forces immersive mode by hiding status and navigation bars whenever the window gains focus.
- Applies immersive mode during `onCreate()` and whenever window focus returns.
- Hides status and navigation bars with transient swipe behavior.
## Dependencies
@@ -152,74 +154,77 @@ Observed architectural patterns in the current codebase:
| Package | Version | Purpose |
|---------|---------|---------|
| `phaser` | `^3.87.0` | Game engine |
| `@capacitor/core` | `^8.3.0` | Capacitor runtime |
| `@capacitor/cli` | `^8.3.0` | Capacitor tooling |
| `phaser` | `^3.87.0` | Game engine runtime |
| `@capacitor/core` | `^8.3.0` | Capacitor runtime bridge |
| `@capacitor/cli` | `^8.3.0` | Capacitor project tooling |
| `@capacitor/android` | `^8.3.0` | Android platform integration |
### JavaScript development dependencies
| Package | Version | Purpose |
|---------|---------|---------|
| `typescript` | `^5.0.0` | Type-checking and TS compilation for builds |
| `vite` | `^5.0.0` | Dev server and bundling |
| `typescript` | `^5.0.0` | Static type checking and TS compilation step |
| `vite` | `^5.0.0` | Dev server and production bundler |
### Android / Gradle dependencies
| Dependency | Source | Purpose |
|------------|--------|---------|
| `com.android.tools.build:gradle:8.13.0` | `android/build.gradle` | Android build plugin |
| `com.google.gms:google-services:4.4.4` | `android/build.gradle` | Optional Google services integration |
| `androidx.appcompat:appcompat` | `android/app/build.gradle` | Android UI compatibility |
| `androidx.coordinatorlayout:coordinatorlayout` | `android/app/build.gradle` | Android layout support |
| `androidx.core:core-splashscreen` | `android/app/build.gradle` | Splash screen support |
| `junit:junit` | `android/app/build.gradle` | JVM-side Android tests |
| `androidx.test.ext:junit` | `android/app/build.gradle` | Instrumented Android testing |
| `androidx.test.espresso:espresso-core` | `android/app/build.gradle` | Android UI testing |
| Dependency | Version | Source | Purpose |
|------------|---------|--------|---------|
| `com.android.tools.build:gradle` | `8.13.0` | `android/build.gradle` | Android Gradle plugin |
| `com.google.gms:google-services` | `4.4.4` | `android/build.gradle` | Optional Google services integration |
| `androidx.appcompat:appcompat` | `1.7.1` | `android/variables.gradle` | Android app compatibility |
| `androidx.coordinatorlayout:coordinatorlayout` | `1.3.0` | `android/variables.gradle` | Layout coordination helpers |
| `androidx.core:core-splashscreen` | `1.2.0` | `android/variables.gradle` | Splash screen support |
| `junit:junit` | `4.13.2` | `android/variables.gradle` | JVM Android tests |
| `androidx.test.ext:junit` | `1.3.0` | `android/variables.gradle` | Instrumented test runner |
| `androidx.test.espresso:espresso-core` | `3.7.0` | `android/variables.gradle` | Instrumented UI testing |
### Platform configuration
- `compileSdkVersion`: 36
- `targetSdkVersion`: 36
- `minSdkVersion`: 24
## Module Organization
```text
main.ts
-> BootScene
-> MenuScene
-> GameScene
-> engine.ts
-> ai.ts
-> ai-worker-client.ts
-> ai-worker-protocol.ts
-> ai.worker.ts
-> ai.ts
-> card-tracker.ts
-> types.ts
-> BootScene
-> MenuScene
-> GameScene
-> engine.ts
-> types.ts
-> card-tracker.ts
-> ai-worker-client.ts
-> ai-worker-protocol.ts
-> ai.worker.ts
-> ai.ts
```
Dependencies are one-directional at the application level:
Application-level dependency direction is one-way:
- `src/game/` imports only from sibling game modules.
- `src/scenes/` imports from `src/game/`.
- `src/scenes/` imports from `src/game/` and Phaser.
- `src/game/` never imports Phaser.
## Data Flow
1. `main.ts` creates the Phaser app and registers all scenes.
2. `BootScene` loads assets, then starts `MenuScene`.
3. `MenuScene` passes the chosen difficulty into `GameScene`.
4. `GameScene.create()` initializes a new `CardTracker`, creates the initial `GameState`, and animates the opening deal.
5. On each turn:
- Human turns use click-driven selection and capture highlighting.
- AI turns call `AIWorkerClient.chooseMove(state, playerIdx, difficulty, tracker, onProgress)`.
6. `AIWorkerClient` posts a typed request into `ai.worker.ts`; if worker setup fails, it falls back to in-thread `chooseMove()`.
7. `chooseMove()` either returns immediately for heuristic tiers or performs batched master search while reporting `AIDecisionProgress`.
8. Worker progress messages drive `GameScene.updateThinkBar()` until a result is posted back.
9. `GameScene.executeMove()` applies the move, updates the tracker, animates the result, refreshes the HUD, and advances the round.
10. When all hands are empty, `engine.ts` finalizes scoring and `GameScene` displays the round summary or final match screen.
2. `BootScene` loads textures and starts `MenuScene`.
3. `MenuScene` passes the chosen difficulty to `GameScene`.
4. `GameScene.create()` creates a fresh `CardTracker`, constructs a new `GameState`, and starts the opening deal.
5. Human turns use pointer-driven card selection and `findCaptures()` output to choose legal captures.
6. AI turns call `AIWorkerClient.chooseMove(state, playerIdx, difficulty, tracker, onProgress)`.
7. `AIWorkerClient` posts a typed request to `ai.worker.ts`; if workers are unavailable, it reruns the same request in-thread.
8. `chooseMove()` returns a heuristic move for lower tiers or performs batched master search while emitting `AIDecisionProgress`.
9. `GameScene` updates the think bar from progress callbacks, executes the returned move, records tracker state, and advances turn order.
10. When every hand is empty, `engine.ts` finalizes scoring and `GameScene` presents the round or match outcome.
## Build System
| Command | Source | Purpose |
|---------|--------|---------|
| `npm run dev` | `package.json` | Starts the Vite development server on port 3000 and opens the browser |
| `npm run dev` | `package.json` | Starts the Vite dev server |
| `npm run build` | user-provided build command | Runs `tsc && vite build` and writes web output to `dist/` |
| `npm run preview` | `package.json` | Serves the built app locally via Vite preview |
| `npm run preview` | `package.json` | Serves the built app with Vite preview |
| `npx tsc --noEmit` | user-provided test command | Type-checks the TypeScript codebase without emitting files |

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.