chore: initial commit

This commit is contained in:
Giancarmine Salucci
2026-03-31 18:38:34 +02:00
commit 3d1f3e5eb4
79 changed files with 6659 additions and 0 deletions

147
docs/ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,147 @@
# Architecture
> Last Updated: 2026-03-31T00:00:00.000Z
## Overview
| Attribute | Value |
|-----------------|--------------------------------------------------------|
| **Language** | TypeScript (ES2020 target, strict mode) |
| **Type** | 2D card game — Scopone Scientifico |
| **Framework** | Phaser 3.87+ (scene-based game engine) |
| **Bundler** | Vite 5 |
| **Native** | Capacitor 8.3 (Android) |
| **Resolution** | 1280 × 720, FIT scaling with auto-center |
## Project Structure
```
scopone-phaser/
├── src/
│ ├── main.ts # Phaser.Game bootstrap + config
│ ├── game/
│ │ ├── types.ts # Card, Suit, Player, GameState, TeamScore, ScoreBreakdown, PRIMIERA_VALUES
│ │ ├── engine.ts # Deck build, shuffle, capture logic, applyMove, scoring, primiera
│ │ └── ai.ts # Heuristic AI: chooseMove, scoreCapture, scoreDump
│ └── scenes/
│ ├── BootScene.ts # Asset loading (atlas, card back image)
│ ├── MenuScene.ts # Start menu with rules summary
│ └── GameScene.ts # Main game: rendering, turn management, effects, audio
├── index.html # Entry point, Italian locale, green felt background
├── public/ # Static assets (atlas.json, atlas.png, retro.png)
├── android/ # Capacitor Android native shell
├── package.json
├── tsconfig.json
├── vite.config.ts
└── capacitor.config.ts
```
## Key Directories
| Directory | Purpose |
|--------------------|----------------------------------------------------------------|
| `src/game/` | Domain logic — types, game engine, AI (no Phaser dependency) |
| `src/scenes/` | Phaser scenes — rendering, input, effects, audio |
| `public/` | Static assets served by Vite (card atlas, card back) |
| `android/` | Capacitor-generated Android project (Gradle, Java) |
| `prompts/` | JIRA agent pipeline artifacts |
## Design Patterns
| Pattern | Where |
|-----------------------------|--------------------------------------------------------------------|
| **Scene lifecycle** | BootScene → MenuScene → GameScene (Phaser scene graph) |
| **Immutable state updates** | `applyMove()` deep-clones `GameState` before mutation |
| **Heuristic scoring** | AI evaluates all legal moves with weighted feature scores |
| **Separation of concerns** | `game/` has no Phaser imports; `scenes/` bridges game ↔ rendering |
| **Procedural audio** | Web Audio API oscillators + delay reverb — no audio files |
No explicit GoF patterns (singleton, factory, observer, DI) detected.
## Key Components
### `types.ts` — Domain Types
- `Card { suit, value, id }` — 40-card Napoletane deck (suits: bastoni, coppe, denara, spade; values 1-10)
- `GameState` — full round state: 4 players, table, current player, team scores, round tracking
- `TeamScore` — per-team stats: cards, scope, denari, settebello, primiera, round/total points
- `ScoreBreakdown` — which team won each scoring category
- `PRIMIERA_VALUES` — lookup table for primiera card values
### `engine.ts` — Game Logic
- `buildDeck()` / `shuffle()` — Fisher-Yates 40-card deck
- `createInitialState()` — deals 10 cards per player, empty table (Scopone Scientifico rules)
- `findCaptures(played, table)` — direct value match (mandatory) or subset-sum combinations
- `applyMove(state, player, card, captureChoice)` — immutable state transition, scopa detection, end-of-round scoring
- `calculateScores()` / `scoreRound()` — carte, denari, settebello, primiera, scope points
- `calcPrimiera(pile)` — best card per suit using `PRIMIERA_VALUES`
- `teamOf(playerIdx)` — team assignment: 0+2 = Team A, 1+3 = Team B
### `ai.ts` — Heuristic AI
- `chooseMove(state, playerIdx)` — evaluates all legal moves (captures + dumps)
- `scoreCapture()` — weighted: scopa (+500), settebello (+300), denari (+50 each), card count, primiera value, opponent threat
- `scoreDump()` — avoids giving opponents scopa (-400), prefers low-value non-denari, penalises dumping 7s and aces
### `GameScene.ts` — Main Scene (~1340 lines)
- Four-player layout: South (human), West/East (AI, rotated ±90°), North (AI partner)
- Deal animation with staggered tweens
- Card selection with postFX glow pulse
- Capture highlighting with multiple-choice UI
- Particle effects: capture burst, scopa explosion, settebello flash, denari shimmer, primiera glow, card trails, victory confetti
- Camera shake + flash on scopa and settebello
- Live score bar with animated counter updates
- Think bar progress indicator during AI turns
- Procedural background music (oscillator drone + triangle melody + chord stabs)
- Round-end summary panel and game-over screen
## Dependencies
### Production
| Package | Version | Purpose |
|----------------------|----------|--------------------------------------|
| `phaser` | ^3.87.0 | 2D game engine |
| `@capacitor/core` | ^8.3.0 | Capacitor runtime |
| `@capacitor/cli` | ^8.3.0 | Capacitor CLI |
| `@capacitor/android` | ^8.3.0 | Android platform plugin |
### Development
| Package | Version | Purpose |
|---------------|---------|--------------------------|
| `typescript` | ^5.0.0 | TypeScript compiler |
| `vite` | ^5.0.0 | Dev server and bundler |
## Module Organisation
```
main.ts ──→ BootScene ──→ MenuScene ──→ GameScene
├── game/engine (createInitialState, applyMove, findCaptures, ...)
├── game/ai (chooseMove)
└── game/types (Card, GameState, ...)
```
`game/` modules are pure logic with no framework coupling. `scenes/` imports from `game/` but never vice versa.
## Data Flow
1. `createInitialState()` builds shuffled deck, deals 10 cards each, empty table
2. `GameScene.nextTurn()` detects current player: human → enable input; AI → delay + `chooseMove()`
3. `applyMove()` returns new `GameState` + capture result + scopa flag
4. `GameScene.executeMove()` animates: card flight → capture burst → pile collection
5. `updateScoreBar()` reflects live team stats with animated counter tweens
6. When all hands empty → `calculateScores()` → round-end overlay
7. First team to 11 points → game-over screen → optional restart
## Build System
| Command | Action |
|--------------------|--------------------------------------------|
| `npm run dev` | `vite` — dev server on port 3000 |
| `npm run build` | `tsc && vite build` — compile + bundle to `dist/` |
| `npm run preview` | `vite preview` — preview production build |
| `tsc --noEmit` | Type-check only (no test framework) |

145
docs/CODE_STYLE.md Normal file
View File

@@ -0,0 +1,145 @@
# Code Style
> Last Updated: 2026-03-31T00:00:00.000Z
## Language & Version
- **TypeScript** 5.x, strict mode enabled
- Target: **ES2020**, module: **ESNext**, module resolution: **bundler**
- `noEmit: true` — Vite handles transpilation; `tsc` is used for type-checking only
## Naming Conventions
| Kind | Convention | Examples |
|------------------|---------------|-------------------------------------------------------------------|
| Types/Interfaces | PascalCase | `Card`, `GameState`, `PlayerIndex`, `TeamScore`, `ScoreBreakdown` |
| Type aliases | PascalCase | `Suit`, `PlayerIndex` |
| Classes | PascalCase | `BootScene`, `MenuScene`, `GameScene` |
| Functions | camelCase | `buildDeck()`, `findCaptures()`, `chooseMove()`, `applyMove()` |
| Constants | UPPER_SNAKE | `PRIMIERA_VALUES`, `SUITS`, `AI_DELAY`, `SCOREBAR_H` |
| Local variables | camelCase | `bestMove`, `capturedCards`, `isScopa`, `afterTable` |
| Private members | camelCase | `this.state`, `this.cardImages`, `this.aiThinking` |
| Parameters | camelCase | `playerIdx`, `captureChoice`, `onComplete` |
## Class & Scene Patterns
Scenes extend `Phaser.Scene` and follow the Phaser lifecycle:
```ts
export class BootScene extends Phaser.Scene {
constructor() {
super({ key: 'BootScene' });
}
preload(): void { /* asset loading */ }
create(): void { /* scene setup */ }
}
```
Scene registration via `Phaser.Types.Core.GameConfig.scene` array in `main.ts`.
## Indentation & Formatting
- **2-space** indentation
- **Single quotes** for string literals
- No semicolons omission — **semicolons used consistently**
- Trailing commas in multi-line objects/arrays
- `const` preferred; `let` when reassignment is needed; no `var`
## Import Patterns
Named imports from local modules:
```ts
import { Card, GameState, PlayerIndex } from './types';
import { findCaptures, canCapture, calcPrimiera, teamOf } from './engine';
import { chooseMove } from '../game/ai';
```
Default import for Phaser:
```ts
import Phaser from 'phaser';
```
Type-only import for Capacitor config:
```ts
import type { CapacitorConfig } from '@capacitor/cli';
```
Relative paths only (`./`, `../`). No path aliases configured.
## Export Patterns
- **Named exports** for all public symbols (`export function`, `export class`, `export interface`, `export type`, `export const`)
- No default exports except `vite.config.ts` and `capacitor.config.ts` (framework convention)
- Private/internal functions are not exported (`getSubsets`, `calculateScores`, `scoreRound`, `deepClone`)
## Type Annotations
- Explicit return types on exported functions: `(): Card[]`, `(): GameState`, `(): boolean`
- Union types for constrained values: `PlayerIndex = 0 | 1 | 2 | 3`
- String literal unions: `Suit = 'bastoni' | 'coppe' | 'denara' | 'spade'`
- Tuple types for fixed-length arrays: `[Player, Player, Player, Player]`, `[TeamScore, TeamScore]`
- `Record<K, V>` for maps: `PRIMIERA_VALUES: Record<number, number>`
## Comments & Documentation
- **JSDoc** comments on key exported functions (`findCaptures`, `applyMove`)
- Section separators using dashed lines:
```ts
// ---------------------------------------------------------------------------
// Deck
// ---------------------------------------------------------------------------
```
- `[trueref]` annotations documenting Phaser API provenance
- Inline comments for non-obvious logic (capture rules, AI heuristic weights)
- No auto-generated docs or separate documentation tooling
## Code Examples (from codebase)
### Immutable state update pattern
```ts
export function applyMove(
state: GameState,
playerIdx: PlayerIndex,
card: Card,
captureChoice?: Card[]
): { nextState: GameState; capture: Capture | null; isScopa: boolean } {
const state2 = deepClone(state);
// ... mutations on state2 ...
return { nextState: state2, capture: ..., isScopa };
}
```
### AI heuristic weighted scoring
```ts
function scoreCapture(...): number {
let score = 100; // base for capturing anything
if (isScopa) score += 500;
if (settebello) score += 300;
score += denariCount * 50;
score += captured.length * 20;
// ...
return score;
}
```
### Phaser particle effect
```ts
const e1 = this.add.particles(x, y, 'particle_glow', {
lifespan: { min: 350, max: 700 },
speed: { min: 80, max: 280 },
scale: { start: 0.9, end: 0 },
tint: color, gravityY: 100, emitting: false,
}).setDepth(25);
e1.explode(count);
```
## Linting & Formatting
No ESLint or Prettier configuration detected. Code style is maintained manually.
TypeScript strict mode provides type-level linting (`strict: true` in `tsconfig.json`).

99
docs/FINDINGS.md Normal file
View File

@@ -0,0 +1,99 @@
# Findings
> Last Updated: 2026-03-31T00:00:00.000Z
## Summary
Initial analysis of the Scopone Scientifico Phaser 3 codebase. This document is populated by the Planner agent as research is performed.
## Codebase Observations
- **Total source files**: 9 TypeScript (6 in `src/`), 3 Java (Capacitor boilerplate)
- **Largest file**: `GameScene.ts` (~1340 lines) — rendering, input, effects, audio, UI
- **Game logic is framework-independent**: `game/` modules have zero Phaser imports
- **No test framework**: only `tsc --noEmit` for type-checking
- **No linter/formatter**: code style enforced manually
- **AI plays all 3 non-human seats** using the same heuristic
- **Procedural audio**: all sound is Web Audio oscillators — no audio asset files
## Potential Improvement Areas
- **AI cheats with perfect information**: `scoreDump()` and `opponentThreatScore()` in `ai.ts` iterate `opp.hand` directly — bots can see all opponent cards. Must be replaced with imperfect-information card tracking.
- **No mastery/difficulty levels**: All 3 AI seats use the same heuristic at the same strength.
- **No card tracking**: No module tracks which cards have been played or remains in the deck.
- **No minimax**: Pure heuristic scoring, no look-ahead or game tree search.
- **Allied bot is selfish**: Compagno (player 2) plays identically to opponents — no cooperative strategy.
## Research Performed
### Web Research: Scopone Scientifico Rules (2026-03-31)
**Sources**: Wikipedia (*Scopa* article, Scopone section), Pagat.com (*Scopone* page by John McLeod)
#### Core Rules (Scopone Scientifico variant)
- 4 players, 2 fixed teams of 2 (sit opposite): Team A = players 0+2, Team B = players 1+3
- 40-card Napoletane deck: 4 suits (bastoni, coppe, denara, spade), values 110
- **All 40 cards dealt** (10 each), **no initial table cards** — the "scientifico" variant
- Play passes around the table (counter-clockwise in Italian tradition; this game uses 0→1→2→3)
- Each turn: play one card face-up to the table
#### Capture Rules
1. If the played card's value **matches a table card**, the table card **must** be captured (single card, not a sum)
2. If **multiple table cards match** the played value, exactly one is captured (player chooses)
3. If **no direct match**, the player may capture a **subset of table cards summing** to the played value
4. If the played card matches both a single card and a sum, **the single card must be captured** (not the sum)
5. There is **no obligation to play a capturing card** — a player may choose to play a non-capturing card instead. But if the played card CAN capture, it MUST capture.
6. **Scopa**: capturing ALL remaining table cards awards +1 point (except on the very last card of the round)
#### Scoring (per round, 4 fixed points + scope)
| Category | Rule |
|------------|----------------------------------------------------------|
| **Carte** | Team with majority of captured cards (20+ of 40). Tie = no point. |
| **Denari** | Team with majority of coins/denara suit cards (6+ of 10). Tie = no point. |
| **Settebello** | Team capturing the 7 of denara. Always awarded. |
| **Primiera** | Team with highest prime value. Prime = best card per suit using special scale. Tie = no point. Must have all 4 suits. |
| **Scope** | +1 per scopa achieved during play. |
#### Primiera Values (confirmed matching codebase)
| Card value | Primiera value |
|------------|---------------|
| 7 | 21 |
| 6 | 18 |
| 1 (Ace) | 16 |
| 5 | 15 |
| 4 | 14 |
| 3 | 13 |
| 2 | 12 |
| 8,9,10 | 10 |
A team missing an entire suit **cannot win primiera** (even 3×21=63 loses to 21+16+16+16=69 with all 4 suits).
#### Winning
- First team to **11+ points** at the end of a round wins
- If both reach 11 in the same round, higher total wins; if tied, play continues
#### Strategy Notes (from Pagat.com)
- **7 of coins (settebello)** is the single most valuable card — contributes to all 4 fixed scoring categories
- **Avoid giving scope**: leave table total ≥ 11 when possible
- **Anchor strategy**: leave a card on table that your team controls (you hold duplicates of that value)
- **Whirlwind**: consecutive scope — clearing the table forces opponent to play, partner captures, repeat
- **Sevens > sixes > aces** in priority for primiera control
- **Paired/unpaired tracking**: if all captures are single-card matches, the last card matches the last table card. Sum captures disrupt this pattern, important for end-game planning.
### Codebase Capture Rule Validation
The `findCaptures()` in `engine.ts` correctly implements:
- Direct match priority over sum captures ✓
- Multiple direct matches: takes ALL matching cards (slight deviation — pagat.com says choose ONE, but Wikipedia says take all. The codebase takes all direct matches. This is the **existing behavior** and must not be altered per success criteria.)
- Sum subsets via power set enumeration ✓
- `applyMove()` auto-captures when possible ✓
### Minimax Feasibility Analysis
- 10 cards per player × 4 players = 40 total moves per round
- Full game tree: ~10^12 nodes — infeasible for exhaustive search
- **Approach**: Depth-limited alpha-beta with determinization for imperfect information
- Sample N possible opponent hand assignments consistent with card tracking
- Run minimax on each sample to limited depth (46 plies)
- Average/vote across samples for best move
- Alpha-beta pruning reduces effective branching factor significantly
- Depth 4 (one full rotation) with ~5 moves per player = ~625 nodes per sample — very manageable
- 1020 samples × 625 nodes = ~6,00012,500 evaluations — runs in <100ms on modern hardware