feat(SCOPONE-0008): refresh project docs

This commit is contained in:
Giancarmine Salucci
2026-04-02 20:16:27 +02:00
parent 747da35190
commit 019c4380be
3 changed files with 333 additions and 321 deletions

View File

@@ -1,145 +1,149 @@
# Code Style
> Last Updated: 2026-03-31T00:00:00.000Z
> Last Updated: 2026-04-02T18:12:18.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
- Primary language: TypeScript 5.x.
- Compiler settings from `tsconfig.json`: `target: ES2020`, `module: ESNext`, `moduleResolution: bundler`, `strict: true`, `noEmit: true`.
- Secondary language: Java for the Capacitor Android wrapper.
## 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` |
| Kind | Convention | Real examples |
|------|------------|---------------|
| Classes | PascalCase | `BootScene`, `MenuScene`, `GameScene`, `CardTracker` |
| Interfaces | PascalCase | `Card`, `Capture`, `GameState`, `AIDecisionProgress`, `SearchProfile` |
| Type aliases | PascalCase | `Suit`, `PlayerIndex`, `Difficulty` |
| Functions | camelCase | `installFullscreenRequest`, `findCaptures`, `createInitialState`, `chooseMove`, `updateThinkBar` |
| Constants | UPPER_SNAKE or descriptive `const` names | `SUITS`, `PRIMIERA_VALUES`, `SEARCH_PROFILES`, `SCOREBAR_H` |
| Private fields | camelCase with `private` modifier | `state`, `tracker`, `thinkBar`, `selectedGlowTween` |
| Parameters and locals | camelCase | `playerIdx`, `captureChoice`, `remainingRatio`, `partnerHandSize` |
## Class & Scene Patterns
## Structural Conventions
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`.
- Phaser scenes extend `Phaser.Scene` and put setup in `create()` and asset loading in `preload()`.
- Core rule modules use exported functions and interfaces rather than classes.
- Stateful scene code uses `private` fields for long-lived UI and interaction state.
- AI configuration is table-driven through `SEARCH_PROFILES` and helper interfaces rather than nested literals inside `chooseMove()`.
## 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`
- TypeScript files use 2-space indentation.
- String literals use single quotes consistently.
- Semicolons are used consistently.
- Early returns are common for guard clauses.
- Multi-line object literals and function calls keep trailing commas when the surrounding style already uses them.
- `const` is the default; `let` is used only where reassignment is needed.
The Android Java wrapper follows the generated template style instead of the TypeScript style. `MainActivity.java` uses tab indentation and standard Android brace placement.
## Import Patterns
Named imports from local modules:
Named imports are used for local modules:
```ts
import { Card, GameState, PlayerIndex } from './types';
import { findCaptures, canCapture, calcPrimiera, teamOf } from './engine';
import { chooseMove } from '../game/ai';
import { Card, GameState, PlayerIndex, Difficulty } from './types';
import { findCaptures, canCapture, teamOf, applyMove } from './engine';
import { CardTracker } from './card-tracker';
```
Default import for Phaser:
Framework imports use default or type-only imports where appropriate:
```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.
The project uses only relative import paths. No path aliases are 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`)
- Public APIs use named exports: `export function`, `export class`, `export interface`, `export type`, `export const`.
- Default exports are reserved for configuration entry points: `vite.config.ts` and `capacitor.config.ts`.
- Internal helpers remain file-local, for example `getSubsets`, `scoreRound`, `shuffleArray`, and `alphaBeta`.
## Type Annotations
## Typing Patterns
- 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>`
- Union types model constrained domains: `PlayerIndex = 0 | 1 | 2 | 3`, `Difficulty = 'beginner' | 'advanced' | 'master'`.
- Fixed-size tuples represent stable game structures such as four players and two team scores.
- `Record<number, number>` is used for lookup tables like `PRIMIERA_VALUES`.
- Exported functions generally declare explicit return types.
- Async behavior is typed directly in signatures such as `chooseMove(...): Promise<AIMove>`.
## 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
- Section banners are used heavily in larger files:
```ts
export function applyMove(
// ---------------------------------------------------------------------------
// Turn management
// ---------------------------------------------------------------------------
```
- JSDoc appears on rule-heavy or non-obvious APIs, for example `findCaptures()`, `applyMove()`, and `CardTracker` methods.
- Scene files include `[trueref]` provenance notes near Phaser-specific APIs.
- Inline comments explain rule edge cases, heuristics, and visual-effect intent rather than restating syntax.
## Code Examples
### Guarded DOM capability checks
```ts
const installFullscreenRequest = (host: HTMLElement): void => {
const canRequestFullscreen =
typeof document.fullscreenEnabled === 'boolean'
? document.fullscreenEnabled
: typeof host.requestFullscreen === 'function';
if (!canRequestFullscreen || typeof host.requestFullscreen !== 'function') {
return;
}
};
```
### Rule-first capture selection
```ts
export function findCaptures(played: Card, table: Card[]): Card[][] {
const directMatches = table.filter(c => c.value === played.value);
if (directMatches.length > 0) {
return directMatches.map((directMatch): Card[] => [directMatch]);
}
const results: Card[][] = [];
const subsets = getSubsets(table);
for (const subset of subsets) {
if (subset.length >= 2) {
const sum = subset.reduce((acc, c) => acc + c.value, 0);
if (sum === played.value) {
results.push(subset);
}
}
}
return results;
}
```
### Async AI entry point with progress reporting
```ts
export async function chooseMove(
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;
difficulty: Difficulty = 'advanced',
tracker?: CardTracker,
onProgress?: (progress: AIDecisionProgress) => void,
): Promise<AIMove> {
const startedAt = Date.now();
const profile = getSearchProfile(state, difficulty);
reportDecisionProgress(onProgress, difficulty, startedAt, profile.timeBudgetMs, 0, 0);
// ...
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`).
No ESLint or Prettier configuration is present.
Formatting is maintained manually, with TypeScript compiler strictness acting as the main automated correctness gate. The only repository-wide verification command currently supplied is `npx tsc --noEmit`.