I rinquarti di Bertovo: gara a punti (Bertovo tira dopo Andrea, preciso secondo il livello), allenamento, posizioni misurate, traiettoria con le sponde e Prossima, comandi sicuri col dito (revisione di Codex); la Brauda in gara; voce di Bertovo (Andrea)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GiECdCPptNRwbVzjzHbohi
This commit is contained in:
2026-10-28 23:55:47 +01:00
co-authored by Claude Opus 5.5
parent bf22dc2511
commit 086e4682d4
24 changed files with 506 additions and 422 deletions
+1 -1
View File
@@ -206,7 +206,7 @@ export function drawBiliardo(ctx, c, def, bg, sheet) {
ctx.restore();
scoreboard(ctx, c, def);
const hint = canThrow(c) ? predict(c).hit : null;
const instruction = hint === 'pin' ? 'Attenzione: la tua biglia va sui birilli (fallo).'
const instruction = c.holding ? c.charging ? 'Carica iniziata: rilascia per tirare.' : 'Tieni 0,6 s per caricare; un tocco fissa la mira.' : hint === 'pin' ? 'Attenzione: la tua biglia va sui birilli (fallo).'
: hint === 'pallino' ? 'Attenzione: tocchi prima il pallino (fallo).'
: c.aimLocked ? 'Mira fissata: un altro clic la sposta.' : 'La stecca segue il mouse: clic per fissare la mira.';
ctx.fillStyle = '#17160fd9'; ctx.fillRect(54, 53, 532, 15);
+42 -10
View File
@@ -9,7 +9,7 @@ export const MIN_SPEED = 50, MAX_SPEED = 520, FRICTION = 70, DRAG = 0.35, CUSHIO
export const SWING = 1.4, FIXED_STEP = 1 / 240;
// La steccata: la stecca va avanti e tocca la biglia; solo allora parte la fisica (e il suono del colpo).
// Così il disegno mostra sempre le posizioni vere e i suoni degli urti cadono insieme alle immagini.
export const WINDUP = 0.18;
export const WINDUP = 0.18, LONG_PRESS = 0.6;
const EPS = 0.5, REST = 0.6, CPU_THINK = 0.2, CPU_SHOT = 1.5;
const CONTACT_EPS = 1e-7, BALL_RESTITUTION = 0.95;
export const OTHER = { player: 'cpu', cpu: 'player' };
@@ -169,7 +169,8 @@ function step(w, dt) {
w.events.push({ kind: hit >= rail ? 'biliardo-hit' : 'biliardo-rail', power: Math.min(1, Math.max(hit, rail) / 400) });
}
function strike(c, who, angle, power) {
export function strike(c, who, angle, power) {
c.turn = null;
const b = c.balls[who], v = speedFor(power);
c.visual.shot = { at: c.visual.time, angle, power, x: b.x, y: b.y };
c.pending = { ball: b, vx: Math.cos(angle) * v, vy: Math.sin(angle) * v, power };
@@ -242,7 +243,15 @@ export function update(c, dt, onContact) {
dt = Math.min(dt, 0.25); c.t += dt;
c.visual.time += dt;
if (c.last) c.last.age += dt;
if (c.holding) { c.holdTime += dt; c.power = powerAt(c.holdTime); }
if (c.turn && canThrow(c) && !c.holding) {
c.turn.time += dt;
c.angle += c.turn.dir * dt * (c.turn.fine ? 0.03 : 0.6 + 1.8 * Math.min(1, c.turn.time / 1.2));
}
if (c.holding) {
c.holdTime += dt;
c.charging = c.holdTime >= c.holdDelay;
if (c.charging) c.power = c.fixedPower ?? (c.holdDelay ? Math.min(1, c.previousPower + powerAt(c.holdTime - c.holdDelay)) : powerAt(c.holdTime));
}
if (c.step === 'rolling' && c.windup > 0) {
// La stecca sta arrivando: la biglia parte quando la tocca; il resto del fotogramma è già moto.
c.windup -= dt;
@@ -288,18 +297,40 @@ export function setPower(c, value) {
c.power = clamp(value, 0, 1); return true;
}
export function shoot(c) { return canThrow(c) && !c.holding && strike(c, 'player', c.angle, c.power); }
export function press(c) {
if (!canThrow(c) || c.holding) return false;
c.previousPower = c.power; c.holding = true; c.holdTime = c.power = 0; return true;
// Una pressione continua ruota senza dipendere dalla ripetizione della tastiera.
export function turn(c, dir, owner, fine = false) {
if (!canThrow(c) || c.holding || c.turn) return false;
c.turn = { dir, owner, fine, time: 0 }; c.angle += dir * (fine ? 0.0005 : 0.03);
c.aimLocked = true; return true;
}
export function cancel(c) {
export function stopTurn(c, owner) {
if (c.turn?.owner !== owner) return false;
c.turn = null; return true;
}
export function key(c, key, down, fine = false) {
if (!['ArrowLeft', 'ArrowRight'].includes(key)) return false;
if (down) { if (c.turn?.owner === key) c.turn.fine = fine; else turn(c, key === 'ArrowLeft' ? -1 : 1, key, fine); }
else stopTurn(c, key);
return true;
}
export function press(c, pointerId) {
if (!canThrow(c) || c.holding) return false;
c.turn = null; c.pointerId = pointerId; c.holdDelay = pointerId === undefined ? 0 : LONG_PRESS;
c.previousPower = c.power; c.holding = true; c.charging = false; c.holdTime = 0;
if (!c.holdDelay && c.fixedPower === undefined) c.power = 0;
return true;
}
export function cancel(c, pointerId) {
if (pointerId !== undefined && c.pointerId !== pointerId) return false;
c.turn = null; c.charging = false;
if (!c.holding) return false;
c.holding = false; c.power = c.previousPower; c.holdTime = 0; return true;
}
export function release(c) {
export function release(c, pointerId) {
if (c.pointerId !== pointerId) return false;
if (!c.holding) return false;
if (c.holdTime < 0.14) return cancel(c); // un tocco breve mira soltanto
c.holding = false; return strike(c, 'player', c.angle, c.power);
if (c.holdTime < Math.max(0.14, c.holdDelay)) return cancel(c, pointerId); // il tocco mira soltanto
c.holding = c.charging = false; return strike(c, 'player', c.angle, c.power);
}
// La guida riproduce il tiro su una copia, con gli stessi urti e lo stesso attrito.
@@ -363,6 +394,7 @@ export function status(c, names) {
if (c.step === 'result') return `Partita a ${names[c.result.winner]}: ${c.points.player} a ${c.points.cpu}.`;
if (c.step === 'rolling') return 'Biglie in movimento…';
if (c.step === 'settle') return 'Si contano i birilli…';
if (c.holding) return c.charging ? 'Carica iniziata: rilascia per tirare.' : 'Mira fissata. Tieni 0,6 s per iniziare la carica.';
const last = lastLine(c, names);
return `${last ? last + ' ' : ''}${names[c.current]} al tiro. (${c.points.player} a ${c.points.cpu}, si va a ${c.target})`;
}
+3 -3
View File
@@ -313,9 +313,9 @@ export class Game {
// Bocce e biliardo: si tiene premuto per caricare la forza e si lascia per tirare (mouse, dito o spazio).
minigame() { const c = this.closeup; return c ? MINIGAMES[this.story.closeups[c.id].type] ?? null : null; }
closeupPress() { const m = this.minigame(); return !!m && !this.speech && !!m.press?.(this.closeup); }
closeupRelease() { return !!this.minigame()?.release?.(this.closeup); }
closeupCancel() { return !!this.minigame()?.cancel?.(this.closeup); }
closeupPress(pointerId) { const m = this.minigame(); return !!m && !this.speech && !!m.press?.(this.closeup, pointerId); }
closeupRelease(pointerId) { return !!this.minigame()?.release?.(this.closeup, pointerId); }
closeupCancel(pointerId) { return !!this.minigame()?.cancel?.(this.closeup, pointerId); }
closeupPlay(index) { return !this.speech && !!this.minigame()?.play?.(this.closeup, index); }
// Solo luce, nessun clic sugli oggetti dietro al primo piano. Il progresso è transitorio:
+45 -17
View File
@@ -1,9 +1,28 @@
import { LEN, WID, R, VIEW, WINDUP } from './biliardo.js';
import { table, sphere, pin, cue } from './biliardo-render.js';
import { guide, canThrow } from './rinquarto.js';
import { guide, canThrow, shooter } from './rinquarto.js';
import { text, panel } from './bocce-render.js';
const sx = x => VIEW.x + x * VIEW.k, sy = y => VIEW.y + y * VIEW.k;
const NAME = { andrea: 'Andrea', bertovo: 'Bertovo' };
// La traiettoria del tiro: resta sul tavolo finché non si va avanti, con le sponde numerate e il contatto che decide.
function trail(ctx, c) {
if (c.trail.length < 2) return;
const good = c.attempt.point, done = c.step === 'review';
ctx.strokeStyle = done ? (good ? '#b9e5b3' : '#ffbf9f') : '#fff8dccc'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(sx(c.trail[0][0]), sy(c.trail[0][1]));
for (const [x, y] of c.trail.slice(1)) ctx.lineTo(sx(x), sy(y));
ctx.stroke();
c.attempt.marks.forEach((m, i) => {
ctx.fillStyle = '#17160f'; ctx.beginPath(); ctx.arc(sx(m.x), sy(m.y), 5, 0, Math.PI * 2); ctx.fill();
text(ctx, String(i + 1), sx(m.x), sy(m.y) + 0.5, 7, '#ffe28a', 'center');
});
if (done && c.attempt.hit) {
const { x, y } = c.attempt.hit;
ctx.strokeStyle = good ? '#b9e5b3' : '#ff6a4a'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(sx(x), sy(y), R * VIEW.k + 4, 0, Math.PI * 2); ctx.stroke();
}
}
export function drawRinquarto(ctx, c, def, bg) {
ctx.save(); ctx.imageSmoothingEnabled = false;
table(ctx, bg);
@@ -17,33 +36,42 @@ export function drawRinquarto(ctx, c, def, bg) {
ctx.stroke(); ctx.setLineDash([]);
}
const b = c.balls.player;
cue(ctx, b.x, b.y, c.angle, R * VIEW.k + 6 + c.power * 26);
cue(ctx, b.x, b.y, c.angle, R * VIEW.k + 6 + (c.charging ? 26 : 10));
} else if (c.visual.shot && c.windup > 0) {
const s = c.visual.shot;
cue(ctx, s.x, s.y, s.angle, R * VIEW.k + (6 + s.power * 26) * c.windup / WINDUP);
cue(ctx, s.x, s.y, s.angle, R * VIEW.k + 32 * c.windup / WINDUP);
}
trail(ctx, c);
for (const p of c.pins) pin(ctx, p, c.visual.time);
// Il bersaglio ha un anello che pulsa; i disturbi una croce grossa, che si vede anche sul telefono.
const tgt = c.balls.cpu, pulse = 1 + Math.sin(c.visual.time * 4) * 0.5;
ctx.strokeStyle = '#ffe28a'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(sx(tgt.x), sy(tgt.y), R * VIEW.k + 3 + pulse, 0, Math.PI * 2); ctx.stroke();
for (const b of Object.values(c.balls)) {
sphere(ctx, b.role, sx(b.x), sy(b.y), R * VIEW.k);
// La croce distingue i disturbi anche senza riconoscere il colore viola.
if (!['player', 'cpu'].includes(b.role)) {
ctx.strokeStyle = '#2b163e'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(sx(b.x) - 2, sy(b.y) - 2); ctx.lineTo(sx(b.x) + 2, sy(b.y) + 2);
ctx.moveTo(sx(b.x) + 2, sy(b.y) - 2); ctx.lineTo(sx(b.x) - 2, sy(b.y) + 2); ctx.stroke();
const k = R * VIEW.k;
ctx.strokeStyle = '#1b0d29'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(sx(b.x) - k, sy(b.y) - k); ctx.lineTo(sx(b.x) + k, sy(b.y) + k);
ctx.moveTo(sx(b.x) + k, sy(b.y) - k); ctx.lineTo(sx(b.x) - k, sy(b.y) + k); ctx.stroke();
}
}
ctx.restore();
// In alto: chi tira, il punteggio, le sponde; l'esito sta qui, così non copre il tavolo.
ctx.fillStyle = '#17160ff0'; ctx.fillRect(54, 4, 532, 64);
text(ctx, 'I RINQUARTI DI BERTOVO', 320, 13, 9, '#efd49e', 'center');
text(ctx, `Posizione ${c.position}/${c.skill.positions} Punti ${c.points}/${c.skill.glory} Sponde ${c.attempt.cushions}/${c.skill.cushions}`, 320, 28, 8, '#fff0c8', 'center');
text(ctx, canThrow(c) ? `Bianca: ${def.names.player} · Gialla: bersaglio · Viola e birilli: disturbi` : c.line, 320, 43, 7, '#d9ccba', 'center');
text(ctx, canThrow(c) ? `«Oh tirami questo rinquarto!?» Forza ${Math.round(c.power * 100)}%` : c.step === 'rolling' ? 'Biglie in movimento…' : 'Un tiro per posizione.', 320, 59, 8, '#9fd0ff', 'center');
if (c.step === 'settle' || c.step === 'result') {
const final = c.step === 'result';
panel(ctx, 155, 145, 330, final ? 96 : 58);
text(ctx, c.attempt.point ? 'Punto!' : 'Niente', 320, 164, 12, c.attempt.point ? '#b9e5b3' : '#ffbf9f', 'center');
text(ctx, final ? `${c.result.winner === 'player' ? 'GLORIA!' : 'SFIDA PERSA'} ${c.points} punti su ${c.skill.positions}` : c.attempt.point ? 'Rinquarto riuscito.' : c.attempt.reason, 320, 188, 8, '#efd49e', 'center');
if (final) text(ctx, `Obiettivo: ${c.skill.glory}. Torna da Bertovo per uscire.`, 320, 221, 7, '#d9ccba', 'center');
text(ctx, c.skill.training ? 'I RINQUARTI DI BERTOVO · ALLENAMENTO' : 'I RINQUARTI DI BERTOVO', 320, 13, 9, '#efd49e', 'center');
const score = c.skill.training ? 'senza punti' : `Andrea ${c.score.andrea} Bertovo ${c.score.bertovo}`;
text(ctx, `Posizione ${c.position}/${c.skill.positions} ${score} Sponde ${c.attempt.cushions}/${c.skill.cushions}`, 320, 29, 9, '#fff0c8', 'center');
const who = NAME[shooter(c)];
const line = c.step === 'review' ? c.line : c.step === 'think' ? 'Tira Bertovo…' : c.step === 'rolling' ? `Tira ${who}…` : `Tocca ad ${who}: «Oh tirami questo rinquarto!?»`;
text(ctx, line, 320, 45, 8, c.step === 'review' ? (c.attempt.point ? '#b9e5b3' : '#ffbf9f') : '#9fd0ff', 'center');
if (c.step === 'review') text(ctx, c.last ? 'Tocca per il risultato' : 'Tocca o premi Prossima', 320, 59, 7, '#d9ccba', 'center');
if (c.step === 'result') {
const r = c.result, title = r.training ? 'ALLENAMENTO FINITO' : r.winner === 'player' ? 'HAI BATTUTO BERTOVO!' : r.winner === 'cpu' ? 'HA VINTO BERTOVO' : 'PARI';
panel(ctx, 155, 145, 330, 80);
text(ctx, title, 320, 166, 12, r.winner === 'player' ? '#b9e5b3' : '#efd49e', 'center');
if (!r.training) text(ctx, `Andrea ${r.points.andrea} · Bertovo ${r.points.bertovo}, su ${c.skill.positions} posizioni`, 320, 190, 8, '#efd49e', 'center');
text(ctx, 'Torna da Bertovo per uscire.', 320, 210, 8, '#d9ccba', 'center');
}
ctx.restore();
}
+179 -78
View File
@@ -1,120 +1,214 @@
// I rinquarti di Bertovo: posizioni coperte, un solo tentativo per posizione.
// I rinquarti di Bertovo (Andrea, 28 ottobre; revisione di Codex): Bertovo mette le biglie in modo che la diretta sia
// coperta, e si deve arrivare al bersaglio (la gialla) dopo almeno tante sponde senza toccare prima i disturbi.
// Sulla stessa posizione tira prima Andrea, poi il tavolo torna com'era e tira Bertovo: un punto per ogni rinquarto
// riuscito, sei posizioni, vince chi ne fa di più. Nell'allenamento tira prima Bertovo, per far vedere, e senza punti.
//
// La forza è sempre piena: conta solo il primo contatto, quindi tirare piano non serve mai (revisione di Codex,
// rilievo 5). Il gioco è un rompicapo di angoli.
import * as billiard from './biliardo.js';
const { LEN, WID, R, PIN, simulate, predict } = billiard;
export { aimAt, aimScreen, nudge, setPower, press, release, cancel, shoot, canThrow } from './biliardo.js';
export { aimAt, aimScreen, nudge, release, cancel, turn, stopTurn, key } from './biliardo.js';
// `cushions`: sponde da fare prima del bersaglio. `width`: la finestra di angoli buoni (in gradi, a forza piena) che
// una posizione deve avere, dalla prima all'ultima: le posizioni si fanno più strette man mano. `bertovo`: quanto è
// preciso lui (la probabilità di stare dentro la finestra), dal più distratto al più spietato.
export const LEVELS = {
bona: { positions: 6, cushions: 1, glory: 3, guideBounces: 2, guideLength: Infinity },
seria: { positions: 6, cushions: 2, glory: 3, guideBounces: 1, guideLength: 65 },
male: { positions: 6, cushions: 3, glory: 2, guideBounces: 0, guideLength: 0 },
allenamento: { positions: 3, cushions: 1, width: [5, 4], bertovo: 1, guideBounces: 2, guideLength: Infinity, training: true },
bona: { positions: 6, cushions: 1, width: [5, 2.5], bertovo: 0.45, guideBounces: 2, guideLength: Infinity },
seria: { positions: 6, cushions: 2, width: [3, 1.5], bertovo: 0.65, guideBounces: 1, guideLength: 65 },
male: { positions: 6, cushions: 3, width: [2, 1], bertovo: 0.88, guideBounces: 0, guideLength: 0 },
};
export const canAdjust = c => billiard.canThrow(c) && !c.holding;
export const aimFree = c => !billiard.canThrow(c);
export const button = c => c.step === 'result' ? 'Finita' : c.step === 'aim' ? 'Tira' : 'In movimento…';
// BUDGET: prove a vuoto per fotogramma mentre si prepara la posizione dopo (una costa circa 0,2 ms su un PC).
const SCAN = 720, STEP_ANGLE = Math.PI * 2 / SCAN, BUDGET = 15, THINK = 1.1;
const ball = (role, x, y) => ({ role, x, y, vx: 0, vy: 0 });
function random(c) { c.seed = (Math.imul(c.seed, 1664525) + 1013904223) >>> 0; return c.seed / 4294967296; }
const attempt = () => ({ cushions: 0, decided: false, point: false, reason: null });
const gauss = c => Math.sqrt(-2 * Math.log(1 - random(c))) * Math.cos(2 * Math.PI * random(c));
// z tale che una normale stia entro ±z con probabilità p: quanto deve essere stretto l'errore di Bertovo.
const zFor = p => p >= 1 ? Infinity : Math.sqrt(2) * erfinv(p);
function erfinv(x) {
const a = 0.147, l = Math.log(1 - x * x), t = 2 / (Math.PI * a) + l / 2;
return Math.sign(x) * Math.sqrt(Math.sqrt(t * t - l / a) - t);
}
const attempt = () => ({ cushions: 0, decided: false, point: false, reason: null, marks: [], hit: null });
// Conta solo le sponde della propria biglia prima del primo ostacolo.
export const shooter = c => c.order[c.round ?? 0];
// Si può mirare e tirare solo quando tocca ad Andrea (la biglia, per il biliardo, è sempre quella «player»).
export const canThrow = c => c.step === 'aim' && shooter(c) === 'andrea';
export const canAdjust = c => canThrow(c) && !c.holding;
// Il pulsante del pannello: Tira quando tocca ad Andrea, Prossima mentre si guarda l'esito.
export const canPress = c => canThrow(c) || c.step === 'review';
export const aimFree = c => !canThrow(c);
export const setPower = () => false; // la forza è sempre piena
export const button = c => c.step === 'review' ? (c.last ? 'Finita' : 'Prossima') : c.step === 'result' ? 'Finita'
: c.step === 'think' ? 'Tira Bertovo…' : c.step === 'aim' ? 'Tira' : 'In movimento…';
// Conta solo le sponde della bianca prima del primo ostacolo; il primo contatto decide.
function contact(result, required, { kind, a, b }) {
if (result.decided || (a.role !== 'player' && b?.role !== 'player')) return;
if (kind === 'rail') { result.cushions++; return; }
if (kind === 'rail') { result.cushions++; result.marks.push({ x: a.x, y: a.y }); return; }
result.decided = true;
const other = a.role === 'player' ? b : a;
const white = a.role === 'player' ? a : b, other = white === a ? b : a;
result.hit = { x: white.x, y: white.y };
result.point = kind === 'ball' && other.role === 'cpu' && result.cushions >= required;
result.reason = result.point ? null : kind === 'ball' && other.role === 'cpu' ? 'poche sponde' : 'disturbo toccato';
}
export function tryShot(c, angle, power) {
const result = attempt();
simulate(c, 'player', angle, power, {
onContact: event => contact(result, c.skill.cushions, event),
stop: () => result.decided,
});
// Il tiro provato a vuoto, su una disposizione qualunque (quella in gioco se non se ne passa un'altra).
export function tryShot(c, angle, power = 1, layout = null) {
const w = layout ? { ...c, balls: layout.balls, pins: layout.pins } : c, result = attempt();
simulate(w, 'player', angle, power, { onContact: event => contact(result, c.skill.cushions, event), stop: () => result.decided });
if (!result.decided) result.reason = 'bersaglio mancato';
return result;
}
// Distanza dal segmento dei centri, con i raggi sommati (biglia in movimento inclusa).
export function directCovered(c) {
const a = c.balls.player, b = c.balls.cpu, dx = b.x - a.x, dy = b.y - a.y, d2 = dx * dx + dy * dy;
if (!d2) return false;
const obstacles = [...Object.values(c.balls).filter(b => !['player', 'cpu'].includes(b.role)).map(b => ({ ...b, radius: R })),
...c.pins.filter(p => !p.down).map(p => ({ ...p, radius: PIN }))];
return obstacles.some(p => {
const t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / d2;
return t > 0 && t < 1 && Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy) < R + p.radius;
});
// Coperta: lungo la linea dei centri il primo urto della bianca non è il bersaglio (si confrontano le distanze del
// primo impatto, non solo la vicinanza alla linea: revisione di Codex, rilievo 8).
export function directCovered(c, layout = c) {
const a = layout.balls.player, b = layout.balls.cpu, dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy);
if (!d) return false;
const ux = dx / d, uy = dy / d;
const impact = (p, radius) => {
const t = (p.x - a.x) * ux + (p.y - a.y) * uy, off = Math.hypot(p.x - a.x - t * ux, p.y - a.y - t * uy), reach = R + radius;
return t > 0 && off < reach ? t - Math.sqrt(reach * reach - off * off) : Infinity;
};
const target = impact(b, R);
const obstacles = [...Object.values(layout.balls).filter(x => !['player', 'cpu'].includes(x.role)).map(x => impact(x, R)),
...layout.pins.filter(p => !p.down).map(p => impact(p, PIN))];
return obstacles.some(t => t < target);
}
export function solve(c) {
// Angoli intercalati: si esplora subito tutto il tavolo, poi si affina a mezzo grado.
for (let offset = 0; offset < 8; offset++) for (let i = offset; i < 720; i += 8) {
const angle = i * Math.PI / 360;
for (const power of [1, 0.82, 0.65]) {
if (tryShot(c, angle, power).point) return { angle, power };
// Una disposizione a caso: bianca e gialla lontane, un disturbo in mezzo, un altro e due birilli sparsi.
function candidate(c) {
const place = role => ball(role, 20 + random(c) * (LEN - 40), 18 + random(c) * (WID - 36));
const player = place('player'), cpu = place('cpu');
if (Math.hypot(cpu.x - player.x, cpu.y - player.y) < 70) return null;
const t = 0.3 + random(c) * 0.4;
const blocker = ball('blocker', player.x + (cpu.x - player.x) * t, player.y + (cpu.y - player.y) * t);
const layout = { balls: { player, cpu, blocker, extra: place('extra') },
pins: Array.from({ length: 2 }, () => ({ x: 20 + random(c) * (LEN - 40), y: 18 + random(c) * (WID - 36), red: false, down: false })) };
const objects = [...Object.values(layout.balls).map(b => ({ ...b, radius: R })), ...layout.pins.map(p => ({ ...p, radius: PIN }))];
if (objects.some((a, i) => objects.slice(i + 1).some(b => Math.hypot(a.x - b.x, a.y - b.y) < a.radius + b.radius + 2))) return null;
return directCovered(c, layout) ? layout : null;
}
// Le finestre di angoli buoni (a forza piena), dalle prove fatte: gruppi di angoli vicini che fanno punto.
function windows(hits) {
const out = [];
for (let i = 0; i < SCAN; i++) {
if (!hits[i] || hits[(i - 1 + SCAN) % SCAN]) continue;
let n = 0; const cushions = [];
while (hits[(i + n) % SCAN] && n < SCAN) { cushions.push(hits[(i + n) % SCAN]); n++; }
const middle = cushions[Math.floor(n / 2)];
out.push({ angle: (i + (n - 1) / 2) * STEP_ANGLE, width: n * 360 / SCAN, cushions: middle });
}
return out;
}
// La finestra che deve avere la posizione numero k (da 0): dalla più larga alla più stretta.
const widthFor = (skill, k) => skill.width[0] + (skill.width[1] - skill.width[0]) * (skill.positions > 1 ? k / (skill.positions - 1) : 0);
// Il generatore lavora a pezzi (BUDGET prove alla volta), così il gioco non si ferma mentre prepara la posizione dopo.
function generate(c, budget) {
let g = c.gen;
while (budget > 0) {
if (!g) {
const layout = candidate(c);
if (!layout) { budget--; continue; }
g = c.gen = { layout, i: 0, hits: new Array(SCAN).fill(0) };
}
for (; g.i < SCAN && budget > 0; g.i++, budget--) {
const r = tryShot(c, g.i * STEP_ANGLE, 1, g.layout);
if (r.point) g.hits[g.i] = r.cushions;
}
if (g.i < SCAN) return null;
c.gen = null;
const k = c.ready.length + c.position, need = widthFor(c.skill, k);
// Si preferisce una finestra col numero giusto di sponde; alla bona deve esserci per forza.
const all = windows(g.hits), exact = all.filter(w => w.cushions === c.skill.cushions);
const pool = exact.length || c.skill.cushions === 1 ? exact : all;
const best = pool.sort((a, b) => b.width - a.width)[0];
if (best && best.width >= need) return { layout: g.layout, solution: { angle: best.angle, power: 1, width: best.width, cushions: best.cushions } };
g = null;
}
return null;
}
const copy = layout => ({ balls: Object.fromEntries(Object.entries(layout.balls).map(([k, b]) => [k, { ...b }])), pins: layout.pins.map(p => ({ ...p })) });
function position(c) {
for (;;) {
const place = role => ball(role, 20 + random(c) * (LEN - 40), 18 + random(c) * (WID - 36));
const player = place('player'), cpu = place('cpu');
if (Math.hypot(cpu.x - player.x, cpu.y - player.y) < 70) continue;
const t = 0.3 + random(c) * 0.4;
const blocker = ball('blocker', player.x + (cpu.x - player.x) * t, player.y + (cpu.y - player.y) * t);
c.balls = { player, cpu, blocker, extra: place('extra') };
c.pins = Array.from({ length: 2 }, () => ({ x: 20 + random(c) * (LEN - 40), y: 18 + random(c) * (WID - 36), red: false, down: false }));
const objects = [...Object.values(c.balls).map(b => ({ ...b, radius: R })), ...c.pins.map(p => ({ ...p, radius: PIN }))];
if (objects.some((a, i) => objects.slice(i + 1).some(b => Math.hypot(a.x - b.x, a.y - b.y) < a.radius + b.radius + 2))) continue;
if (!directCovered(c)) continue;
const solution = solve(c);
if (!solution) continue;
c.solution = solution;
break;
}
c.position++;
c.step = 'aim'; c.t = c.accumulator = 0; c.power = 0.75; c.holding = false; c.aimLocked = false;
c.shot = c.pending = c.visual.shot = null; c.windup = 0;
// Prepara il tavolo per chi tira adesso, sempre dalla disposizione di partenza della posizione.
function setTable(c) {
const fresh = copy(c.start);
c.balls = fresh.balls; c.pins = fresh.pins;
c.step = shooter(c) === 'andrea' ? 'aim' : 'think';
c.t = c.accumulator = 0; c.power = 1; c.holding = false; c.charging = false; c.aimLocked = false; c.plan = null;
c.shot = c.pending = c.visual.shot = null; c.windup = 0; c.trail = [];
c.angle = Math.atan2(c.balls.cpu.y - c.balls.player.y, c.balls.cpu.x - c.balls.player.x);
c.attempt = attempt();
c.line = 'Bertovo: «Oh tirami questo rinquarto!?»';
c.line = shooter(c) === 'andrea' ? 'Bertovo: «Oh tirami questo rinquarto!?»' : 'Tira Bertovo…';
}
function nextPosition(c) {
while (!c.ready.length) { const p = generate(c, 4000); if (p) c.ready.push(p); }
const p = c.ready.shift();
c.position++; c.start = copy(p.layout); c.solution = p.solution; c.round = 0;
setTable(c);
}
export function newRinquarto(seed = Date.now() >>> 0, def = {}) {
const level = LEVELS[def.level] ? def.level : 'seria';
const c = { ...billiard.newBiliardo(seed), level, skill: LEVELS[level], position: 0, points: 0, history: [] };
position(c);
const c = { ...billiard.newBiliardo(seed), level, skill: LEVELS[level], position: 0, score: { andrea: 0, bertovo: 0 }, history: [],
order: LEVELS[level].training ? ['bertovo', 'andrea'] : ['andrea', 'bertovo'], ready: [], gen: null, fixedPower: 1, trail: [], last: false };
nextPosition(c);
return c;
}
// Bertovo mira al centro della finestra buona, con un errore che dipende dal livello: dentro la finestra con la
// probabilità `bertovo`. Il tiro poi si fa davvero: se sbaglia, sbaglia sul panno.
export function bertovoPlan(c) {
const half = c.solution.width / 2 * Math.PI / 180, z = zFor(c.skill.bertovo);
return { angle: c.solution.angle + (Number.isFinite(z) ? gauss(c) * half / z : 0), power: 1 };
}
// Dopo l'esito, un tocco (o Prossima) va avanti: tocca all'altro sulla stessa posizione, o alla posizione dopo.
export function advance(c) {
if (c.step !== 'review') return false;
if (c.round < c.order.length - 1) { c.round++; setTable(c); return true; }
if (c.position >= c.skill.positions) { finish(c); return true; }
nextPosition(c);
return true;
}
function finish(c) {
const { andrea, bertovo } = c.score;
c.step = 'result';
c.result = { winner: c.skill.training ? 'draw' : andrea > bertovo ? 'player' : andrea < bertovo ? 'cpu' : 'draw', points: { ...c.score }, training: !!c.skill.training };
}
// Mentre si guarda l'esito, Spazio, Invio, un tocco sul tavolo o il pulsante vanno avanti.
export function press(c, pointerId) { return c.step === 'review' ? advance(c) : billiard.press(c, pointerId); }
export function shoot(c) { return c.step === 'review' ? advance(c) : canThrow(c) && !c.holding && billiard.strike(c, 'player', c.angle, 1); }
export function update(c, dt) {
if (!Number.isFinite(dt) || dt <= 0) return;
dt = Math.min(dt, 0.25);
if (c.step === 'result') {
// L’ultimo birillo può essere ancora in caduta: il riepilogo ferma la partita, non l’animazione.
c.visual.time += dt;
return;
}
if (c.step === 'settle') {
c.t += dt;
// I birilli finiscono di cadere anche mentre si legge l'esito del tiro.
c.visual.time += dt;
if (c.t >= 1.8) position(c);
// Intanto si prepara la posizione dopo, un po' per volta.
if (c.position + c.ready.length < c.skill.positions) { const p = generate(c, BUDGET); if (p) c.ready.push(p); }
// L'ultimo birillo può essere ancora in caduta: l'animazione va avanti anche fermi sull'esito.
if (c.step === 'result' || c.step === 'review') { c.visual.time += dt; return; }
if (c.step === 'think') {
c.t += dt; c.visual.time += dt;
if (c.t >= THINK) { const plan = bertovoPlan(c); billiard.strike(c, 'player', plan.angle, plan.power); }
return;
}
const before = c.step;
billiard.update(c, dt, event => contact(c.attempt, c.skill.cushions, event));
if (c.step !== 'settle') return;
if (!c.attempt.decided) c.attempt.reason = 'bersaglio mancato';
c.points += Number(c.attempt.point);
c.history.push({ ...c.attempt });
c.line = c.attempt.point ? 'Punto!' : `Niente: ${c.attempt.reason}.`;
if (c.position === c.skill.positions) {
c.step = 'result';
c.result = { winner: c.points >= c.skill.glory ? 'player' : 'cpu', points: c.points };
if (c.step === 'rolling' && !c.windup) {
const b = c.balls.player, last = c.trail.at(-1);
if (!last || Math.hypot(last[0] - b.x, last[1] - b.y) > 1.5) c.trail.push([b.x, b.y]);
}
if (before !== 'rolling' || c.step !== 'settle') return;
// Il tiro è finito: l'esito resta sul tavolo, con la traiettoria, finché non si va avanti.
if (!c.attempt.decided) c.attempt.reason = 'bersaglio mancato';
const who = shooter(c);
if (!c.skill.training) c.score[who] += Number(c.attempt.point);
c.history.push({ position: c.position, who, ...c.attempt });
c.line = `${who === 'andrea' ? 'Andrea' : 'Bertovo'}: ${c.attempt.point ? 'punto!' : `niente, ${c.attempt.reason}.`}`;
c.step = 'review';
c.last = c.round === c.order.length - 1 && c.position >= c.skill.positions;
}
// La guida si ferma al contatto, al limite di lunghezza o alla sponda consentita.
@@ -130,9 +224,16 @@ export function guide(c) {
return points;
}
const need = c => c.skill.cushions === 1 ? 'Serve almeno 1 sponda.' : `Servono almeno ${c.skill.cushions} sponde.`;
export function status(c) {
const prefix = `Posizione ${c.position} di ${c.skill.positions}. Punti: ${c.points}.`;
if (c.step === 'result') return `${prefix} ${c.line} ${c.result.winner === 'player' ? 'Gloria!' : 'Sfida persa.'} Obiettivo: ${c.skill.glory}.`;
const score = c.skill.training ? 'Allenamento, senza punti.' : `Andrea ${c.score.andrea}, Bertovo ${c.score.bertovo}.`;
const prefix = `Posizione ${c.position} di ${c.skill.positions}. ${score}`;
if (c.step === 'result') {
if (c.result.training) return 'Allenamento finito. Quando vuoi, la sfida vera.';
return `${prefix} ${c.result.winner === 'player' ? 'Hai battuto Bertovo!' : c.result.winner === 'cpu' ? 'Ha vinto Bertovo.' : 'Pari.'}`;
}
if (c.step === 'review') return `${prefix} ${c.line} ${c.last ? 'Tocca per il risultato.' : 'Tocca o premi Prossima.'}`;
if (c.step === 'think') return `${prefix} Tira Bertovo…`;
if (c.step === 'rolling') return `${prefix} Sponde: ${c.attempt.cushions}/${c.skill.cushions}.`;
return `${prefix} ${c.line} ${c.skill.cushions === 1 ? 'Serve almeno 1 sponda.' : `Servono almeno ${c.skill.cushions} sponde.`}`;
return `${prefix} ${c.line} ${need(c)}`;
}
+33 -11
View File
@@ -507,15 +507,16 @@ canvas.addEventListener('pointerdown', e => {
if (gara.press(game.closeup, e.pointerId)) { press = { gara: e.pointerId }; canvas.setPointerCapture(e.pointerId); }
return;
}
if (press?.closeup) return;
const aimed = game.closeupAim(scenePoint(e));
if (['biliardo', 'rinquarto', 'basket'].includes(story.closeups[game.closeup.id].type)) {
if (!aimed && !game.speech) return; // dove non si può mirare (dietro Andrea) non si carica nemmeno
if (aimed) game.closeup.aimLocked = true; // il clic fissa la mira
}
if (['bocce', 'basket', 'pesca'].includes(story.closeups[game.closeup.id].type) && aimed) game.closeup.aimLocked = true;
press = { closeup: true };
press = { closeup: true, pointerId: e.pointerId, state: game.closeup };
// Alle bocce si tiene premuto per caricare la forza (la battuta in corso, un tocco la salta).
if (!game.skip()) game.closeupPress();
if (!game.skip()) game.closeupPress(e.pointerId);
canvas.setPointerCapture(e.pointerId);
return;
}
@@ -543,7 +544,12 @@ canvas.addEventListener('pointerup', e => {
if (e.pointerId === press.gara) { if (game?.closeup) gara.release(game.closeup, e.pointerId); press = null; }
return;
}
if (press.closeup) { press = null; if (running && !game.closeupRelease() && !game.skip()) game.closeupTap(); return; }
if (press.closeup) {
if (e.pointerId !== press.pointerId) return;
const state = press.state; press = null;
if (running && game.closeup === state && !game.closeupRelease(e.pointerId) && !game.skip()) game.closeupTap();
return;
}
clearTimeout(press.timer);
// Il secondo clic vicino al primo, entro poco, è un doppio clic: stesso comando, al doppio della velocità.
if (!press.long) {
@@ -554,8 +560,13 @@ canvas.addEventListener('pointerup', e => {
}
press = null;
});
canvas.addEventListener('pointercancel', () => { if (press) clearTimeout(press.timer); press = null; game?.closeupCancel(); });
canvas.addEventListener('lostpointercapture', () => { if (press?.closeup || press?.gara !== undefined || press?.card !== undefined || press?.table !== undefined) { press = null; game?.closeupCancel(); } });
canvas.addEventListener('pointercancel', e => {
if (press?.closeup && e.pointerId !== press.pointerId) return;
if (press) clearTimeout(press.timer);
if (!press?.closeup || game?.closeup === press.state) game?.closeupCancel(e.pointerId);
press = null;
});
canvas.addEventListener('lostpointercapture', e => { if (press?.closeup && e.pointerId !== press.pointerId) return; if (press?.closeup || press?.gara !== undefined || press?.card !== undefined || press?.table !== undefined) { press = null; game?.closeupCancel(e.pointerId); } });
canvas.addEventListener('contextmenu', e => {
e.preventDefault();
if (running && !game.closeup) command.clickScene(scenePoint(e), { look: true });
@@ -590,7 +601,7 @@ const MINI = {
briscola: { ...briscola, back: 'Torna all’oratorio', label: 'Briscola: tocca una carta per giocarla. Frecce o 1, 2, 3 scelgono; Invio gioca. Esc esce.' },
bocce: { ...bocce, nudge: (c, dir) => bocce.aim(c, c.aim.u, c.aim.w + dir * 0.3), back: 'Torna al pallaio', label: 'Bocce: tocca il campo o il dettaglio per mirare. Regola la forza e premi Lancia.' },
biliardo: { ...biliardo, back: 'Torna al bar', label: 'Biliardo: clic o tocco fissa la mira. Frecce per affinarla, Maiusc per passi più piccoli. Regola la forza e premi Tira.' },
rinquarto: { ...rinquarto, back: 'Torna da Bertovo', label: 'I rinquarti di Bertovo: clic o tocco fissa la mira. Frecce per affinarla, Maiusc per passi più piccoli. Regola la forza e premi Tira.' },
rinquarto: { ...rinquarto, back: 'Torna da Bertovo', label: 'I rinquarti di Bertovo: clic o tocco fissa la mira, frecce o pulsanti Mira per girare la stecca (Maiusc per i passi fini), Tira per tirare. Dopo l’esito, Prossima.' },
basket: { ...basket, back: 'Torna in strada', label: 'Fai due tiri: muovi il mouse o tocca per mirare, tieni premuto per caricare la forza, lascia per tirare.' },
// La gara: niente mira né forza, il pulsante alterna gas e freno (chi non può tenere premuto).
gara: { ...gara, toggle: true, back: 'Torna dal Trappola', label: 'GP di Fortezza: tieni premuto sulla scena per il gas e trascina verso la direzione in cui vuoi andare sullo schermo; alza il dito per mollare. Anche col mouse. Oppure Spazio, Invio o ↑ per il gas, ← → per sterzare, ↓ per frenare; disponibili anche i pulsanti Gas, Sterza e Frena.' },
@@ -645,7 +656,16 @@ for (let i = 0; i < 3; i++) {
button.addEventListener('focus', () => { if (game?.closeup?.id === 'briscola') briscola.select(game.closeup, i); });
}
for (const [id, dir] of [['bocce-left', -1], ['bocce-right', 1]]) {
$(id).addEventListener('click', () => { const c = miniState(); if (c && mini().nudge(c, dir)) c.aimLocked = true; });
$(id).addEventListener('click', e => { const c = miniState(); if (!c) return;
if (mini().turn) { if (!e.detail) { mini().turn(c, dir, 'click'); mini().stopTurn(c, 'click'); } }
else if (mini().nudge(c, dir)) c.aimLocked = true;
});
$(id).addEventListener('pointerdown', e => { const c = miniState();
if (c && mini().turn?.(c, dir, e.pointerId)) $(id).setPointerCapture(e.pointerId);
});
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) $(id).addEventListener(ev, e => {
const c = miniState(); if (c) mini().stopTurn?.(c, e.pointerId);
});
// Al GP di Fortezza si sterza finché il pulsante resta premuto (anche col dito, insieme a Gas).
$(id).addEventListener('pointerdown', () => { const c = miniState(); if (c) mini().steerButton?.(c, dir); });
for (const ev of ['pointerup', 'pointerleave', 'pointercancel']) $(id).addEventListener(ev, () => { const c = miniState(); if (c) mini().steerButton?.(c, 0); });
@@ -821,8 +841,8 @@ window.addEventListener('keydown', e => {
if (e.key === 'Escape') { game.closeupClose(); return; }
const onButton = ['BUTTON', 'SUMMARY'].includes(e.target.tagName), onControl = onButton && e.target.closest?.('#bocce-controls');
// Il GP di Fortezza: frecce, Spazio e Invio finché si tengono giù (su un pulsante Spazio e Invio lo premono).
if (!(onButton && [' ', 'Enter'].includes(e.key)) && mini().key?.(game.closeup, e.key, true)) { e.preventDefault(); return; }
if (onControl) return;
if (!(onButton && [' ', 'Enter'].includes(e.key)) && mini().key?.(game.closeup, e.key, true, e.shiftKey)) { e.preventDefault(); return; }
if (onControl && [' ', 'Enter'].includes(e.key)) return;
const c = game.closeup, m = mini();
if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
e.preventDefault();
@@ -868,7 +888,7 @@ window.addEventListener('keydown', e => {
// Alle bocce e al biliardo, lasciando spazio o Invio parte il tiro.
window.addEventListener('keyup', e => {
// Il GP di Fortezza tiene conto di ogni tasto per conto suo: lasciarne uno non toglie il gas del dito o degli altri.
if (miniState() && mini().key) { mini().key(game.closeup, e.key, false); return; }
if (miniState() && mini().key?.(game.closeup, e.key, false)) return;
if (running && [' ', 'Enter'].includes(e.key)) game?.closeupRelease();
});
@@ -985,10 +1005,12 @@ function updateUi() {
setValue($('bocce-power'), Math.round(c.power * 100));
setValue($('bocce-power-value'), `${Math.round(c.power * 100)}%`);
for (const id of ['bocce-power', 'bocce-left', 'bocce-right']) setProp($(id), 'disabled', !(mg.canAdjust?.(c) ?? mg.canThrow(c)) || (c.holding && !mg.toggle) || !!game.speech);
setProp($('bocce-throw'), 'disabled', !mg.canThrow(c) || (c.holding && !mg.toggle) || !!game.speech);
setProp($('bocce-throw'), 'disabled', !(mg.canPress?.(c) ?? mg.canThrow(c)) || (c.holding && !mg.toggle) || !!game.speech);
// Il GP di Fortezza: niente forza, e i due pulsanti di mira diventano lo sterzo (si tengono premuti).
// Nel GP di Fortezza il cursore della forza diventa la sensibilità dello sterzo col dito (ricordata).
const powerLabel = $('bocce-power').closest('label');
// Ai rinquarti la forza è sempre piena: il cursore non serve.
setProp(powerLabel, 'hidden', def.type === 'rinquarto');
const powerName = def.type === 'gara' ? 'Sensibilità ' : 'Forza ';
if (powerLabel.firstChild.nodeValue !== powerName) powerLabel.firstChild.nodeValue = powerName;
setAttr($('bocce-power'), 'aria-label', def.type === 'gara' ? 'Sensibilità dello sterzo col dito' : 'Forza del lancio');
+12 -7
View File
@@ -227,10 +227,11 @@ export const story = {
type: 'rinquarto',
picture: 'assets/closeups/biliardo-tavolo.png',
names: { player: 'Andrea', cpu: 'Bertovo' },
win: [{ say: 'Questo rinquarto era bono!', who: 'bertovo' }], // [DA ANDREA]
lose: [{ say: 'Le sponde ci sono per qualcosa!', who: 'bertovo' }], // [DA ANDREA]
quit: [{ say: 'Questo me lo tengo per la prossima.' }], // [DA ANDREA]
draw: [{ say: 'Si riprova?', who: 'bertovo' }], // [DA ANDREA]
// Andrea contro Bertovo, sulle stesse posizioni; nell'allenamento il risultato è sempre «pari». [DA ANDREA: le battute]
win: [{ say: 'M\'hai battuto ai rinquarti. Però un lo dire a nessuno.', who: 'bertovo', pose: 'shrug' }, { set: 'rinquarti_vinti' }],
lose: [{ say: 'Le sponde ci sono per qualcosa! Basta chiederglielo per bene.', who: 'bertovo', pose: 'laugh' }],
quit: [{ say: 'Questo me lo tengo per la prossima.' }],
draw: [{ say: 'Visto? Geometrie celestiali. Si riprova quando vuoi.', who: 'bertovo', pose: 'explain' }],
},
fessura: {
type: 'torch',
@@ -3229,9 +3230,13 @@ export const story = {
{ say: 'Geometria. La biglia va dove le dici, basta chiederglielo per bene.', who: 'bertovo', pose: 'chalk' },
{ say: 'E con un po\' di gesso.', who: 'bertovo', pose: 'laugh' },
] },
{ text: 'Dai, fammi vedere un rinquarto.', next: 'sfida', then: [
{ say: 'Te lo faccio vedere? No: lo tiri te.', who: 'bertovo', pose: 'talk' },
{ say: 'Le biglie le metto io, nascoste per bene. Oh tirami questo rinquarto!?', who: 'bertovo', pose: 'explain' },
// L'allenamento: lui tira per primo e fa vedere, poi lo rifai te, senza punti.
{ text: 'Dai, fammi vedere un rinquarto.', next: 'end', then: [
{ say: 'Guarda bene: prima lo tiro io, poi lo rifai te. Tre posizioni, una sponda.', who: 'bertovo', pose: 'chalk' },
{ closeup: 'rinquarto', level: 'allenamento' },
] },
{ text: 'Si fa una sfida a rinquarti?', next: 'sfida', then: [
{ say: 'Le biglie le metto io, nascoste per bene. Tiri te, poi tiro io. Oh tirami questo rinquarto!?', who: 'bertovo', pose: 'explain' },
] },
{ text: 'Ci si vede, Bertovo.', next: 'end', then: [{ say: 'Occhio alle sponde, fuori.', who: 'bertovo', pose: 'shrug' }] },
],