2048 in a pane. Slide tiles with w, a, s and d, merge equal numbers, reach 2048. Two undos, a best score that survives restarts, and a board that replays from…

2048 in a pane beside the conversation. Slide the tiles with w, a, s and d; two equal tiles that meet merge into one and score; a new tile appears after every move. Make a 2048 tile, then keep going for a higher one. Two undos, a best score and highest tile that survive restarts, and a board that replays from its seed.
It's a game you play, not a watcher: it never calls a model, never reads what Claude is doing, and costs no tokens.

Recorded in a terminal. The Desktop app draws the same pane, with each key shown as a badge.
2048 score 1256 best 4512 · highest 512 · move 83
Score 1256 · best 4512
┌─────┐┌─────┐┌─────┐┌─────┐
│ ││ 2 ││ 8 ││ 4 │
└─────┘└─────┘└─────┘└─────┘
┌─────┐┌─────┐┌─────┐┌─────┐
│ 2 ││ 16 ││ 32 ││ 16 │
└─────┘└─────┘└─────┘└─────┘
┌─────┐┌─────┐┌─────┐┌─────┐
│ 8 ││ 64 ││ 128 ││ 32 │
└─────┘└─────┘└─────┘└─────┘
┌─────┐┌─────┐┌─────┐┌─────┐
│ 16 ││ 256 ││ 512 ││ 64 │
└─────┘└─────┘└─────┘└─────┘
w: Up a: Left s: Down d: Right
n: New game u: Undo (2) h: Help Esc closes
The tiles are colored, which the text above can't show. They use the original game's palette, so the board looks the same on any theme: beige empty slots, cream 2s and 4s, orange deepening through 8 to 64, gold from 128 to 2048, and near-black beyond. Each tile is three rows tall with its number centered.
/plugin marketplace add MDmubarak786/claude-mods
/plugin install game-2048@modhub
Try it for one session without installing:
claude --plugin-dir ./mods/game-2048
/2048. The pane opens with two tiles on a 4 by 4 board. A fresh board shows a short how-to until you hide it with h, which also shows it again.The keys work while the pane has the focus. If pressing w types into the prompt instead, click the pane first.
| Command | What it does |
|---|---|
/2048 | Open the pane. Where no pane can be drawn, print the board and the score. |
/2048 new | Start a new game. |
/2048 stats | Games played, best score, highest tile. |
From claude plugin validate ./mods/game-2048:
hooks: session.start, classic.SessionStart{source=clear|resume|fork}, command.run{command="2048"}, ui.render{component=Pane}
calls: $.clock.now (via load, startNew), $.command.register, $.session.surfaces, $.state.get, $.state.set, $.store.get (via load), $.store.set (via save), $.ui.invalidate, $.ui.log, $.ui.open, $.ui.resolve, $.ui.toast
$.store keeps the board, the score, the last two moves for undo, and the record, so a game survives a restart. A game saved by 0.1.x, with its single undo, loads as it was. If the store can't be read at start, the mod plays in memory and writes nothing over the saved record.$.clock seeds each game. There is no timer: nothing happens between your moves.claude plugin validate --strict and claude plugin test passing: line sliding and merging, all four directions, seeded spawns, a move that changes nothing, two undos and a refused third, a saved game from 0.1.x, game over on a locked board, the 2048 win that keeps play going, mounted pane tests for the keys, the status lines, the commands, an unreadable store, and a narrow pane.MIT, see the repository root.
hooks/register.ts 231 lines1// 2048: slide tiles, merge equal numbers, reach 2048, in a pane.
2//
3// /2048 open the game
4// /2048 new start a new game
5// /2048 stats games, best score, highest tile
6//
7// In the pane: w, a, s and d slide the tiles up, left, down and right; u takes
8// a move back, up to two, n starts a new game, h shows the how-to. Nothing here
9// calls a model, reads what Claude is doing, or leaves the machine.
10
11import { atom, read, update } from 'claude-code'
12import type { Game, Stats } from '../types'
13import { GOAL, MAX_UNDO, SIZE, at, isGame, migrate, move, newGame, undo, type Dir } from './game'
14
15const PANE = '2048'
16const EMPTY_STATS: Stats = { games: 0, best: 0, highest: 0 }
17const EMPTY: Game = { seed: 0, cells: [], score: 0, moves: 0, won: false, over: false, prev: [], stats: EMPTY_STATS }
18const game = atom({ plugin: 'game-2048', key: 'game' } as const, EMPTY)
19
20// The how-to block: shown on a fresh board until h hides it, for the session.
21let help: boolean | null = null
22// False after the store could not be read: then nothing is written over the
23// saved record until a later load reads it.
24let storeOk = true
25
26async function save($, g: Game) {
27 if (!storeOk) return
28 try {
29 await $.store.set('game', g)
30 } catch {
31 // The drawing still updates; the store catches up on the next change.
32 }
33}
34
35async function change($, fn: (cur: Game) => Game): Promise<Game> {
36 let out: Game | null = null
37 await update($, game, (cur) => {
38 out = fn(cur)
39 return out
40 })
41 if (out) await save($, out)
42 return out ?? (await read($, game))
43}
44
45async function load($) {
46 let saved: unknown = undefined
47 let upgraded = false
48 let readable = true
49 try {
50 const raw = await $.store.get('game')
51 saved = migrate(raw)
52 upgraded = saved !== raw
53 } catch {
54 readable = false
55 }
56 storeOk = readable
57 if (isGame(saved)) {
58 await update($, game, () => saved as Game)
59 // A game saved in an older shape is written back in the current one.
60 if (upgraded) await save($, saved)
61 return
62 }
63 if (!readable) {
64 const cur = await read($, game)
65 if (!cur.seed) await update($, game, () => newGame(Date.now(), { ...EMPTY_STATS, games: 1 }))
66 $.ui.log('2048 could not read its saved game; playing without saving')
67 return
68 }
69 const fresh = newGame(await $.clock.now(), { ...EMPTY_STATS, games: 1 })
70 await update($, game, () => fresh)
71 await save($, fresh)
72}
73
74async function startNew($) {
75 const now = await $.clock.now()
76 return change($, (cur) => newGame(now, { ...cur.stats, games: cur.stats.games + 1 }))
77}
78
79function summary(g: Game): string {
80 if (!g.seed) return 'No game yet.'
81 const row = (r: number) => Array.from({ length: SIZE }, (_, c) => g.cells[at(r, c)] || '.').join(' ')
82 const state = g.over ? 'No moves left.' : g.won ? 'You reached ' + GOAL + '; keep going.' : 'In play.'
83 return '2048: ' + Array.from({ length: SIZE }, (_, r) => row(r)).join(' / ') + '. Score ' + g.score + ', best ' + g.stats.best + '. ' + state + ' /2048 opens the pane.'
84}
85
86// The original game's tile colors, which read the same on any theme: a board of
87// beige slots, cream for 2 and 4, orange climbing to the gold of 2048, and
88// near-black beyond it. Light text on the dark tiles, dark text on the light.
89const TILES: Record<number, [string, string]> = {
90 2: ['#eee4da', '#776e65'],
91 4: ['#ede0c8', '#776e65'],
92 8: ['#f2b179', '#f9f6f2'],
93 16: ['#f59563', '#f9f6f2'],
94 32: ['#f67c5f', '#f9f6f2'],
95 64: ['#f65e3b', '#f9f6f2'],
96 128: ['#edcf72', '#f9f6f2'],
97 256: ['#edcc61', '#f9f6f2'],
98 512: ['#edc850', '#f9f6f2'],
99 1024: ['#edc53f', '#f9f6f2'],
100 2048: ['#edc22e', '#f9f6f2'],
101}
102const EMPTY_TILE = '#cdc1b4'
103function tileStyle(v: number): [string, string] {
104 if (!v) return [EMPTY_TILE, EMPTY_TILE]
105 return TILES[v] ?? ['#3c3a32', '#f9f6f2']
106}
107
108export function register(on) {
109 on('session.start', async ($, e, next) => {
110 help = null
111 try {
112 await load($)
113 } catch (error) {
114 $.ui.log('2048 could not load its game: ' + error)
115 }
116 try {
117 await $.command.register({ name: '2048', description: 'Play 2048 in a pane', argumentHint: '[new | stats]', immediate: true })
118 } catch (error) {
119 $.ui.log('could not register /2048: ' + error)
120 }
121 return next(e)
122 })
123
124 // /clear and /resume reset $.state; the game lives on in the store.
125 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
126 await load($)
127 return next(e)
128 }).catch(async ($, e, next) => next(e))
129
130 on('command.run', { command: '2048' }, async ($, e) => {
131 const args = e.args.trim().toLowerCase()
132 if (args === 'new') return { text: 'New game. ' + summary(await startNew($)) }
133 if (args === 'stats') {
134 const s = (await read($, game)).stats
135 return { text: 'Games ' + s.games + ' · best score ' + s.best + ' · highest tile ' + s.highest }
136 }
137 if (args) return { text: 'Usage: /2048, /2048 new, or /2048 stats' }
138 // Under claude -p nothing draws, and ui.open still reports the pane as placed:
139 // the surfaces list is the reliable sign.
140 let surfaces = []
141 try {
142 surfaces = await $.session.surfaces()
143 } catch {
144 surfaces = []
145 }
146 if (!surfaces.length) return { text: summary(await read($, game)) }
147 const placed = await $.ui.open({ id: PANE, title: '2048', focus: true, closeOnEscape: true, rows: 32 })
148 if (!placed.isPlaced) return { text: summary(await read($, game)) }
149 return {}
150 }).catch(async () => ({ text: '2048: the command failed.' }))
151
152 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
153 if (e.requestId !== PANE) return next(e)
154 const g = await read($, game)
155 const { Box, Text, Button } = $.ui.resolve(e)
156 if (!g.seed) return Text({ children: ['No game loaded. /2048 new starts one.'] })
157 const columns = e.props.bodyColumns || 60
158 const wide = columns >= 50
159 const showHelp = help ?? (wide && g.moves === 0)
160
161 const status = g.over ? { text: 'No moves left. Score ' + g.score + '. Press n for a new game.', color: 'error', bold: true }
162 : g.won ? { text: 'You made ' + GOAL + '! Keep going for a higher tile, or n for a new game.', color: 'success', bold: true }
163 : g.moves === 0 ? { text: 'Slide with w, a, s, d. Equal tiles that touch merge.', color: 'suggestion' }
164 : { text: 'Score ' + g.score + (g.score > 0 && g.stats.best <= g.score ? ' · a new best' : ' · best ' + g.stats.best), color: 'suggestion' }
165
166 const header = Box({ flexDirection: 'column', children: [
167 Box({ flexDirection: 'row', columnGap: 2, flexWrap: 'wrap', children: [
168 Text({ bold: true, children: ['2048'] }),
169 Text({ children: ['score ', Text({ bold: true, children: [String(g.score)] })] }),
170 Text({ dimColor: true, children: ['best ' + g.stats.best + ' · highest ' + g.stats.highest + ' · move ' + g.moves] }),
171 ] }),
172 Text({ color: status.color, bold: status.bold, wrap: 'wrap', children: [status.text] }),
173 ] })
174
175 // Every tile is a fixed-size Box, three rows tall and seven wide, with the
176 // number centered, so the board is a grid of near-square tiles on any
177 // surface. An empty slot is a tile of the board's own color.
178 const tile = (r: number, c: number) => {
179 const v = g.cells[at(r, c)]
180 const [backgroundColor, color] = tileStyle(v)
181 return Box({ width: 7, height: 3, justifyContent: 'center', alignItems: 'center', backgroundColor, children: [Text({ bold: true, color, children: [v ? String(v) : ' '] })] })
182 }
183 const grid = Box({ flexDirection: 'column', rowGap: 1, children: Array.from({ length: SIZE }, (_, r) => Box({ flexDirection: 'row', columnGap: 1, children: Array.from({ length: SIZE }, (_, c) => tile(r, c)) })) })
184
185 const slideButton = (key: string, dir: Dir, label: string) =>
186 Button({ key, label, hotkey: key, plain: true, onPress: async () => {
187 let error: string | undefined
188 await change($, (cur) => {
189 const r = move(cur, dir)
190 error = r.error
191 return r.game
192 })
193 if (error) $.ui.toast(error)
194 } })
195 const controls = Box({ flexDirection: 'row', columnGap: 2, flexWrap: 'wrap', children: [
196 slideButton('w', 'up', 'Up'),
197 slideButton('a', 'left', 'Left'),
198 slideButton('s', 'down', 'Down'),
199 slideButton('d', 'right', 'Right'),
200 ] })
201
202 const howTo = Box({ flexDirection: 'column', borderStyle: 'round', borderColor: 'suggestion', paddingX: 1, children: [
203 Text({ bold: true, children: ['How to play'] }),
204 Text({ wrap: 'wrap', children: ['1. Press w, a, s or d: every tile slides that way as far as it can.'] }),
205 Text({ wrap: 'wrap', children: ['2. Two equal tiles that meet merge into one, and its value is added to your score. A new 2 (or 4) appears after each move.'] }),
206 Text({ wrap: 'wrap', children: ['3. Make a 2048 tile. The game ends when no slide changes the board. u takes a move back, up to ' + MAX_UNDO + '.'] }),
207 Text({ dimColor: true, wrap: 'wrap', children: ['Keys need the pane focused: click it if nothing happens. h hides this.'] }),
208 ] })
209
210 const footer = Box({ flexDirection: 'row', columnGap: 3, flexWrap: 'wrap', children: [
211 Button({ key: 'new', label: 'New game', hotkey: 'n', plain: true, onPress: () => startNew($) }),
212 Button({ key: 'undo', label: g.prev.length ? 'Undo (' + g.prev.length + ')' : 'Undo', hotkey: 'u', plain: true, onPress: async () => {
213 let error: string | undefined
214 await change($, (cur) => {
215 const r = undo(cur)
216 error = r.error
217 return r.game
218 })
219 if (error) $.ui.toast(error)
220 } }),
221 Button({ key: 'help', label: showHelp ? 'Hide help' : 'Help', hotkey: 'h', plain: true, dimColor: true, onPress: () => {
222 help = !showHelp
223 $.ui.invalidate('ui.render')
224 } }),
225 Text({ dimColor: true, children: ['Esc closes'] }),
226 ] })
227
228 return Box({ flexDirection: 'column', rowGap: 1, children: showHelp ? [header, grid, controls, howTo, footer] : [header, grid, controls, footer] })
229 })
230}
231hooks/game.ts 156 lines1// The rules of 2048, pure: no `$` here, so the tests and the hooks module
2// share one implementation.
3
4import type { Game, Stats } from '../types'
5
6export const SIZE = 4
7export const GOAL = 2048
8export type Dir = 'up' | 'down' | 'left' | 'right'
9export const DIRS: Dir[] = ['up', 'down', 'left', 'right']
10
11function hash(s: string): number {
12 let h = 2166136261
13 for (let i = 0; i < s.length; i++) {
14 h ^= s.charCodeAt(i)
15 h = Math.imul(h, 16777619)
16 }
17 return h >>> 0
18}
19
20function rng(seed: number): () => number {
21 let a = seed
22 return () => {
23 a = (a + 0x6d2b79f5) | 0
24 let t = Math.imul(a ^ (a >>> 15), 1 | a)
25 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
26 return ((t ^ (t >>> 14)) >>> 0) / 4294967296
27 }
28}
29
30export const at = (row: number, col: number) => row * SIZE + col
31
32// Drop a 2 (or, one time in ten, a 4) on an empty cell. Deterministic from the
33// seed and the spawn number, so a game replays the same way.
34export function spawn(cells: number[], seed: number, n: number): number[] {
35 const empty = cells.map((v, i) => (v ? -1 : i)).filter((i) => i >= 0)
36 if (!empty.length) return cells
37 const r = rng(hash(seed + ':spawn:' + n))
38 const i = empty[Math.floor(r() * empty.length)]
39 const out = cells.slice()
40 out[i] = r() < 0.1 ? 4 : 2
41 return out
42}
43
44// Slide one line toward index 0, merging each pair once; the points gained ride along.
45export function slideLine(line: number[]): { line: number[]; gained: number } {
46 const packed = line.filter(Boolean)
47 const out: number[] = []
48 let gained = 0
49 for (let i = 0; i < packed.length; i++) {
50 if (i + 1 < packed.length && packed[i] === packed[i + 1]) {
51 out.push(packed[i] * 2)
52 gained += packed[i] * 2
53 i++
54 } else out.push(packed[i])
55 }
56 while (out.length < SIZE) out.push(0)
57 return { line: out, gained }
58}
59
60// The cells of each line in the order they slide for `dir`: the leading cell first.
61function lines(dir: Dir): number[][] {
62 const out: number[][] = []
63 for (let k = 0; k < SIZE; k++) {
64 const idx = [0, 1, 2, 3]
65 if (dir === 'left') out.push(idx.map((i) => at(k, i)))
66 if (dir === 'right') out.push(idx.map((i) => at(k, SIZE - 1 - i)))
67 if (dir === 'up') out.push(idx.map((i) => at(i, k)))
68 if (dir === 'down') out.push(idx.map((i) => at(SIZE - 1 - i, k)))
69 }
70 return out
71}
72
73export function slide(cells: number[], dir: Dir): { cells: number[]; gained: number; moved: boolean } {
74 const out = cells.slice()
75 let gained = 0
76 let moved = false
77 for (const line of lines(dir)) {
78 const before = line.map((i) => cells[i])
79 const r = slideLine(before)
80 gained += r.gained
81 line.forEach((i, k) => {
82 if (out[i] !== r.line[k]) moved = true
83 out[i] = r.line[k]
84 })
85 }
86 return { cells: out, gained, moved }
87}
88
89export function canMove(cells: number[]): boolean {
90 return DIRS.some((d) => slide(cells, d).moved)
91}
92
93export function highestTile(cells: number[]): number {
94 return Math.max(0, ...cells)
95}
96
97/** Moves kept for undo; the oldest is dropped past this. */
98export const MAX_UNDO = 2
99
100export function newGame(seed: number, stats: Stats): Game {
101 let cells = new Array(SIZE * SIZE).fill(0)
102 cells = spawn(cells, seed, 0)
103 cells = spawn(cells, seed, 1)
104 return { seed, cells, score: 0, moves: 0, won: false, over: false, prev: [], stats }
105}
106
107export type MoveResult = { game: Game; error?: string }
108
109export function move(g: Game, dir: Dir): MoveResult {
110 if (!g.cells.length) return { game: g, error: 'No game yet.' }
111 if (g.over) return { game: g, error: 'No moves left. Press n for a new game.' }
112 const r = slide(g.cells, dir)
113 if (!r.moved) return { game: g, error: 'Nothing slides that way.' }
114 const moves = g.moves + 1
115 const cells = spawn(r.cells, g.seed, moves + 1)
116 const score = g.score + r.gained
117 const highest = highestTile(cells)
118 const over = !canMove(cells)
119 const stats: Stats = { ...g.stats, best: Math.max(g.stats.best, score), highest: Math.max(g.stats.highest, highest) }
120 return { game: { ...g, cells, score, moves, won: g.won || highest >= GOAL, over, prev: [...g.prev, { cells: g.cells, score: g.score, moves: g.moves, won: g.won }].slice(-MAX_UNDO), stats } }
121}
122
123export function undo(g: Game): MoveResult {
124 const last = g.prev[g.prev.length - 1]
125 if (!last) return { game: g, error: 'Nothing to take back.' }
126 return { game: { ...g, cells: last.cells, score: last.score, moves: last.moves, won: last.won, over: false, prev: g.prev.slice(0, -1) } }
127}
128
129/**
130 * Brings a saved game up to the current shape. Games saved before 0.2.0 kept a
131 * single undo in `prev`, as one snapshot or null; now it is a list. Anything
132 * else passes through unchanged for isGame to judge.
133 */
134export function migrate(x: unknown): unknown {
135 if (!x || typeof x !== 'object') return x
136 const g = x as Record<string, unknown>
137 if (g.prev === null) return { ...g, prev: [] }
138 if (!!g.prev && typeof g.prev === 'object' && !Array.isArray(g.prev)) return { ...g, prev: [g.prev] }
139 return x
140}
141
142export function isGame(x: unknown): x is Game {
143 if (!x || typeof x !== 'object') return false
144 const g = x as Record<string, unknown>
145 const board = (c: unknown) => Array.isArray(c) && c.length === SIZE * SIZE && c.every((v) => Number.isInteger(v) && v >= 0)
146 const stats = g.stats as Record<string, unknown> | undefined
147 const snapshot = (p: unknown) => {
148 const s = p as Record<string, unknown> | null
149 return !!s && typeof s === 'object' && board(s.cells) && Number.isInteger(s.score) && Number.isInteger(s.moves) && typeof s.won === 'boolean'
150 }
151 return typeof g.seed === 'number' && board(g.cells) && Number.isInteger(g.score) && Number.isInteger(g.moves) &&
152 typeof g.won === 'boolean' && typeof g.over === 'boolean' &&
153 Array.isArray(g.prev) && g.prev.every(snapshot) &&
154 !!stats && typeof stats === 'object' && ['games', 'best', 'highest'].every((k) => Number.isInteger(stats[k]))
155}
156types/index.d.ts 26 lines1export type Stats = { games: number; best: number; highest: number }
2/** The board as it stood before a move, so undo can put it back. */
3export type Snapshot = { cells: number[]; score: number; moves: number; won: boolean }
4export type Game = {
5 /** Seed of this game's tile spawns; 0 until a game exists. */
6 seed: number
7 /** 16 tiles in reading order; 0 is empty. */
8 cells: number[]
9 score: number
10 /** Moves that changed the board; also the spawn counter. */
11 moves: number
12 /** A 2048 tile has appeared; play goes on. */
13 won: boolean
14 /** No move changes the board. */
15 over: boolean
16 /** The game before each of the last moves, oldest first, for undo; at most MAX_UNDO. */
17 prev: Snapshot[]
18 stats: Stats
19}
20
21declare module 'claude-code' {
22 interface PluginState {
23 'game-2048': { game: Game }
24 }
25}
26