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:
@@ -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
@@ -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
@@ -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:
|
||||
|
||||
@@ -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
@@ -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)}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user