fertig-classic-games/src/games/backgammon/BackgammonCheckers.js

232 lines
8.7 KiB
JavaScript

// BackgammonCheckers.js — the 30 checkers as persistent sprites with stable ids.
//
// Every checker is a shadow Image + a face Image (never a Container, so depth
// works). `sync(state)` assigns ids to locations so nothing that stays put
// moves: a location that shrinks releases its TOP checkers, a location that
// grows takes freed ones. A single move therefore always relocates exactly the
// checker the scene animated (the top of the source stack), and an undo just
// slides the changed checkers back.
//
// Locations: 'p<idx>' (a point), 'bar', 'off'.
import { CR } from './BackgammonLayout.js';
import { clack, slam } from './BackgammonSound.js';
const lerp = (a, b, t) => a + (b - a) * t;
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
export const locKey = (where) => (where === 'bar' ? 'bar' : where === 'off' ? 'off' : `p${where}`);
export class CheckerSet {
constructor(scene, layout, depth) {
this.scene = scene;
this.L = layout;
this.depth = depth;
this.items = []; // id → item
this.lists = { white: new Map(), black: new Map() }; // key → [ids bottom→top]
}
build() {
const s = this.scene;
for (let id = 0; id < 30; id++) {
const color = id < 15 ? 'white' : 'black';
const shadow = s.add.image(0, 0, 'bg-chk-shadow').setDepth(this.depth - 0.5).setAlpha(0.7);
const img = s.add.image(0, 0, `bg-chk-${color}`).setDepth(this.depth);
this.items.push({ id, color, img, shadow, x: 0, y: 0, h: 0, edge: false, key: null, slot: 0, tier: 0, busy: false });
}
return this;
}
// ── placement maths ─────────────────────────────────────────────────────────
countsOf(state, color) {
const m = new Map();
for (let idx = 0; idx < 24; idx++) {
const pt = state.points[idx];
if (pt.color === color && pt.count) m.set(`p${idx}`, pt.count);
}
if (state.bar[color]) m.set('bar', state.bar[color]);
if (state.borneOff[color]) m.set('off', state.borneOff[color]);
return m;
}
slotFor(color, key, s, count) {
if (key === 'bar') return { ...this.L.barPos(color, s, count), edge: false };
if (key === 'off') return { ...this.L.offPos(color, s), tier: s, edge: true };
const p = this.L.slotPos(Number(key.slice(1)), s);
return { ...p, edge: false };
}
depthFor(it) {
if (it.edge) return this.depth + 0.2 + it.slot * 0.001;
return this.depth + it.tier * 0.1 + it.slot * 0.001 + (it.key === 'bar' ? 0.05 : 0);
}
// Re-assign ids to match `state`. Returns [{ it, to }] for checkers whose
// target changed.
assign(state) {
const changes = [];
for (const color of ['white', 'black']) {
const lists = this.lists[color];
const counts = this.countsOf(state, color);
const freed = [];
const ids = this.items.filter((it) => it.color === color).map((it) => it.id);
if (!this.assigned) {
// first time: hand out in order
let k = 0;
lists.clear();
for (const [key, n] of counts) lists.set(key, ids.slice(k, (k += n)));
} else {
for (const [key, list] of lists) {
const want = counts.get(key) ?? 0;
while (list.length > want) freed.push(list.pop());
if (!list.length) lists.delete(key);
}
for (const [key, n] of counts) {
const list = lists.get(key) ?? [];
while (list.length < n && freed.length) list.push(freed.shift());
lists.set(key, list);
}
}
for (const [key, list] of lists) {
list.forEach((id, s) => {
const it = this.items[id];
const to = this.slotFor(color, key, s, list.length);
if (it.key !== key || it.slot !== s || Math.abs(it.x - to.x) > 0.5 || Math.abs(it.y - to.y) > 0.5 || it.edge !== to.edge) {
changes.push({ it, to, key, s });
}
});
}
}
this.assigned = true;
return changes;
}
// Snap or slide every checker to its place for `state`.
sync(state, { dur = 0 } = {}) {
const changes = this.assign(state);
const jobs = [];
for (const { it, to, key, s } of changes) {
it.key = key; it.slot = s; it.tier = to.tier ?? 0;
if (dur <= 0 || it.busy) { this.place(it, to.x, to.y, 0, to.edge); continue; }
jobs.push(this.slide(it, to, dur));
}
return Promise.all(jobs);
}
place(it, x, y, h = 0, edge = it.edge) {
it.x = x; it.y = y; it.h = h;
if (edge !== it.edge) {
it.edge = edge;
it.img.setTexture(edge ? `bg-edge-${it.color}` : `bg-chk-${it.color}`);
}
const lift = h / 60;
it.img.setPosition(x, y - h * 0.55);
it.img.setScale(1 + lift * 0.12);
it.shadow.setPosition(x + 4 + h * 0.18, y + 6 + h * 0.3);
it.shadow.setScale(1 + lift * 0.25);
it.shadow.setAlpha(edge ? 0 : Math.max(0.2, 0.7 - lift * 0.25));
if (!it.flying) {
const d = this.depthFor(it);
it.img.setDepth(d); it.shadow.setDepth(d - 0.05);
}
}
slide(it, to, dur) {
const from = { x: it.x, y: it.y };
const p = { t: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const k = easeInOut(p.t);
this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), Math.sin(Math.PI * p.t) * 10, p.t > 0.5 ? to.edge : it.edge);
},
onComplete: () => { this.place(it, to.x, to.y, 0, to.edge); res(); },
});
});
}
// ── queries ─────────────────────────────────────────────────────────────────
topOf(color, where) {
const list = this.lists[color].get(locKey(where));
return list?.length ? this.items[list[list.length - 1]] : null;
}
itemsAt(color, where) {
return (this.lists[color].get(locKey(where)) ?? []).map((id) => this.items[id]);
}
// Where the next checker of `color` lands on `where` once state is `after`.
landingFor(after, color, where) {
const key = locKey(where);
const counts = this.countsOf(after, color);
const n = counts.get(key) ?? 1;
return this.slotFor(color, key, n - 1, n);
}
// ── animated moves ──────────────────────────────────────────────────────────
// Arc one checker from where it is to `to` ({x, y, edge}); hops with a little
// lift, lands with a squash and a clack. opts.spin for hits.
fly(it, to, { dur = 420, height = 70, spin = 0, sound = true, stack = 0, slamIt = false } = {}) {
const from = { x: it.x, y: it.y };
it.flying = true; it.busy = true;
it.img.setDepth(this.depth + 30); it.shadow.setDepth(this.depth + 29.5);
const p = { t: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const k = easeInOut(p.t);
this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), Math.sin(Math.PI * p.t) * height, p.t > 0.6 ? to.edge : it.edge);
if (spin) it.img.setRotation(spin * p.t * Math.PI * 2);
},
onComplete: () => {
it.img.setRotation(0);
this.place(it, to.x, to.y, 0, to.edge);
if (sound) (slamIt ? slam : clack)(this.scene, { stack });
// squash on landing
const sq = { k: 0 };
this.scene.tweens.add({
targets: sq, k: 1, duration: 120, ease: 'Linear',
onUpdate: () => { const v = Math.sin(Math.PI * sq.k) * 0.08; it.img.setScale(1 + v, 1 - v); },
onComplete: () => {
it.img.setScale(1);
it.flying = false; it.busy = false;
const d = this.depthFor(it);
it.img.setDepth(d); it.shadow.setDepth(d - 0.05);
res();
},
});
},
});
});
}
// Lift / drop the top checker of a selected point.
setLifted(it, on) {
if (!it || it.edge) return;
if (on) {
it.lifted = true;
it.flying = true;
it.img.setDepth(this.depth + 28); it.shadow.setDepth(this.depth + 27.5);
this.place(it, it.x, it.y, 16);
} else if (it.lifted) {
it.lifted = false;
it.flying = false;
this.place(it, it.x, it.y, 0);
}
}
// Drag: follow the pointer.
dragTo(it, x, y) {
it.flying = true;
it.img.setDepth(this.depth + 30); it.shadow.setDepth(this.depth + 29.5);
it.img.setPosition(x, y - 10);
it.img.setScale(1.12);
it.shadow.setPosition(x + 14, y + 16).setScale(1.25).setAlpha(0.35);
}
allItems() { return this.items; }
}
export { CR };