Game updates
This commit is contained in:
parent
371724dc84
commit
47885bab01
|
|
@ -15,6 +15,18 @@ export async function requestAILetter({ fragment, skill }) {
|
|||
}
|
||||
}
|
||||
|
||||
// Example safe words the loser could have headed toward from `prefix`.
|
||||
// Resolves to a string[] (empty when no safe move existed).
|
||||
export async function requestSuggestions(prefix, max = 3) {
|
||||
try {
|
||||
const res = await api.post('/words/ghost/suggest', { prefix, max });
|
||||
return res.words ?? [];
|
||||
} catch (err) {
|
||||
console.error('[ghost] suggest request failed:', err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Grade a fragment a player just formed: { isWord, isPrefix }.
|
||||
export async function judgeFragment(fragment) {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { playSound, SFX } from '../../ui/Sounds.js';
|
|||
import {
|
||||
GHOST_LETTERS, createInitialState, appendLetter, concedeRound, other,
|
||||
} from './GhostLogic.js';
|
||||
import { requestAILetter, judgeFragment, nextThinkDelay } from './GhostAI.js';
|
||||
import { requestAILetter, judgeFragment, requestSuggestions, nextThinkDelay } from './GhostAI.js';
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
const TILE_W = 84;
|
||||
|
|
@ -326,9 +326,15 @@ export default class GhostGame extends Phaser.Scene {
|
|||
const matchOver = this.playerGhost >= TARGET || this.aiGhost >= TARGET;
|
||||
if (matchOver) this.recordResult(this.aiGhost >= TARGET ? 'win' : 'loss');
|
||||
|
||||
this.time.delayedCall(800, () => {
|
||||
if (matchOver) this.showVictoryScreen(this.aiGhost >= TARGET);
|
||||
else this.showRoundResult(loser, reason);
|
||||
// The prefix the loser faced before their losing letter (the AI didn't append
|
||||
// one when stumped, so the whole fragment is what it faced).
|
||||
const faced = reason === 'stumped' ? this.gs.fragment : this.gs.fragment.slice(0, -1);
|
||||
|
||||
this.time.delayedCall(800, async () => {
|
||||
if (matchOver) return this.showVictoryScreen(this.aiGhost >= TARGET);
|
||||
const words = await requestSuggestions(faced);
|
||||
if (!this.scene.isActive()) return;
|
||||
this.showRoundResult(loser, reason, words);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -336,7 +342,7 @@ export default class GhostGame extends Phaser.Scene {
|
|||
return GHOST_LETTERS.map((l, i) => (i < count ? l : '·')).join(' ');
|
||||
}
|
||||
|
||||
showRoundResult(loser, reason) {
|
||||
showRoundResult(loser, reason, words = []) {
|
||||
const cx = GAME_WIDTH / 2;
|
||||
const cy = GAME_HEIGHT / 2;
|
||||
const oppName = this.opponent?.name ?? 'CPU';
|
||||
|
|
@ -359,24 +365,33 @@ export default class GhostGame extends Phaser.Scene {
|
|||
const earnLine = `${loserName} ${verb} a “${earnedLetter}”`;
|
||||
const seriesLine = `You ${this.ghostStr(this.playerGhost)} ${oppName} ${this.ghostStr(this.aiGhost)}`;
|
||||
|
||||
const panel = this.add.rectangle(cx, cy, 720, 240, 0x0a0e14, 0.94)
|
||||
const hasSafe = words.length > 0;
|
||||
const suggestLine = hasSafe
|
||||
? `Safe play would lead to: ${words.join(' · ')}`
|
||||
: 'No safe move was possible';
|
||||
|
||||
const panel = this.add.rectangle(cx, cy, 780, 300, 0x0a0e14, 0.94)
|
||||
.setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.ui + 10);
|
||||
const t1 = this.add.text(cx, cy - 70, headline, {
|
||||
const t1 = this.add.text(cx, cy - 100, headline, {
|
||||
fontFamily: 'Righteous', fontSize: '36px',
|
||||
color: loser === 'player' ? COLORS.dangerHex : '#6aff88',
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui + 11);
|
||||
const t2 = this.add.text(cx, cy - 18, detail, {
|
||||
const t2 = this.add.text(cx, cy - 54, detail, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.accentHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui + 11);
|
||||
const t3 = this.add.text(cx, cy + 22, earnLine, {
|
||||
const t3 = this.add.text(cx, cy - 12, earnLine, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui + 11);
|
||||
const t4 = this.add.text(cx, cy + 64, seriesLine, {
|
||||
const t4 = this.add.text(cx, cy + 32, suggestLine, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '19px',
|
||||
color: hasSafe ? '#6aff88' : COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui + 11);
|
||||
const t5 = this.add.text(cx, cy + 80, seriesLine, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui + 11);
|
||||
|
||||
this.time.delayedCall(2600, () => {
|
||||
[panel, t1, t2, t3, t4].forEach(o => o.destroy());
|
||||
this.time.delayedCall(3000, () => {
|
||||
[panel, t1, t2, t3, t4, t5].forEach(o => o.destroy());
|
||||
this.startNextRound();
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
// Word Ladder AI — a thin client wrapper. The intelligence (graph BFS + skill
|
||||
// model) lives server-side in wordLadderEngine.js, like Scrabble/Ghost; this
|
||||
// just advances the AI's own ladder one rung per request and tracks its path.
|
||||
|
||||
import { api } from '../../services/api.js';
|
||||
|
||||
export function createAIState({ start, target, skill }) {
|
||||
const S = String(start).toUpperCase();
|
||||
return {
|
||||
current: S,
|
||||
target: String(target).toUpperCase(),
|
||||
skill: skill ?? 3,
|
||||
path: [S],
|
||||
done: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Ask the server for the AI's next rung. Updates aiState and returns
|
||||
// { word, delayMs, done } — delayMs is the suggested pause before the next move.
|
||||
export async function requestNextMove(aiState) {
|
||||
let res;
|
||||
try {
|
||||
res = await api.post('/words/wordladder/ai-move', {
|
||||
current: aiState.current,
|
||||
target: aiState.target,
|
||||
skill: aiState.skill,
|
||||
});
|
||||
} catch {
|
||||
return { word: aiState.current, delayMs: 2000, done: aiState.done };
|
||||
}
|
||||
|
||||
const word = String(res.word ?? aiState.current).toUpperCase();
|
||||
if (word !== aiState.current) {
|
||||
aiState.current = word;
|
||||
aiState.path.push(word);
|
||||
}
|
||||
aiState.done = !!res.done || word === aiState.target;
|
||||
return { word, delayMs: res.delayMs ?? 2000, done: aiState.done };
|
||||
}
|
||||
|
|
@ -0,0 +1,600 @@
|
|||
import * as Phaser from 'phaser';
|
||||
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
|
||||
import { api } from '../../services/api.js';
|
||||
import { auth } from '../../services/auth.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { MusicPlayer } from '../../ui/MusicPlayer.js';
|
||||
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
|
||||
import { playSound, SFX } from '../../ui/Sounds.js';
|
||||
import {
|
||||
createInitialState, lastRung, tryAddRung, undoRung, isSolved, stepsTaken, changedIndex,
|
||||
} from './WordLadderLogic.js';
|
||||
import { createAIState, requestNextMove } from './WordLadderAI.js';
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
const TILE = 58;
|
||||
const TGAP = 8;
|
||||
const N_ROWS = 7; // visible working-board rows (sliding window)
|
||||
const ROW_PITCH = TILE + 8; // 66
|
||||
|
||||
const ROW0_Y = 140; // first working-board row center (board sits at top)
|
||||
const GOAL_ROW_Y = 644; // goal row sits BELOW the working board
|
||||
|
||||
const KEY_W = 50, KEY_H = 56, KEY_WW = 78, KEY_G = 7;
|
||||
const KBD_TOP = 724;
|
||||
|
||||
const PLR_CX = 560, AI_CX = 1360, SOLO_CX = GAME_WIDTH / 2;
|
||||
|
||||
const DEPTH = { bg: 0, board: 1, tile: 2, ui: 10, overlay: 40 };
|
||||
|
||||
const C = {
|
||||
empty: 0x121213,
|
||||
border: 0x565758,
|
||||
active: 0x818384,
|
||||
filled: 0x1a1a1b,
|
||||
start: 0x2a3550,
|
||||
target: 0x538d4e,
|
||||
key: 0x818384,
|
||||
};
|
||||
|
||||
const KEYBOARD_ROWS = [
|
||||
['Q','W','E','R','T','Y','U','I','O','P'],
|
||||
['A','S','D','F','G','H','J','K','L'],
|
||||
['ENTER','Z','X','C','V','B','N','M','⌫'],
|
||||
];
|
||||
|
||||
export default class WordLadderGame extends Phaser.Scene {
|
||||
constructor() { super('WordLadderGame'); }
|
||||
|
||||
init(data) {
|
||||
this._initData = { ...data };
|
||||
this.gameDef = data.game;
|
||||
this.opponent = data.opponents?.[0] ?? null;
|
||||
this.versus = !!this.opponent;
|
||||
this.skill = this.opponent?.skill ?? 3;
|
||||
this.length = data.wordLength ?? 4;
|
||||
this.skipIntro = data.skipIntro ?? false;
|
||||
|
||||
this.gs = null;
|
||||
this.aiState = null;
|
||||
this.validSet = null;
|
||||
this.currentInput = '';
|
||||
this.activeRow = 1;
|
||||
this.animating = false;
|
||||
this.playerDone = false;
|
||||
this.aiDone = false;
|
||||
this.gameEnded = false;
|
||||
this.hintsUsed = 0;
|
||||
this.aiTimer = null;
|
||||
this.aiNextDelay = 1500;
|
||||
this.opponentPortrait = null;
|
||||
}
|
||||
|
||||
async create() {
|
||||
const music = this.cache.json.get('music');
|
||||
if (music?.tracks) new MusicPlayer(this, music.tracks);
|
||||
this.buildParticleTexture();
|
||||
|
||||
let player, opponent, validWords;
|
||||
try {
|
||||
const res = await api.get(`/words/wordladder/start?length=${this.length}&versus=${this.versus}`);
|
||||
player = res.player;
|
||||
opponent = res.opponent;
|
||||
validWords = res.validWords;
|
||||
} catch (err) {
|
||||
console.error('[wordladder] failed to fetch puzzle:', err);
|
||||
player = { start: 'COLD', target: 'WARM', par: 4 };
|
||||
validWords = ['COLD', 'CORD', 'CARD', 'WARD', 'WARM'];
|
||||
}
|
||||
|
||||
this.validSet = new Set((validWords ?? []).map(w => w.toUpperCase()));
|
||||
this.gs = createInitialState({ ...player, length: this.length });
|
||||
if (this.versus && opponent) {
|
||||
this.aiState = createAIState({ start: opponent.start, target: opponent.target, skill: this.skill });
|
||||
}
|
||||
|
||||
this.playerCX = this.versus ? PLR_CX : SOLO_CX;
|
||||
|
||||
this.buildBackground();
|
||||
this.buildPortraits();
|
||||
this.buildBoards();
|
||||
this.buildKeyboard();
|
||||
this.buildStatusText();
|
||||
this.buildControls();
|
||||
this.setupInput();
|
||||
|
||||
this.renderPlayerBoard();
|
||||
if (this.aiState) {
|
||||
this.renderAIBoard();
|
||||
this.scheduleAIMove();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────
|
||||
|
||||
buildParticleTexture() {
|
||||
if (this.textures.exists('ladderParticle')) return;
|
||||
const g = this.make.graphics({ add: false });
|
||||
g.fillStyle(0xffffff, 1);
|
||||
g.fillCircle(5, 5, 5);
|
||||
g.generateTexture('ladderParticle', 10, 10);
|
||||
g.destroy();
|
||||
}
|
||||
|
||||
buildBackground() {
|
||||
const cx = GAME_WIDTH / 2;
|
||||
this.add.rectangle(cx, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg);
|
||||
|
||||
this.add.text(cx, 40, 'WORD LADDER', {
|
||||
fontFamily: 'Righteous', fontSize: '46px', color: COLORS.textHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
|
||||
const labelStyle = { fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex };
|
||||
this.add.text(this.playerCX, 90, 'YOU', labelStyle).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
|
||||
if (this.versus) {
|
||||
const g = this.add.graphics().setDepth(DEPTH.bg);
|
||||
g.lineStyle(1, 0x2a2a2c, 1);
|
||||
g.lineBetween(cx, 30, cx, 690);
|
||||
|
||||
this.add.text(AI_CX, 90, this.opponent?.name?.toUpperCase() ?? 'CPU', labelStyle)
|
||||
.setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
|
||||
this.add.text(cx, 400, 'VS', {
|
||||
fontFamily: 'Righteous', fontSize: '34px', color: COLORS.accentHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
}
|
||||
}
|
||||
|
||||
buildPortraits() {
|
||||
const r = 58;
|
||||
const py = 250;
|
||||
const ppx = 96;
|
||||
createPlayerPortrait(this, ppx, py, r, DEPTH.ui, 'WordLadderGame');
|
||||
this.add.text(ppx, py + r + 10, auth.user?.username ?? 'You', {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex,
|
||||
}).setOrigin(0.5, 0).setDepth(DEPTH.ui);
|
||||
|
||||
if (this.versus) {
|
||||
const opx = GAME_WIDTH - 96;
|
||||
this.opponentPortrait = createOpponentPortrait(this, this.opponent, opx, py, r, DEPTH.ui, { playIntro: !this.skipIntro });
|
||||
this.add.text(opx, py + r + 10, this.opponent?.name ?? 'CPU', {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex,
|
||||
}).setOrigin(0.5, 0).setDepth(DEPTH.ui);
|
||||
}
|
||||
}
|
||||
|
||||
buildBoards() {
|
||||
this.playerGoalTiles = this.createGoalRow(this.playerCX, this.gs.target);
|
||||
this.playerTiles = this.createWorkingGrid(this.playerCX);
|
||||
if (this.aiState) {
|
||||
this.aiGoalTiles = this.createGoalRow(AI_CX, this.aiState.target);
|
||||
this.aiTiles = this.createWorkingGrid(AI_CX);
|
||||
}
|
||||
}
|
||||
|
||||
boardLeft(centerX) {
|
||||
const boardW = this.length * TILE + (this.length - 1) * TGAP;
|
||||
return centerX - boardW / 2;
|
||||
}
|
||||
|
||||
tileX(centerX, col) {
|
||||
return this.boardLeft(centerX) + col * (TILE + TGAP) + TILE / 2;
|
||||
}
|
||||
|
||||
createGoalRow(centerX, target) {
|
||||
this.add.text(centerX, GOAL_ROW_Y - TILE / 2 - 18, 'GOAL', {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
|
||||
const tiles = [];
|
||||
for (let c = 0; c < this.length; c++) {
|
||||
const x = this.tileX(centerX, c);
|
||||
const container = this.add.container(x, GOAL_ROW_Y).setDepth(DEPTH.tile);
|
||||
const bg = this.add.rectangle(0, 0, TILE, TILE, C.filled).setStrokeStyle(2, C.target);
|
||||
const label = this.add.text(0, 0, target[c] ?? '', {
|
||||
fontFamily: 'Righteous', fontSize: '30px', color: '#6aff88', fontStyle: 'bold',
|
||||
}).setOrigin(0.5);
|
||||
container.add([bg, label]);
|
||||
tiles.push({ container, bg, label });
|
||||
}
|
||||
return tiles;
|
||||
}
|
||||
|
||||
createWorkingGrid(centerX) {
|
||||
const grid = [];
|
||||
for (let r = 0; r < N_ROWS; r++) {
|
||||
const row = [];
|
||||
const y = ROW0_Y + r * ROW_PITCH;
|
||||
for (let c = 0; c < this.length; c++) {
|
||||
const x = this.tileX(centerX, c);
|
||||
const container = this.add.container(x, y).setDepth(DEPTH.tile);
|
||||
const bg = this.add.rectangle(0, 0, TILE, TILE, C.empty).setStrokeStyle(2, C.border);
|
||||
const label = this.add.text(0, 0, '', {
|
||||
fontFamily: 'Righteous', fontSize: '30px', color: '#ffffff', fontStyle: 'bold',
|
||||
}).setOrigin(0.5);
|
||||
container.add([bg, label]);
|
||||
row.push({ container, bg, label });
|
||||
}
|
||||
grid.push(row);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
buildKeyboard() {
|
||||
this.keyObjs = {};
|
||||
const cx = this.playerCX;
|
||||
KEYBOARD_ROWS.forEach((keys, rowIdx) => {
|
||||
const isWide = (k) => k === 'ENTER' || k === '⌫';
|
||||
const rowW = keys.reduce((s, k) => s + (isWide(k) ? KEY_WW : KEY_W) + KEY_G, -KEY_G);
|
||||
let x = cx - rowW / 2;
|
||||
keys.forEach(key => {
|
||||
const kw = isWide(key) ? KEY_WW : KEY_W;
|
||||
const kcx = x + kw / 2;
|
||||
const kcy = KBD_TOP + rowIdx * (KEY_H + KEY_G) + KEY_H / 2;
|
||||
x += kw + KEY_G;
|
||||
|
||||
const container = this.add.container(kcx, kcy).setDepth(DEPTH.ui);
|
||||
const bg = this.add.rectangle(0, 0, kw, KEY_H, C.key).setStrokeStyle(0);
|
||||
bg.setInteractive({ cursor: 'pointer', useHandCursor: true });
|
||||
const lbl = this.add.text(0, 0, key, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: key.length > 1 ? '15px' : '21px',
|
||||
color: '#ffffff', fontStyle: 'bold',
|
||||
}).setOrigin(0.5);
|
||||
container.add([bg, lbl]);
|
||||
this.keyObjs[key] = { container, bg, lbl };
|
||||
|
||||
bg.on('pointerdown', () => {
|
||||
if (key === 'ENTER') this.submitWord();
|
||||
else if (key === '⌫') this.removeLetter();
|
||||
else this.addLetter(key);
|
||||
});
|
||||
bg.on('pointerover', () => bg.setFillStyle(0x9a9b9c));
|
||||
bg.on('pointerout', () => bg.setFillStyle(C.key));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
buildStatusText() {
|
||||
this.statusText = this.add.text(this.playerCX, KBD_TOP - 26, '', {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.dangerHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
|
||||
if (this.versus) {
|
||||
this.aiThinkText = this.add.text(AI_CX, KBD_TOP - 26, '', {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.accentHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
}
|
||||
|
||||
const parLine = this.gs.par ? `Par: ${this.gs.par} steps` : '';
|
||||
this.parText = this.add.text(this.playerCX, GAME_HEIGHT - 30, parLine, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.ui);
|
||||
}
|
||||
|
||||
buildControls() {
|
||||
const y = 940;
|
||||
this.undoBtn = new Button(this, this.playerCX - 130, y, 'Undo', () => this.undo(), {
|
||||
variant: 'ghost', width: 150, height: 48, fontSize: 20,
|
||||
}).setDepth(DEPTH.ui);
|
||||
|
||||
this.hintBtn = new Button(this, this.playerCX + 130, y, 'Hint', () => this.hint(), {
|
||||
variant: 'ghost', width: 150, height: 48, fontSize: 20,
|
||||
}).setDepth(DEPTH.ui);
|
||||
|
||||
new Button(this, GAME_WIDTH - 100, GAME_HEIGHT - 44, 'Leave', () => this.scene.start('GameMenu'), {
|
||||
variant: 'ghost', width: 160, height: 44, fontSize: 20,
|
||||
}).setDepth(DEPTH.ui);
|
||||
}
|
||||
|
||||
// ── Rendering ──────────────────────────────────────────────────────────────
|
||||
|
||||
renderPlayerBoard() {
|
||||
const showActive = !this.gameEnded && this.gs.status === 'playing';
|
||||
this.activeRow = this.renderWorkingBoard(this.playerTiles, this.gs.rungs, {
|
||||
showActive,
|
||||
target: this.gs.target,
|
||||
});
|
||||
if (showActive) this.updateActiveRow();
|
||||
}
|
||||
|
||||
renderAIBoard() {
|
||||
this.renderWorkingBoard(this.aiTiles, this.aiState.path, {
|
||||
showActive: false,
|
||||
target: this.aiState.target,
|
||||
});
|
||||
}
|
||||
|
||||
// Paints a sliding window of `rungs` (plus an active input row when showActive).
|
||||
// Returns the screen-row index of the active row (or -1).
|
||||
renderWorkingBoard(tiles, rungs, { showActive, target }) {
|
||||
const used = rungs.length + (showActive ? 1 : 0);
|
||||
const windowStart = Math.max(0, used - N_ROWS);
|
||||
let activeScreenRow = -1;
|
||||
|
||||
for (let r = 0; r < N_ROWS; r++) {
|
||||
const gi = windowStart + r;
|
||||
const rowTiles = tiles[r];
|
||||
if (gi < rungs.length) {
|
||||
const prev = gi > 0 ? rungs[gi - 1] : null;
|
||||
this.paintRung(rowTiles, rungs[gi], {
|
||||
isStart: gi === 0,
|
||||
isTarget: rungs[gi] === target,
|
||||
changed: changedIndex(prev, rungs[gi]),
|
||||
});
|
||||
} else if (showActive && gi === rungs.length) {
|
||||
activeScreenRow = r;
|
||||
this.paintActive(rowTiles, '');
|
||||
} else {
|
||||
this.paintEmpty(rowTiles);
|
||||
}
|
||||
}
|
||||
return activeScreenRow;
|
||||
}
|
||||
|
||||
paintRung(rowTiles, word, { isStart, isTarget, changed }) {
|
||||
const fill = isTarget ? C.target : isStart ? C.start : C.filled;
|
||||
rowTiles.forEach((tile, i) => {
|
||||
tile.label.setText(word[i] ?? '');
|
||||
tile.label.setColor(i === changed ? COLORS.goldHex : '#ffffff');
|
||||
tile.bg.setFillStyle(fill);
|
||||
tile.bg.setStrokeStyle(2, isStart ? COLORS.accent : isTarget ? C.target : C.border);
|
||||
tile.container.setScale(1);
|
||||
});
|
||||
}
|
||||
|
||||
paintActive(rowTiles, input) {
|
||||
rowTiles.forEach((tile, i) => {
|
||||
const ch = input[i] ?? '';
|
||||
tile.label.setText(ch);
|
||||
tile.label.setColor('#ffffff');
|
||||
tile.bg.setFillStyle(ch ? C.filled : C.empty);
|
||||
tile.bg.setStrokeStyle(2, ch ? C.active : C.border);
|
||||
tile.container.setScale(1);
|
||||
});
|
||||
}
|
||||
|
||||
paintEmpty(rowTiles) {
|
||||
rowTiles.forEach((tile) => {
|
||||
tile.label.setText('');
|
||||
tile.bg.setFillStyle(C.empty);
|
||||
tile.bg.setStrokeStyle(2, 0x2a2a2c);
|
||||
tile.container.setScale(1);
|
||||
});
|
||||
}
|
||||
|
||||
updateActiveRow() {
|
||||
if (this.activeRow < 0) return;
|
||||
this.paintActive(this.playerTiles[this.activeRow], this.currentInput);
|
||||
}
|
||||
|
||||
// ── Input ──────────────────────────────────────────────────────────────────
|
||||
|
||||
setupInput() {
|
||||
this.input.keyboard.on('keydown', (evt) => {
|
||||
if (this.animating || this.playerDone || this.gameEnded) return;
|
||||
if (/^[a-zA-Z]$/.test(evt.key)) this.addLetter(evt.key.toUpperCase());
|
||||
else if (evt.key === 'Backspace') this.removeLetter();
|
||||
else if (evt.key === 'Enter') this.submitWord();
|
||||
});
|
||||
}
|
||||
|
||||
addLetter(l) {
|
||||
if (this.animating || this.playerDone || this.gameEnded) return;
|
||||
if (this.currentInput.length >= this.length) return;
|
||||
this.currentInput += l;
|
||||
this.updateActiveRow();
|
||||
const tile = this.playerTiles[this.activeRow]?.[this.currentInput.length - 1];
|
||||
if (tile) this.bounceTile(tile);
|
||||
}
|
||||
|
||||
removeLetter() {
|
||||
if (this.currentInput.length === 0 || this.playerDone || this.gameEnded) return;
|
||||
this.currentInput = this.currentInput.slice(0, -1);
|
||||
this.updateActiveRow();
|
||||
}
|
||||
|
||||
submitWord() {
|
||||
if (this.animating || this.playerDone || this.gameEnded) return;
|
||||
|
||||
const result = tryAddRung(this.gs, this.currentInput, this.validSet);
|
||||
if (!result.ok) {
|
||||
this.shakeRow(this.playerTiles[this.activeRow]);
|
||||
this.flashStatus(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
this.gs = result.state;
|
||||
this.currentInput = '';
|
||||
playSound(this, SFX.PENCIL_WRITE);
|
||||
this.renderPlayerBoard();
|
||||
this.popRow(this.committedScreenRow());
|
||||
|
||||
if (isSolved(this.gs)) {
|
||||
this.playerDone = true;
|
||||
this.handleFinish('player');
|
||||
}
|
||||
}
|
||||
|
||||
// Screen row of the most recently committed rung (for the pop animation).
|
||||
committedScreenRow() {
|
||||
const used = this.gs.rungs.length + (this.gs.status === 'playing' && !this.gameEnded ? 1 : 0);
|
||||
const windowStart = Math.max(0, used - N_ROWS);
|
||||
return (this.gs.rungs.length - 1) - windowStart;
|
||||
}
|
||||
|
||||
undo() {
|
||||
if (this.playerDone || this.gameEnded || this.animating) return;
|
||||
if (this.gs.rungs.length <= 1) { this.flashStatus('Nothing to undo'); return; }
|
||||
this.gs = undoRung(this.gs);
|
||||
this.currentInput = '';
|
||||
playSound(this, SFX.PIECE_CLICK);
|
||||
this.renderPlayerBoard();
|
||||
}
|
||||
|
||||
async hint() {
|
||||
if (this.playerDone || this.gameEnded || this.animating) return;
|
||||
if (this.hintsUsed >= 1) { this.flashStatus('No hints left'); return; }
|
||||
this.hintsUsed = 1;
|
||||
this.hintBtn.setEnabled(false).setLabel('Hint used');
|
||||
try {
|
||||
const res = await api.post('/words/wordladder/hint', {
|
||||
current: lastRung(this.gs), target: this.gs.target,
|
||||
});
|
||||
if (res.word) {
|
||||
this.currentInput = String(res.word).toUpperCase().slice(0, this.length);
|
||||
this.updateActiveRow();
|
||||
this.flashStatus('Hint filled — press Enter', COLORS.accentHex);
|
||||
} else {
|
||||
this.flashStatus('No hint available');
|
||||
}
|
||||
} catch {
|
||||
this.flashStatus('Hint unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
flashStatus(msg, color = COLORS.dangerHex) {
|
||||
this.statusText.setColor(color).setText(msg);
|
||||
this.time.delayedCall(1400, () => { if (this.statusText) this.statusText.setText(''); });
|
||||
}
|
||||
|
||||
// ── AI race loop ─────────────────────────────────────────────────────────────
|
||||
|
||||
scheduleAIMove() {
|
||||
if (this.aiDone || this.gameEnded) return;
|
||||
this.aiThinkText?.setText('thinking…');
|
||||
this.aiTimer = this.time.delayedCall(this.aiNextDelay, () => this.doAIMove());
|
||||
}
|
||||
|
||||
async doAIMove() {
|
||||
if (this.aiDone || this.gameEnded) return;
|
||||
this.aiThinkText?.setText('');
|
||||
|
||||
const { delayMs, done } = await requestNextMove(this.aiState);
|
||||
if (this.gameEnded) return;
|
||||
|
||||
this.aiNextDelay = delayMs;
|
||||
this.renderAIBoard();
|
||||
this.popRow(this.aiCommittedScreenRow(), this.aiTiles);
|
||||
playSound(this, SFX.PIECE_CLICK);
|
||||
|
||||
if (done) {
|
||||
this.aiDone = true;
|
||||
this.handleFinish('ai');
|
||||
} else {
|
||||
this.scheduleAIMove();
|
||||
}
|
||||
}
|
||||
|
||||
aiCommittedScreenRow() {
|
||||
const used = this.aiState.path.length;
|
||||
const windowStart = Math.max(0, used - N_ROWS);
|
||||
return (this.aiState.path.length - 1) - windowStart;
|
||||
}
|
||||
|
||||
// ── End of game ──────────────────────────────────────────────────────────────
|
||||
|
||||
handleFinish(winner) {
|
||||
if (this.gameEnded) return;
|
||||
this.gameEnded = true;
|
||||
this.playerDone = true;
|
||||
if (this.aiTimer) { this.aiTimer.remove(); this.aiTimer = null; }
|
||||
this.aiThinkText?.setText('');
|
||||
|
||||
const playerWon = winner === 'player';
|
||||
if (this.versus) this.opponentPortrait?.playEmotion(playerWon ? 'upset' : 'happy');
|
||||
this.recordResult(playerWon ? 'win' : 'loss');
|
||||
|
||||
this.time.delayedCall(600, () => this.showResult(playerWon));
|
||||
}
|
||||
|
||||
showResult(playerWon) {
|
||||
const cx = GAME_WIDTH / 2;
|
||||
const cy = GAME_HEIGHT / 2;
|
||||
|
||||
if (playerWon) {
|
||||
const fw = this.add.particles(cx, cy, 'ladderParticle', {
|
||||
speed: { min: 80, max: 420 }, lifespan: 1300, scale: { start: 1.1, end: 0 },
|
||||
alpha: { start: 1, end: 0 }, quantity: 3, frequency: 40,
|
||||
tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0x88ff44], angle: { min: 0, max: 360 },
|
||||
emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-GAME_WIDTH / 2, -GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT) },
|
||||
}).setDepth(DEPTH.overlay - 1);
|
||||
this.time.delayedCall(2600, () => { fw.stop(); this.time.delayedCall(1300, () => fw.destroy()); });
|
||||
}
|
||||
|
||||
this.add.rectangle(cx, cy, 720, 360, 0x0a0e14, 0.95)
|
||||
.setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.overlay);
|
||||
|
||||
const headline = this.versus
|
||||
? (playerWon ? 'You win the race!' : `${this.opponent?.name ?? 'CPU'} wins!`)
|
||||
: 'Solved!';
|
||||
this.add.text(cx, cy - 110, headline, {
|
||||
fontFamily: 'Righteous', fontSize: '44px',
|
||||
color: playerWon ? '#ffd700' : COLORS.textHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.overlay + 1);
|
||||
|
||||
const ladderLine = this.gs.rungs.join(' → ');
|
||||
this.add.text(cx, cy - 40, ladderLine, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.accentHex,
|
||||
align: 'center', wordWrap: { width: 660 },
|
||||
}).setOrigin(0.5).setDepth(DEPTH.overlay + 1);
|
||||
|
||||
const parStr = this.gs.par ? ` · Par: ${this.gs.par}` : '';
|
||||
this.add.text(cx, cy + 30, `Your steps: ${stepsTaken(this.gs)}${parStr}`, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setDepth(DEPTH.overlay + 1);
|
||||
|
||||
const btnY = cy + 120;
|
||||
new Button(this, cx - 130, btnY, 'Play Again', () => {
|
||||
this.scene.restart({ ...this._initData, skipIntro: true });
|
||||
}, { width: 230, height: 52, fontSize: 22 }).setDepth(DEPTH.overlay + 1);
|
||||
|
||||
new Button(this, cx + 130, btnY, 'Leave', () => this.scene.start('GameMenu'),
|
||||
{ variant: 'ghost', width: 230, height: 52, fontSize: 22 }).setDepth(DEPTH.overlay + 1);
|
||||
}
|
||||
|
||||
// ── Animations ───────────────────────────────────────────────────────────────
|
||||
|
||||
popRow(screenRow, tiles = this.playerTiles) {
|
||||
if (screenRow < 0 || screenRow >= N_ROWS) return;
|
||||
const row = tiles[screenRow];
|
||||
row.forEach((tile, i) => {
|
||||
this.time.delayedCall(i * 40, () => {
|
||||
this.tweens.add({ targets: tile.container, scale: 1.12, duration: 90, yoyo: true, ease: 'Sine.easeOut' });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
bounceTile(tile) {
|
||||
this.tweens.add({ targets: tile.container, scaleY: 1.08, duration: 80, yoyo: true, ease: 'Sine.easeOut' });
|
||||
}
|
||||
|
||||
shakeRow(rowTiles) {
|
||||
if (!rowTiles) return;
|
||||
playSound(this, SFX.PIECE_CLICK);
|
||||
const containers = rowTiles.map(t => t.container);
|
||||
const startXs = containers.map(c => c.x);
|
||||
this.tweens.add({
|
||||
targets: containers,
|
||||
x: (target, _k, _v, index) => startXs[index] + 8,
|
||||
duration: 50, yoyo: true, repeat: 3, ease: 'Sine.easeInOut',
|
||||
onComplete: () => containers.forEach((c, i) => { c.x = startXs[i]; }),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Misc ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
async recordResult(result) {
|
||||
try {
|
||||
const score = result === 'win' ? Math.max(20, 100 - Math.max(0, stepsTaken(this.gs) - (this.gs.par ?? stepsTaken(this.gs))) * 12) : 0;
|
||||
await api.post('/history/single-player', {
|
||||
slug: 'wordladder', score, opponentScores: [0], result,
|
||||
});
|
||||
} catch { /* best effort */ }
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
if (this.aiTimer) { this.aiTimer.remove(); this.aiTimer = null; }
|
||||
this.opponentPortrait?.destroy();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
// Pure Word Ladder logic — no Phaser dependency.
|
||||
//
|
||||
// A ladder transforms START into TARGET by changing exactly one letter per rung,
|
||||
// where every rung is a real word of the same length. State tracks the rungs
|
||||
// played so far (rungs[0] is always the start word).
|
||||
|
||||
export function createInitialState({ start, target, par, length }) {
|
||||
const S = String(start).toUpperCase();
|
||||
return {
|
||||
start: S,
|
||||
target: String(target).toUpperCase(),
|
||||
par: par ?? null,
|
||||
length: length ?? S.length,
|
||||
rungs: [S],
|
||||
status: 'playing', // 'playing' | 'won'
|
||||
};
|
||||
}
|
||||
|
||||
export function lastRung(state) {
|
||||
return state.rungs[state.rungs.length - 1];
|
||||
}
|
||||
|
||||
// True when a and b are the same length and differ in exactly one position.
|
||||
export function isOneLetterDifferent(a, b) {
|
||||
if (a.length !== b.length) return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) diff++;
|
||||
if (diff > 1) return false;
|
||||
}
|
||||
return diff === 1;
|
||||
}
|
||||
|
||||
// Index of the single differing position between two equal-length words, or -1.
|
||||
export function changedIndex(prev, word) {
|
||||
if (!prev || prev.length !== word.length) return -1;
|
||||
for (let i = 0; i < word.length; i++) {
|
||||
if (prev[i] !== word[i]) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Attempt to append `word` as the next rung. Returns { ok, state } on success or
|
||||
// { ok: false, reason } with a short message suitable for display.
|
||||
export function tryAddRung(state, word, validSet) {
|
||||
if (state.status !== 'playing') return { ok: false, reason: 'Round over' };
|
||||
const W = String(word).toUpperCase();
|
||||
|
||||
if (W.length !== state.length) return { ok: false, reason: 'Not enough letters' };
|
||||
if (!isOneLetterDifferent(lastRung(state), W)) return { ok: false, reason: 'Change exactly one letter' };
|
||||
if (!validSet.has(W)) return { ok: false, reason: 'Not in word list' };
|
||||
if (state.rungs.includes(W)) return { ok: false, reason: 'Word already used' };
|
||||
|
||||
const rungs = [...state.rungs, W];
|
||||
const status = W === state.target ? 'won' : 'playing';
|
||||
return { ok: true, state: { ...state, rungs, status } };
|
||||
}
|
||||
|
||||
// Remove the most recent rung (never the start word).
|
||||
export function undoRung(state) {
|
||||
if (state.rungs.length <= 1) return state;
|
||||
return { ...state, rungs: state.rungs.slice(0, -1), status: 'playing' };
|
||||
}
|
||||
|
||||
export function isSolved(state) {
|
||||
return lastRung(state) === state.target;
|
||||
}
|
||||
|
||||
// Steps taken so far (rungs beyond the start word).
|
||||
export function stepsTaken(state) {
|
||||
return state.rungs.length - 1;
|
||||
}
|
||||
|
|
@ -34,6 +34,7 @@ import ChessGame from './games/chess/ChessGame.js';
|
|||
import WordleGame from './games/wordle/WordleGame.js';
|
||||
import ScrabbleGame from './games/scrabble/ScrabbleGame.js';
|
||||
import GhostGame from './games/ghost/GhostGame.js';
|
||||
import WordLadderGame from './games/wordladder/WordLadderGame.js';
|
||||
|
||||
const config = {
|
||||
type: Phaser.AUTO,
|
||||
|
|
@ -81,6 +82,7 @@ const config = {
|
|||
WordleGame,
|
||||
ScrabbleGame,
|
||||
GhostGame,
|
||||
WordLadderGame,
|
||||
],
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -14,10 +14,11 @@ export default class GameRoomScene extends Phaser.Scene {
|
|||
this.cardBack = data.cardBack ?? null;
|
||||
this.tilePlacement = data.tilePlacement ?? 'standard';
|
||||
this.deckMode = data.deckMode ?? 'standard';
|
||||
this.wordLength = data.wordLength ?? 4;
|
||||
}
|
||||
|
||||
create() {
|
||||
const slugDispatch = { backgammon: 'Backgammon', holdem: 'HoldemGame', blackjack: 'BlackjackGame', parchisi: 'ParchisiGame', yatzi: 'YatziGame', skipbo: 'SkipBoGame', phase10: 'Phase10Game', chinesecheckers: 'ChineseCheckersGame', gofish: 'GoFishGame', uno: 'UnoGame', craps: 'CrapsGame', roulette: 'RouletteGame', mexicantrain: 'MexicanTrainGame', hearts: 'HeartsGame', catan: 'CatanGame', nerts: 'NertsGame', bingo: 'BingoGame', baccarat: 'BaccaratGame', dominion: 'DominionGame', checkers: 'CheckersGame', chess: 'ChessGame', wordle: 'WordleGame', scrabble: 'ScrabbleGame', ghost: 'GhostGame' };
|
||||
const slugDispatch = { backgammon: 'Backgammon', holdem: 'HoldemGame', blackjack: 'BlackjackGame', parchisi: 'ParchisiGame', yatzi: 'YatziGame', skipbo: 'SkipBoGame', phase10: 'Phase10Game', chinesecheckers: 'ChineseCheckersGame', gofish: 'GoFishGame', uno: 'UnoGame', craps: 'CrapsGame', roulette: 'RouletteGame', mexicantrain: 'MexicanTrainGame', hearts: 'HeartsGame', catan: 'CatanGame', nerts: 'NertsGame', bingo: 'BingoGame', baccarat: 'BaccaratGame', dominion: 'DominionGame', checkers: 'CheckersGame', chess: 'ChessGame', wordle: 'WordleGame', scrabble: 'ScrabbleGame', ghost: 'GhostGame', wordladder: 'WordLadderGame' };
|
||||
if (slugDispatch[this.game.slug]) {
|
||||
this.scene.start(slugDispatch[this.game.slug], {
|
||||
game: this.game,
|
||||
|
|
@ -26,6 +27,7 @@ export default class GameRoomScene extends Phaser.Scene {
|
|||
cardBack: this.cardBack,
|
||||
tilePlacement: this.tilePlacement,
|
||||
deckMode: this.deckMode,
|
||||
wordLength: this.wordLength,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
this.selectedTilePlacement = 'standard';
|
||||
this.selectedMatchVariant = 4;
|
||||
this.selectedDeckMode = 'standard';
|
||||
this.selectedWordLength = 4;
|
||||
this._initializing = false;
|
||||
this.skillByOpp = {}; // opp.id → AI skill level 1..5 (Nerts only)
|
||||
}
|
||||
|
|
@ -121,6 +122,8 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
|
||||
if (this.gameDef.slug === 'dominion') this.buildDeckModeSection(340, 1013);
|
||||
|
||||
if (this.gameDef.slug === 'wordladder') this.buildWordLengthSection(340, 1013);
|
||||
|
||||
if (!isWordGame) {
|
||||
this.buildOptionSection('Playfield', 630, this.cache.json.get('playfields')?.playfields ?? [],
|
||||
'selectedPlayfield', 'playfieldTiles', (pf) => this.selectPlayfield(pf));
|
||||
|
|
@ -366,7 +369,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
|
||||
// Skill control: pips always show the level; the +/- buttons appear only
|
||||
// when this opponent is selected. Enabled for games with a 1–5 AI skill.
|
||||
if (['nerts', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost'].includes(this.gameDef.slug)) {
|
||||
if (['nerts', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder'].includes(this.gameDef.slug)) {
|
||||
bio.style.webkitLineClamp = '1';
|
||||
|
||||
const skillRow = document.createElement('div');
|
||||
|
|
@ -639,6 +642,52 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
});
|
||||
}
|
||||
|
||||
// ── Word Ladder: word-length toggle ───────────────────────────────────────
|
||||
buildWordLengthSection(centerX, centerY) {
|
||||
const options = [
|
||||
{ id: 3, label: '3-Letter' },
|
||||
{ id: 4, label: '4-Letter' },
|
||||
];
|
||||
const pillW = 150, pillH = 40, pillGap = 12;
|
||||
const totalW = options.length * pillW + (options.length - 1) * pillGap;
|
||||
const labelY = centerY - 28;
|
||||
const pillY = centerY + 10;
|
||||
|
||||
const labelText = this.add.text(centerX, labelY, 'Word Length', {
|
||||
fontFamily: '"Julius Sans One"',
|
||||
fontSize: '20px',
|
||||
color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5);
|
||||
const labelBg = this.add.rectangle(centerX, labelY, labelText.width + 32, labelText.height + 14, 0x000000, 0.72);
|
||||
this.children.moveBelow(labelBg, labelText);
|
||||
|
||||
this._wordLengthBtns = [];
|
||||
options.forEach((opt, i) => {
|
||||
const x = centerX - totalW / 2 + i * (pillW + pillGap) + pillW / 2;
|
||||
const isSelected = this.selectedWordLength === opt.id;
|
||||
const bg = this.add.rectangle(x, pillY, pillW, pillH, COLORS.panel)
|
||||
.setStrokeStyle(3, isSelected ? COLORS.accent : COLORS.muted)
|
||||
.setInteractive({ useHandCursor: true });
|
||||
const pillBg = this.add.rectangle(x, pillY, pillW, pillH, 0x000000, 0.72);
|
||||
this.children.moveBelow(pillBg, bg);
|
||||
this.add.text(x, pillY, opt.label, {
|
||||
fontFamily: '"Julius Sans One"',
|
||||
fontSize: '16px',
|
||||
color: COLORS.textHex,
|
||||
}).setOrigin(0.5);
|
||||
|
||||
const refresh = () => {
|
||||
this._wordLengthBtns.forEach(({ bg: b, id }) =>
|
||||
b.setStrokeStyle(3, id === this.selectedWordLength ? COLORS.accent : COLORS.muted)
|
||||
);
|
||||
};
|
||||
bg.on('pointerup', () => { this.selectedWordLength = opt.id; refresh(); });
|
||||
bg.on('pointerover', () => { if (this.selectedWordLength !== opt.id) bg.setStrokeStyle(3, COLORS.text); });
|
||||
bg.on('pointerout', () => { if (this.selectedWordLength !== opt.id) bg.setStrokeStyle(3, COLORS.muted); });
|
||||
this._wordLengthBtns.push({ bg, id: opt.id });
|
||||
});
|
||||
}
|
||||
|
||||
// ── Generic option section builder ─────────────────────────────────────────
|
||||
|
||||
buildOptionSection(label, labelY, items, selectedProp, tilesProp, onSelect, tileW = TILE_W, tileH = TILE_H, tileGap = TILE_GAP) {
|
||||
|
|
@ -747,7 +796,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
// ── Start game ─────────────────────────────────────────────────────────────
|
||||
|
||||
startGame() {
|
||||
if (this.selected.size === 0) return;
|
||||
if (this.selected.size < (this.gameDef.minOpponents ?? 1)) return;
|
||||
this._startingGame = true;
|
||||
stopMenuMusic();
|
||||
const opponents = this.cards
|
||||
|
|
@ -761,6 +810,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
tilePlacement: this.selectedTilePlacement,
|
||||
matchVariant: this.selectedMatchVariant,
|
||||
deckMode: this.selectedDeckMode,
|
||||
wordLength: this.selectedWordLength,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,3 +47,4 @@ registerGame({ slug: 'chess', name: 'Chess', category: 'tabletop', minPlayers: 2
|
|||
registerGame({ slug: 'wordle', name: 'Wordle', category: 'word', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1 });
|
||||
registerGame({ slug: 'scrabble', name: 'Scrabble', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3 });
|
||||
registerGame({ slug: 'ghost', name: 'Ghost', category: 'word', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1 });
|
||||
registerGame({ slug: 'wordladder', name: 'Word Ladder', category: 'word', minPlayers: 1, maxPlayers: 2, minOpponents: 0, maxOpponents: 1 });
|
||||
|
|
|
|||
|
|
@ -111,6 +111,49 @@ export function chooseLetter(fragment, skill) {
|
|||
return { letter, isWord: !!child.terminal, isPrefix: true };
|
||||
}
|
||||
|
||||
// ── Public: example safe words from a faced prefix ─────────────────────────────
|
||||
|
||||
// Given the fragment a player FACED (before their losing letter), return up to
|
||||
// `max` complete words they could have headed toward via a safe move — i.e. a
|
||||
// letter that does not itself complete a word. Returns [] when no safe move
|
||||
// existed (the player was genuinely cornered).
|
||||
export function suggestWords(prefix, max = 3) {
|
||||
const P = String(prefix).toUpperCase();
|
||||
const node = nodeFor(P);
|
||||
if (!node) return [];
|
||||
|
||||
const safe = Object.keys(node.children).filter(L => !node.children[L].terminal);
|
||||
shuffleInPlace(safe);
|
||||
|
||||
const words = [];
|
||||
for (const L of safe) {
|
||||
const w = shortestWord(node.children[L], P + L);
|
||||
if (w && !words.includes(w)) words.push(w);
|
||||
if (words.length >= max) break;
|
||||
}
|
||||
return words;
|
||||
}
|
||||
|
||||
// Shortest complete word at or below `node` (BFS), prefixed by `prefix`.
|
||||
function shortestWord(node, prefix) {
|
||||
const queue = [[node, prefix]];
|
||||
let i = 0;
|
||||
while (i < queue.length) {
|
||||
const [n, p] = queue[i++];
|
||||
if (n.terminal) return p;
|
||||
for (const L in n.children) queue.push([n.children[L], p + L]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function shuffleInPlace(arr) {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
function randomFrom(arr) {
|
||||
return arr[Math.floor(Math.random() * arr.length)];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,238 @@
|
|||
// Server-side Word Ladder dictionary + puzzle generator + skill-based AI.
|
||||
//
|
||||
// Word Ladder: transform a START word into a TARGET word by changing exactly one
|
||||
// letter at a time, where every intermediate rung is a real word of the same
|
||||
// length (COLD → CORD → CARD → WARD → WARM).
|
||||
//
|
||||
// The word graph (one node per word, an edge between words differing in exactly
|
||||
// one position) is implicit: neighbours are generated on demand by trying all 25
|
||||
// substitutions at each position and testing membership in a Set. The graphs are
|
||||
// small (a few thousand 3/4-letter words), so BFS over them is cheap.
|
||||
|
||||
const LENGTHS = [3, 4];
|
||||
const A = 'A'.charCodeAt(0);
|
||||
|
||||
// Optimal-path length ranges that make a satisfying puzzle, per word length.
|
||||
const PAR_RANGE = {
|
||||
3: [3, 5],
|
||||
4: [4, 6],
|
||||
};
|
||||
|
||||
// Skill profiles for the AI opponent. `wander` = chance of stepping onto a
|
||||
// non-progress neighbour (a detour it must later recover from). `delay` =
|
||||
// "thinking" time [lo, hi] ms before each rung (pacing, not intelligence).
|
||||
const SKILL = {
|
||||
1: { wander: 0.70, delay: [9000, 15000] },
|
||||
2: { wander: 0.55, delay: [7000, 11000] },
|
||||
3: { wander: 0.42, delay: [5000, 8000] },
|
||||
4: { wander: 0.28, delay: [3500, 6000] },
|
||||
5: { wander: 0.15, delay: [2500, 4500] },
|
||||
};
|
||||
|
||||
const wordSets = {}; // length → Set<string>
|
||||
const wordArrays = {}; // length → string[]
|
||||
|
||||
export function initWordLadderDictionary(words3, words4) {
|
||||
setFor(3, words3);
|
||||
setFor(4, words4);
|
||||
}
|
||||
|
||||
function setFor(length, words) {
|
||||
const arr = (words ?? []).map(w => String(w).toUpperCase()).filter(w => w.length === length);
|
||||
wordSets[length] = new Set(arr);
|
||||
wordArrays[length] = [...wordSets[length]];
|
||||
}
|
||||
|
||||
export function dictionaryReady() {
|
||||
return LENGTHS.every(L => wordArrays[L]?.length > 0);
|
||||
}
|
||||
|
||||
// ── Graph ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Valid words differing from `word` in exactly one position.
|
||||
export function neighbors(word) {
|
||||
const W = String(word).toUpperCase();
|
||||
const set = wordSets[W.length];
|
||||
if (!set) return [];
|
||||
const out = [];
|
||||
for (let i = 0; i < W.length; i++) {
|
||||
const before = W.slice(0, i);
|
||||
const after = W.slice(i + 1);
|
||||
const orig = W[i];
|
||||
for (let c = 0; c < 26; c++) {
|
||||
const ch = String.fromCharCode(A + c);
|
||||
if (ch === orig) continue;
|
||||
const cand = before + ch + after;
|
||||
if (set.has(cand)) out.push(cand);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// BFS from `start`; returns Map<word, distance> over the connected component.
|
||||
// `maxDepth` (optional) bounds the search for puzzle generation.
|
||||
function bfsDistances(start, maxDepth = Infinity) {
|
||||
const dist = new Map([[start, 0]]);
|
||||
const queue = [start];
|
||||
let i = 0;
|
||||
while (i < queue.length) {
|
||||
const w = queue[i++];
|
||||
const d = dist.get(w);
|
||||
if (d >= maxDepth) continue;
|
||||
for (const n of neighbors(w)) {
|
||||
if (!dist.has(n)) {
|
||||
dist.set(n, d + 1);
|
||||
queue.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
// Shortest path between two words (inclusive of both ends), or null.
|
||||
export function shortestPath(from, to) {
|
||||
const start = String(from).toUpperCase();
|
||||
const goal = String(to).toUpperCase();
|
||||
if (start === goal) return [start];
|
||||
if (start.length !== goal.length) return null;
|
||||
|
||||
const prev = new Map([[start, null]]);
|
||||
const queue = [start];
|
||||
let i = 0;
|
||||
while (i < queue.length) {
|
||||
const w = queue[i++];
|
||||
for (const n of neighbors(w)) {
|
||||
if (prev.has(n)) continue;
|
||||
prev.set(n, w);
|
||||
if (n === goal) {
|
||||
const path = [];
|
||||
for (let cur = goal; cur !== null; cur = prev.get(cur)) path.unshift(cur);
|
||||
return path;
|
||||
}
|
||||
queue.push(n);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Puzzle generation ────────────────────────────────────────────────────────
|
||||
|
||||
// Build a puzzle whose optimal solution is exactly `par` steps. Retries with
|
||||
// fresh random starts; relaxes to the deepest reachable target if `par` proves
|
||||
// hard to hit for the chosen start.
|
||||
function generatePuzzleWithPar(length, par, attempts = 300) {
|
||||
const pool = wordArrays[length] ?? [];
|
||||
if (pool.length === 0) return null;
|
||||
|
||||
for (let a = 0; a < attempts; a++) {
|
||||
const start = randomFrom(pool);
|
||||
const dist = bfsDistances(start, par);
|
||||
const exact = [];
|
||||
let deepest = null, deepestD = 0;
|
||||
for (const [word, d] of dist) {
|
||||
if (word === start) continue;
|
||||
if (d === par) exact.push(word);
|
||||
if (d > deepestD) { deepest = word; deepestD = d; }
|
||||
}
|
||||
if (exact.length > 0) {
|
||||
const target = randomFrom(exact);
|
||||
return { start, target, par };
|
||||
}
|
||||
// Last few attempts: accept the deepest target we can reach (>= 2 steps).
|
||||
if (a >= attempts - 5 && deepest && deepestD >= 2) {
|
||||
return { start, target: deepest, par: deepestD };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickPar(length) {
|
||||
const [lo, hi] = PAR_RANGE[length] ?? [3, 5];
|
||||
return lo + Math.floor(Math.random() * (hi - lo + 1));
|
||||
}
|
||||
|
||||
// Single puzzle (solo mode).
|
||||
export function generatePuzzle(length) {
|
||||
const L = LENGTHS.includes(length) ? length : 4;
|
||||
return generatePuzzleWithPar(L, pickPar(L)) ?? fallbackPuzzle(L);
|
||||
}
|
||||
|
||||
// Two distinct puzzles of equal par (versus mode — fair race).
|
||||
export function generateVersusPuzzles(length) {
|
||||
const L = LENGTHS.includes(length) ? length : 4;
|
||||
const par = pickPar(L);
|
||||
const player = generatePuzzleWithPar(L, par) ?? fallbackPuzzle(L);
|
||||
let opponent = null;
|
||||
for (let a = 0; a < 20; a++) {
|
||||
const cand = generatePuzzleWithPar(L, player.par);
|
||||
if (cand && cand.start !== player.start && cand.target !== player.target) {
|
||||
opponent = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { player, opponent: opponent ?? generatePuzzleWithPar(L, player.par) ?? fallbackPuzzle(L) };
|
||||
}
|
||||
|
||||
// Degenerate safety net: a start word and one neighbour (par 1). Only reached if
|
||||
// the dictionary is empty/broken.
|
||||
function fallbackPuzzle(length) {
|
||||
const pool = wordArrays[length] ?? [];
|
||||
const start = pool[0] ?? 'CATS'.slice(0, length);
|
||||
const ns = neighbors(start);
|
||||
return { start, target: ns[0] ?? start, par: ns.length ? 1 : 0 };
|
||||
}
|
||||
|
||||
// ── AI opponent ────────────────────────────────────────────────────────────────
|
||||
|
||||
function profileFor(skill) {
|
||||
return SKILL[Math.max(1, Math.min(5, skill | 0))] ?? SKILL[3];
|
||||
}
|
||||
|
||||
// Advance the AI one rung from `current` toward `target`. Skill sets both pace
|
||||
// (delayMs) and accuracy (chance of a detour that lengthens its path).
|
||||
export function chooseAIMove(current, target, skill) {
|
||||
const cur = String(current).toUpperCase();
|
||||
const goal = String(target).toUpperCase();
|
||||
if (cur === goal) return { word: cur, delayMs: 0, done: true };
|
||||
|
||||
const profile = profileFor(skill);
|
||||
const ns = neighbors(cur);
|
||||
if (ns.length === 0) return { word: cur, delayMs: 0, done: false };
|
||||
|
||||
// Distances to the goal, so we know which neighbours make progress.
|
||||
const dist = bfsDistances(goal);
|
||||
const d = dist.get(cur);
|
||||
const progress = ns.filter(n => dist.get(n) === d - 1);
|
||||
const detour = ns.filter(n => dist.get(n) !== d - 1);
|
||||
|
||||
let word;
|
||||
if (detour.length > 0 && Math.random() < profile.wander) {
|
||||
word = randomFrom(detour);
|
||||
} else if (progress.length > 0) {
|
||||
word = randomFrom(progress);
|
||||
} else {
|
||||
word = randomFrom(ns);
|
||||
}
|
||||
|
||||
const [lo, hi] = profile.delay;
|
||||
const delayMs = Math.round(lo + Math.random() * (hi - lo));
|
||||
return { word, delayMs, done: word === goal };
|
||||
}
|
||||
|
||||
// ── Hint ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// The next word on a shortest path from `current` to `target`.
|
||||
export function hintMove(current, target) {
|
||||
const path = shortestPath(current, target);
|
||||
return path && path.length > 1 ? path[1] : null;
|
||||
}
|
||||
|
||||
// ── Misc ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function validWordsOfLength(length) {
|
||||
return [...(wordArrays[length] ?? [])];
|
||||
}
|
||||
|
||||
function randomFrom(arr) {
|
||||
return arr[Math.floor(Math.random() * arr.length)];
|
||||
}
|
||||
|
|
@ -3,7 +3,15 @@ import fs from 'node:fs';
|
|||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { initScrabbleDictionary, isValidWord, chooseMove } from './scrabbleEngine.js';
|
||||
import { initGhostDictionary, judge as ghostJudge, chooseLetter as ghostChooseLetter } from './ghostEngine.js';
|
||||
import { initGhostDictionary, judge as ghostJudge, chooseLetter as ghostChooseLetter, suggestWords as ghostSuggestWords } from './ghostEngine.js';
|
||||
import {
|
||||
initWordLadderDictionary,
|
||||
generatePuzzle as ladderGeneratePuzzle,
|
||||
generateVersusPuzzles as ladderGenerateVersus,
|
||||
chooseAIMove as ladderChooseAIMove,
|
||||
hintMove as ladderHintMove,
|
||||
validWordsOfLength as ladderValidWords,
|
||||
} from './wordLadderEngine.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const WORDLIST_PATH = path.join(__dirname, '../data/wordlists/enable1.txt');
|
||||
|
|
@ -125,6 +133,12 @@ function loadWordLists() {
|
|||
initGhostDictionary(ghostWords);
|
||||
console.log(`[words] loaded ${ghostWords.length} Ghost words (4+ letters)`);
|
||||
|
||||
// Word Ladder dictionaries: 3- and 4-letter words for the two game variants.
|
||||
const ladderThree = allWords.filter(w => /^[A-Z]{3}$/.test(w));
|
||||
const ladderFour = allWords.filter(w => /^[A-Z]{4}$/.test(w));
|
||||
initWordLadderDictionary(ladderThree, ladderFour);
|
||||
console.log(`[words] loaded Word Ladder dictionaries (${ladderThree.length} 3-letter, ${ladderFour.length} 4-letter)`);
|
||||
|
||||
// Answer pool: prefer curated common words that are also in ENABLE;
|
||||
// supplement with additional ENABLE words up to a healthy pool size.
|
||||
const curated = [...COMMON_WORDS].filter(w => enableFive.has(w));
|
||||
|
|
@ -203,4 +217,45 @@ router.post('/ghost/ai-move', (req, res) => {
|
|||
res.json(ghostChooseLetter(fragment, skill));
|
||||
});
|
||||
|
||||
// POST /api/words/ghost/suggest { prefix: string, max?: number }
|
||||
// Example safe words the loser could have headed toward from the faced prefix.
|
||||
router.post('/ghost/suggest', (req, res) => {
|
||||
const prefix = String(req.body?.prefix ?? '');
|
||||
const max = Number(req.body?.max) || 3;
|
||||
res.json({ words: ghostSuggestWords(prefix, max) });
|
||||
});
|
||||
|
||||
// ── Word Ladder ────────────────────────────────────────────────────────────────
|
||||
|
||||
// GET /api/words/wordladder/start?length=3|4&versus=true|false
|
||||
// Solo: { player, opponent: null, validWords }.
|
||||
// Versus: { player, opponent, validWords } — two puzzles of equal par.
|
||||
router.get('/wordladder/start', (req, res) => {
|
||||
const length = Number(req.query.length) === 3 ? 3 : 4;
|
||||
const versus = String(req.query.versus) === 'true';
|
||||
const validWords = ladderValidWords(length);
|
||||
if (versus) {
|
||||
const { player, opponent } = ladderGenerateVersus(length);
|
||||
return res.json({ player, opponent, validWords });
|
||||
}
|
||||
res.json({ player: ladderGeneratePuzzle(length), opponent: null, validWords });
|
||||
});
|
||||
|
||||
// POST /api/words/wordladder/ai-move { current, target, skill }
|
||||
// Advances the AI opponent one rung toward its target.
|
||||
router.post('/wordladder/ai-move', (req, res) => {
|
||||
const current = String(req.body?.current ?? '');
|
||||
const target = String(req.body?.target ?? '');
|
||||
const skill = Number(req.body?.skill) || 3;
|
||||
res.json(ladderChooseAIMove(current, target, skill));
|
||||
});
|
||||
|
||||
// POST /api/words/wordladder/hint { current, target }
|
||||
// One valid next step on a shortest path toward the target.
|
||||
router.post('/wordladder/hint', (req, res) => {
|
||||
const current = String(req.body?.current ?? '');
|
||||
const target = String(req.body?.target ?? '');
|
||||
res.json({ word: ladderHintMove(current, target) });
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
|
|
|||
Loading…
Reference in New Issue