When we added self-hosted daily puzzles and card-game tools to IviGames, we wanted every game to load instantly, run offline-friendly in the browser with no in-game video ads, and produce identical daily boards across every time zone without calling a backend API.

To keep the game rules easy to test and reuse, we separated the pure logic from all DOM and UI code and open-sourced all four engines under the MIT license: yanjingzhan/browser-puzzle-engines.

  • Zero runtime dependencies (pure ES modules for modern browsers and Node.js >=18)
  • Deterministic UTC daily seeds using a lightweight mulberry32 PRNG
  • Covered by Node's built-in node --test runner

Here is a quick breakdown of the core algorithms and edge cases we solved in each engine.

1. Unique-Solution 9x9 Sudoku (src/sudoku.js)

The most common bug in DIY Sudoku generators is removing random clues without verifying uniqueness. If a board ends up with two valid solutions, players hit an unfair guess at the end.

In src/sudoku.js, we start from a shuffled valid solved board and remove cells one by one. Before accepting each removal, we run countSolutions(puzzle, 2)—a backtracking solver that tracks row, column, and 3x3 box constraints with three Int32Array(9) bitmasks and picks the next empty cell using the Minimum Remaining Values (MRV) heuristic. It aborts as soon as solutions >= 2:

const ALL = 0x3fe; // bits 1..9 for (let k = 0; k < empties.length; k++) { const idx = empties[k]; if (idx === -1) continue; const r = Math.floor(idx / 9); const c = idx % 9; const b = Math.floor(r / 3) * 3 + Math.floor(c / 3); const cands = ALL & ~(rows[r] | cols[c] | boxes[b]); const cnt = bitCount(cands); if (cnt === 0) return; if (cnt < bestCount) { bestCount = cnt; bestPos = k; bestCands = cands; if (cnt === 1) break; } } 

Because bitmask lookups and MRV pruning keep the search tree tiny, generating a guaranteed unique-solution board (easy: 42 clues, medium: 34 clues, hard: 28 clues) takes only milliseconds in the browser, and getDailySudoku(dateStr) produces the exact same board for every player on a given UTC date.

2. Immutable 4x4 2048 Engine (src/merge2048.js)

Writing separate loop logic for left, right, up, and down invites off-by-one bugs—especially around the rule that a merged tile cannot merge a second time in the same move (for example, [2, 2, 4, 0] sliding left must produce [4, 4, 0, 0], not [8, 0, 0, 0]).

Instead of four separate implementations, slideBoard(grid, direction) extracts each row or column in the movement direction, feeds it through a single pure slideLineLeft(line) helper, and writes the transformed line back into a fresh 4x4 grid:

function slideLineLeft(line) { const nums = line.filter((v) => v !== 0); const out = []; let scoreGained = 0; let reached2048 = false; for (let i = 0; i < nums.length; i++) { if (i + 1 < nums.length && nums[i] === nums[i + 1]) { const merged = nums[i] * 2; out.push(merged); scoreGained += merged; if (merged >= 2048) reached2048 = true; i++; // skip the next tile so it cannot double-merge } else { out.push(nums[i]); } } while (out.length < 4) out.push(0); const moved = out.some((v, idx) => v !== line[idx]); return { line: out, moved, scoreGained, reached2048 }; } 

Because every step returns a brand-new grid without mutating state, undo stacks, score tracking, and seeded daily starts (createInitialState({ mode: 'daily', dateStr })) stay trivial to reason about.

3. Duplicate-Letter 5-Letter Word Evaluation (src/word.js)

Evaluating a 5-letter word guess looks simple until duplicate letters show up. A single-pass check will mistakenly mark a second copy of a letter as present (yellow) even when the answer only contains that letter once and it was already matched in the right spot.

evaluateGuess(guessInput, answerInput) avoids that with a strict two-pass frequency map:

export function evaluateGuess(guessInput, answerInput) { const guess = String(guessInput || '').toUpperCase(); const answer = String(answerInput || '').toUpperCase(); const statuses = Array(5).fill('absent'); const remaining = {}; // Pass 1: lock exact matches and count unmatched answer letters for (let i = 0; i < 5; i++) { if (guess[i] === answer[i]) { statuses[i] = 'correct'; } else { remaining[answer[i]] = (remaining[answer[i]] || 0) + 1; } } // Pass 2: only mark misplaced letters while remaining count > 0 for (let i = 0; i < 5; i++) { if (statuses[i] === 'correct') continue; const ch = guess[i]; if (remaining[ch] > 0) { statuses[i] = 'present'; remaining[ch] -= 1; } } return statuses; } 

The module also ships with a curated answer list (ANSWER_WORDS), an expanded valid-guess set (VALID_WORDS), UTC daily rotation (getDailyAnswer), and emoji share-grid formatting (formatShareText).

4. Spades Partnership Scoring & Sandbag Rollover (src/spades.js)

Card-game scorekeepers fail fast when you try to mutate running totals in place—editing an earlier hand corrupts bag counts and -100 penalties downstream.

src/spades.js models every hand as a pure function (scoreTeamHand) and computes the entire match from scratch via replayHands(hands, options). Each hand calculates base bid points (bid * 10 + overtricks, or -bid * 10 if set), Nil / Blind Nil deltas (±100 / ±200), and automatic 10-bag sandbag penalties:

const bagTotal = prevBags + bagsEarned; const sandbagTriggers = sandbagPenalty ? Math.floor(bagTotal / 10) : 0; const nextBags = sandbagPenalty ? bagTotal % 10 : bagTotal; const penaltyPoints = sandbagTriggers * -100; const netPoints = handPoints + penaltyPoints; 

Live Demos & Source Code

You can try all four engines live in the browser or pull the MIT-licensed modules directly from GitHub:

Engine Module Live Browser Demo
Sudoku generator & solver src/sudoku.js Daily Sudoku on IviGames
2048 sliding grid src/merge2048.js Number Merge 2048 on IviGames
5-letter word game src/word.js Daily 5-Letter Word on IviGames
Spades partnership scorer src/spades.js Spades Scorekeeper on IviGames

Feedback, edge-case reports, and PRs are welcome!