@junli-gong/arcade-core
v2.0.0
Published
Pure, immutable 2048 rules for browsers and Node.js.
Maintainers
Readme
Arcade Core
2048 rules for Node.js and browsers, with no runtime dependencies. Functions return new boards. The app manages scores, storage, controls and UI.
Installation
npm install @junli-gong/arcade-coreExample
import { move, spawn, hasMoves, canMove } from '@junli-gong/arcade-core';
let board = Array.from({ length: 4 }, () => Array(4).fill(null));
board = spawn(spawn(board));
let score = 0;
if (canMove(board, 'left')) {
const moved = move(board, 'left');
score += moved.flat().reduce((sum, tile) => sum + (tile?.merged ? tile.value : 0), 0);
board = spawn(moved);
}
console.log({ board, score, gameOver: !hasMoves(board) });Read the merge markers before calling spawn: every operation resets old
markers. A valid action spawns once; an invalid action must not call spawn.
An empty board has no possible slide (hasMoves is false), so initialize it
with two calls to spawn before starting play.
Board contract
- A board is exactly four rows of four cells:
board[row][column]. Row 0 is the top edge and column 0 is the left edge. - An empty cell is
null. An occupied cell is{ id, value, merged? }. idis a unique positive safe integer on the current board.valueis a safe integer power of two starting at 2. Optionalmergedis a boolean.- Returned tiles always have
id,value, andmerged; extra tile properties are not carried over. Inputs, rows, and tile objects are never mutated. - Returned rows and occupied tile objects are always new, even on a no-op or a full-board spawn. No returned object aliases an input object.
- Tiles that only slide preserve their ids. Each merge product receives a fresh
id above the greatest input id. This prevents a spawned tile from reusing an id
removed by a merge in the same rendered update. Only merge products have
merged: truefor thatmove. - Merge ids are allocated sequentially from
max(input ids) + 1: visit rows top-to-bottom for horizontal moves, or columns left-to-right for vertical moves, and process each line from its destination edge.spawnthen usesmax(current ids) + 1. This is deterministic and requires no global counter. - With the normal move-then-spawn lifecycle, newly created ids always exceed the previous board's maximum. Resetting a game may restart ids from 1.
API
Only the following four functions are public exports.
move(board, direction) → Board
Directions are exactly 'up', 'down', 'left', and 'right'. All tiles slide
to that edge. Equal adjacent tiles merge once per move, after gaps are removed:
[2, 2, 2, 2] → [4, 4, null, null] and [4, 4, 8, null] → [8, 8, null, null]
when moving left. No new tile is spawned. Every tile not produced by this move's
merge has merged: false, including previously marked tiles.
canMove(board, direction) → boolean
Returns whether a slide would change positions or values. It ignores old merge
markers. Use this to skip invalid actions, prevent extra spawns, and keep the
score unchanged for a no-op. The direction uses the same validation as move.
hasMoves(board) → boolean
Returns whether at least one direction can change the board. A full board with
no equal neighbors returns false; a full board with an equal pair returns
true. A nonempty board with a gap always has a possible move. An entirely
empty board returns false, because a slide cannot change it.
spawn(board, rng = Math.random) → Board
Chooses one empty cell uniformly, scanning empties in row-major order. The first
rng() sample selects its index with Math.floor(sample * emptyCount); the
second makes a 2 for [0, 0.9) or a 4 for [0.9, 1). Exactly two samples are
consumed when a tile is created. A full board returns a fresh copy and makes no
RNG calls. Both spawned and existing tiles have merged: false.
rng must be a no-argument function returning a finite number in [0, 1).
Inject a seeded or fixed generator to reproduce games. For example:
const empty = Array.from({ length: 4 }, () => Array(4).fill(null));
const predictable = spawn(empty, () => 0); // id 1, value 2, at [0][0]Math.random is the convenience default; reproducible results require an
explicit generator. The package never changes or stores that generator.
Errors
Malformed boards, duplicate ids, invalid directions, and non-function RNGs
throw TypeError. Out-of-range RNG samples or exhausted safe tile ids throw
RangeError. Invalid input never mutates the board. Errors thrown by a caller's
RNG are allowed to propagate. A merge that would exceed Number.MAX_SAFE_INTEGER
throws RangeError instead of returning a board outside this contract. Movement
predicates still describe the 2048 rule, without performing the merge arithmetic.
Development and packaging
Requires Node 20 or newer. No dependencies need installation for these tests.
npm test
npm run pack:check
npm packprepublishOnly runs the tests before npm publish --access public. The package
ships only src, this README, the MIT license, package metadata, and the
changelog. The deployed app installs the published version from npm; local
tarballs are used only during development.
Credits
2048 rules follow the course assignment and Gabriele Cirulli's original game. The implementation and tests were written for this project; no 2048 helper library is used.
