以純 TypeScript 實作 4 款經典益智及棋盤遊戲求解器:Trie、DP、Minimax、AST
Implementing 4 Classic Puzzle & Board-Game Solvers in Pure TypeScript (Trie, DP, Minimax, AST)
Lifevor 的遊戲求解器集合以純 TypeScript 實作 4 款經典益智及棋盤遊戲求解器,涵蓋 Word Hunt、Nonogram、Connect 4 和 24 Game。四者分別採用 Trie 剪枝 DFS、記憶化 DP、Minimax 配合 Alpha-Beta,以及浮點數 AST;所有求解器均在瀏覽器內運行,無須與伺服器往返。
Classic puzzle and board-game solvers are some of the most rewarding things to build in TypeScript—and running them 100% client-side in the browser forces you to care about pruning, memoization, and subtle edge cases that never show up in textbook pseudocode.
While building the game solver collection on Lifevor, we implemented four completely different algorithmic engines in pure TypeScript. Here are the concrete data structures and gotchas behind each one.
1. Word Hunt: Trie-Pruned 8-Way DFS in a Web Worker
In our Word Hunt Solver, a naive DFS over a 4×4 or 5×5 letter grid explodes factorially if you walk every path before checking a dictionary.
Loading the word list into a Trie (TrieNode with children and isWord) lets us prune dead prefixes on the very first mismatched character:
function dfs(
index: number,
node: TrieNode,
currentWord: string,
currentPath: number[],
visited: boolean[]
) {
const char = letters[index]!;
const nextNode = node.children[char];
if (!nextNode) return; // Instant prefix pruning
const nextWord = currentWord + char;
currentPath.push(index);
visited[index] = true;
if (nextNode.isWord && nextWord.length >= 3 && !results.has(nextWord)) {
results.set(nextWord, {
word: nextWord,
path: [...currentPath],
score: getScore(nextWord.length),
});
}
const row = Math.floor(index / size);
const col = index % size;
for (const [dr, dc] of dirs) {
const nr = row + dr;
const nc = col + dc;
if (nr >= 0 && nr < size && nc >= 0 && nc < size) {
const nextIndex = nr * size + nc;
if (!visited[nextIndex]) {
dfs(nextIndex, nextNode, nextWord, currentPath, visited);
}
}
}
currentPath.pop();
visited[index] = false;
}
Running this inside a dedicated Web Worker keeps the UI responsive even on 5×5 grids while returning every valid swipe path sorted by score.
2. Nonogram: Memoized DP Line Deduction
In our Nonogram Solver, enumerating every valid permutation of a 20×20 row blows up quickly. Instead, we model each cell as a tri-state (0: Unknown, 1: Filled, 2: Empty) and use a memoized feasibility function dp(idx, bIdx) to check whether the remaining clue blocks can legally fit from position idx.
One crucial invariant inside the placement loop: you can never skip past a cell already known to be filled (1):
if (line[i]! === 1) {
break; // Must consume this filled cell, cannot skip it
}
Once dp(0, 0) confirms a row or column is satisfiable, deducing forced cells is clean and exact: for each unknown cell 0, temporarily test 1 (canBe1) and 2 (canBe2). If only one branch is satisfiable, that cell is logically forced; if neither is, we hit a contradiction and backtrack.
3. Connect 4: Avoiding Static Evaluation Parity Artifacts
In our Connect 4 Solver, the Minimax + Alpha-Beta search evaluates every 4-cell window (horizontal, vertical, and both diagonals) alongside positional column weights.
One subtle trap when tuning positional weights on a 6×7 board is giving higher weights to middle rows than bottom rows. Because Connect 4 pieces fall with gravity, row-varying weights create a "vertical parity" evaluation artifact where the engine misvalues stacked threats. Using uniform column weights across all 6 rows ([10, 20, 30, 40, 30, 20, 10]) strictly enforces center-column dominance without distorting vertical threat evaluation.
4. 24 Game: Floating-Point Fractions & Safe Parenthesis Stripping
In our 24 Game Solver, integer-only arithmetic fails on famous fraction puzzles like 8, 8, 3, 3 (8 ÷ (3 − 8 ÷ 3) = 24).
We evaluate an ExpressionNode AST in floating point with a 1e-6 epsilon check (Math.abs(result.value - 24) < 1e-6) and flag any step where Math.abs(left.value % right.value) > 1e-6 so fraction-based solutions are clearly highlighted.
Another small formatting bug to watch out for: blindly stripping leading ( and trailing ) breaks expressions like (3 + 5) * (1 + 2) into 3 + 5) * (1 + 2. Always track parenthesis depth from index 1 to length - 2—only strip the outer pair if depth never drops below 0.
Try Them Live
All four solvers run entirely inside the browser with zero server round-trips. You can test any of them directly on Lifevor.
來源:DEV Community · dev.to