@my-games/2048-react 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,355 @@
1
+ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
2
+ import { Game2048 as Game2048$1, bestMove } from "@my-games/2048-core";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ // src/useGame.ts
5
+ function useGame(options = {}) {
6
+ const { aiDepth = 3, size, storage, saveKey, bestKey, freshStart, target, undoLimit, rng } = options;
7
+ const game = useMemo(() => new Game2048$1({
8
+ size,
9
+ storage,
10
+ saveKey,
11
+ bestKey,
12
+ freshStart,
13
+ target,
14
+ undoLimit,
15
+ rng
16
+ }), [
17
+ size,
18
+ saveKey,
19
+ bestKey,
20
+ target,
21
+ undoLimit
22
+ ]);
23
+ const gameRef = useRef(game);
24
+ gameRef.current = game;
25
+ const [state, setState] = useState(() => game.getState());
26
+ useEffect(() => {
27
+ setState(game.getState());
28
+ return game.subscribe((s) => setState(s));
29
+ }, [game]);
30
+ return {
31
+ state,
32
+ game,
33
+ move: (dir) => gameRef.current.move(dir),
34
+ newGame: () => gameRef.current.newGame(),
35
+ undo: () => gameRef.current.undo(),
36
+ continuePlaying: () => gameRef.current.continuePlaying(),
37
+ suggestMove: () => bestMove(gameRef.current.getGridValues(), { depth: aiDepth }),
38
+ aiMove: () => {
39
+ const dir = bestMove(gameRef.current.getGridValues(), { depth: aiDepth });
40
+ if (dir) gameRef.current.move(dir);
41
+ return dir;
42
+ }
43
+ };
44
+ }
45
+ // src/Game2048.tsx
46
+ var KEY_TO_DIR = {
47
+ ArrowUp: "up",
48
+ ArrowDown: "down",
49
+ ArrowLeft: "left",
50
+ ArrowRight: "right",
51
+ w: "up",
52
+ a: "left",
53
+ s: "down",
54
+ d: "right",
55
+ W: "up",
56
+ A: "left",
57
+ S: "down",
58
+ D: "right"
59
+ };
60
+ function cssVars(vars) {
61
+ return vars;
62
+ }
63
+ function Game2048Inner(props, ref) {
64
+ const { size = 4, storage, saveKey, bestKey, freshStart = false, autofocus = true, enableAI = false, aiDepth = 3, title = "2048", onMove, onWon, onLost, className } = props;
65
+ const { state, move, newGame, undo, continuePlaying, suggestMove, aiMove } = useGame({
66
+ size,
67
+ storage,
68
+ saveKey,
69
+ bestKey,
70
+ freshStart,
71
+ aiDepth
72
+ });
73
+ const boardRef = useRef(null);
74
+ const touchStartPoint = useRef(null);
75
+ const lastScoreRef = useRef(state.score);
76
+ const lastStatusRef = useRef(state.status);
77
+ const [scoreDelta, setScoreDelta] = useState(null);
78
+ const [aiHint, setAiHint] = useState(null);
79
+ const deltaTimer = useRef(void 0);
80
+ const performMove = useCallback((dir) => {
81
+ const before = lastScoreRef.current;
82
+ if (move(dir)) {
83
+ onMove?.(dir, state.score - before);
84
+ if (enableAI) setAiHint(null);
85
+ }
86
+ }, [
87
+ move,
88
+ onMove,
89
+ state.score,
90
+ enableAI
91
+ ]);
92
+ useEffect(() => {
93
+ const handler = (ev) => {
94
+ const dir = KEY_TO_DIR[ev.key];
95
+ if (!dir) return;
96
+ if (document.activeElement !== boardRef.current) return;
97
+ ev.preventDefault();
98
+ performMove(dir);
99
+ };
100
+ window.addEventListener("keydown", handler, { passive: false });
101
+ return () => window.removeEventListener("keydown", handler);
102
+ }, [performMove]);
103
+ useEffect(() => {
104
+ if (autofocus) boardRef.current?.focus({ preventScroll: true });
105
+ }, [autofocus]);
106
+ const onTouchStart = (ev) => {
107
+ if (ev.touches.length !== 1) return;
108
+ const t = ev.touches[0];
109
+ if (!t) return;
110
+ touchStartPoint.current = {
111
+ x: t.clientX,
112
+ y: t.clientY
113
+ };
114
+ boardRef.current?.focus({ preventScroll: true });
115
+ };
116
+ const onTouchEnd = (ev) => {
117
+ const start = touchStartPoint.current;
118
+ touchStartPoint.current = null;
119
+ if (!start) return;
120
+ const t = ev.changedTouches[0];
121
+ if (!t) return;
122
+ const dx = t.clientX - start.x;
123
+ const dy = t.clientY - start.y;
124
+ const adx = Math.abs(dx);
125
+ const ady = Math.abs(dy);
126
+ if (Math.max(adx, ady) < 24) return;
127
+ performMove(adx > ady ? dx > 0 ? "right" : "left" : dy > 0 ? "down" : "up");
128
+ };
129
+ useEffect(() => {
130
+ const gained = state.score - lastScoreRef.current;
131
+ if (gained > 0) {
132
+ setScoreDelta({
133
+ amount: gained,
134
+ key: Date.now() + Math.random()
135
+ });
136
+ if (deltaTimer.current) window.clearTimeout(deltaTimer.current);
137
+ deltaTimer.current = window.setTimeout(() => setScoreDelta(null), 700);
138
+ }
139
+ lastScoreRef.current = state.score;
140
+ }, [state.score]);
141
+ useEffect(() => {
142
+ if (state.status === lastStatusRef.current) return;
143
+ if (state.status === "won") onWon?.();
144
+ else if (state.status === "lost") onLost?.();
145
+ lastStatusRef.current = state.status;
146
+ }, [
147
+ state.status,
148
+ onWon,
149
+ onLost
150
+ ]);
151
+ useEffect(() => () => {
152
+ if (deltaTimer.current) window.clearTimeout(deltaTimer.current);
153
+ }, []);
154
+ const gridStyle = useMemo(() => cssVars({
155
+ gridTemplateColumns: `repeat(${state.size}, 1fr)`,
156
+ gridTemplateRows: `repeat(${state.size}, 1fr)`
157
+ }), [state.size]);
158
+ const boardVars = useMemo(() => cssVars({ "--cols": state.size }), [state.size]);
159
+ const undoDisabled = state.historySize === 0;
160
+ const overlayVisible = state.status !== "playing";
161
+ const isWon = state.status === "won";
162
+ const isLost = state.status === "lost";
163
+ useImperativeHandle(ref, () => ({
164
+ suggestMove,
165
+ aiMove,
166
+ newGame,
167
+ undo,
168
+ move,
169
+ continuePlaying
170
+ }), [
171
+ suggestMove,
172
+ aiMove,
173
+ newGame,
174
+ undo,
175
+ move,
176
+ continuePlaying
177
+ ]);
178
+ return /* @__PURE__ */ jsxs("div", {
179
+ className: ["game-2048", className].filter(Boolean).join(" "),
180
+ children: [
181
+ title ? /* @__PURE__ */ jsxs("header", {
182
+ className: "game-2048-header",
183
+ children: [/* @__PURE__ */ jsx("h1", {
184
+ className: "game-2048-title",
185
+ children: title
186
+ }), /* @__PURE__ */ jsxs("div", {
187
+ className: "game-2048-scores",
188
+ children: [/* @__PURE__ */ jsxs("div", {
189
+ className: "game-2048-score-box",
190
+ children: [
191
+ /* @__PURE__ */ jsx("span", {
192
+ className: "label",
193
+ children: "Score"
194
+ }),
195
+ /* @__PURE__ */ jsx("span", {
196
+ className: "value",
197
+ children: state.score
198
+ }),
199
+ scoreDelta ? /* @__PURE__ */ jsxs("span", {
200
+ className: "delta",
201
+ children: ["+", scoreDelta.amount]
202
+ }, scoreDelta.key) : null
203
+ ]
204
+ }), /* @__PURE__ */ jsxs("div", {
205
+ className: "game-2048-score-box",
206
+ children: [/* @__PURE__ */ jsx("span", {
207
+ className: "label",
208
+ children: "Best"
209
+ }), /* @__PURE__ */ jsx("span", {
210
+ className: "value",
211
+ children: state.bestScore
212
+ })]
213
+ })]
214
+ })]
215
+ }) : null,
216
+ /* @__PURE__ */ jsxs("div", {
217
+ className: "game-2048-toolbar",
218
+ children: [/* @__PURE__ */ jsxs("p", {
219
+ className: "game-2048-desc",
220
+ children: [
221
+ "合并相同数字,冲过 ",
222
+ /* @__PURE__ */ jsx("b", { children: "2048" }),
223
+ "。方向键 / WASD / 触屏滑动。"
224
+ ]
225
+ }), /* @__PURE__ */ jsxs("div", {
226
+ className: "game-2048-actions",
227
+ children: [
228
+ enableAI ? /* @__PURE__ */ jsx("button", {
229
+ className: "game-2048-button",
230
+ type: "button",
231
+ disabled: isLost,
232
+ onClick: () => setAiHint(suggestMove()),
233
+ children: "提示"
234
+ }) : null,
235
+ enableAI ? /* @__PURE__ */ jsx("button", {
236
+ className: "game-2048-button",
237
+ type: "button",
238
+ disabled: isLost,
239
+ onClick: () => {
240
+ const before = state.score;
241
+ const dir = aiMove();
242
+ if (dir) {
243
+ onMove?.(dir, state.score - before);
244
+ setAiHint(null);
245
+ }
246
+ },
247
+ children: "AI 帮走"
248
+ }) : null,
249
+ /* @__PURE__ */ jsx("button", {
250
+ className: "game-2048-button",
251
+ type: "button",
252
+ disabled: undoDisabled,
253
+ onClick: () => undo(),
254
+ children: "撤销"
255
+ }),
256
+ /* @__PURE__ */ jsx("button", {
257
+ className: "game-2048-button is-primary",
258
+ type: "button",
259
+ onClick: () => newGame(),
260
+ children: "新游戏"
261
+ })
262
+ ]
263
+ })]
264
+ }),
265
+ /* @__PURE__ */ jsxs("div", {
266
+ ref: boardRef,
267
+ className: "game-2048-board",
268
+ style: boardVars,
269
+ tabIndex: 0,
270
+ role: "application",
271
+ "aria-label": `2048 游戏板 ${state.status}`,
272
+ onTouchStart,
273
+ onTouchEnd,
274
+ children: [
275
+ /* @__PURE__ */ jsx("div", {
276
+ className: "game-2048-grid",
277
+ style: gridStyle,
278
+ children: Array.from({ length: state.size * state.size }).map((_, i) => /* @__PURE__ */ jsx("div", { className: "game-2048-cell" }, i))
279
+ }),
280
+ /* @__PURE__ */ jsx("div", {
281
+ className: "game-2048-tile-layer",
282
+ children: state.tiles.map((t) => {
283
+ const cls = [
284
+ "game-2048-tile",
285
+ t.isNew ? "is-new" : "",
286
+ t.merged ? "is-merged" : "",
287
+ t.value > 2048 ? "is-super" : ""
288
+ ].filter(Boolean).join(" ");
289
+ return /* @__PURE__ */ jsx("div", {
290
+ className: cls,
291
+ style: cssVars({
292
+ "--row": t.row,
293
+ "--col": t.col
294
+ }),
295
+ "data-value": t.value,
296
+ ...t.value > 2048 ? { "data-super": "1" } : {},
297
+ children: t.value
298
+ }, t.id);
299
+ })
300
+ }),
301
+ enableAI && aiHint ? /* @__PURE__ */ jsxs("div", {
302
+ className: "game-2048-ai-indicator",
303
+ style: cssVars({
304
+ position: "absolute",
305
+ top: "8px",
306
+ left: "8px",
307
+ zIndex: 3
308
+ }),
309
+ children: ["推荐:", aiHint]
310
+ }) : null,
311
+ /* @__PURE__ */ jsxs("div", {
312
+ className: [
313
+ "game-2048-overlay",
314
+ overlayVisible ? "is-visible" : "",
315
+ isWon ? "is-won" : "",
316
+ isLost ? "is-lost" : ""
317
+ ].filter(Boolean).join(" "),
318
+ children: [
319
+ isWon ? /* @__PURE__ */ jsx("h2", { children: "你赢了!" }) : null,
320
+ isLost ? /* @__PURE__ */ jsx("h2", { children: "游戏结束" }) : null,
321
+ /* @__PURE__ */ jsxs("div", {
322
+ className: "row",
323
+ children: [
324
+ isWon ? /* @__PURE__ */ jsx("button", {
325
+ className: "game-2048-button",
326
+ type: "button",
327
+ onClick: () => continuePlaying(),
328
+ children: "继续游戏"
329
+ }) : null,
330
+ isLost && !undoDisabled ? /* @__PURE__ */ jsx("button", {
331
+ className: "game-2048-button",
332
+ type: "button",
333
+ onClick: () => undo(),
334
+ children: "悔一步"
335
+ }) : null,
336
+ overlayVisible ? /* @__PURE__ */ jsx("button", {
337
+ className: "game-2048-button is-primary",
338
+ type: "button",
339
+ onClick: () => newGame(),
340
+ children: "再来一局"
341
+ }) : null
342
+ ]
343
+ })
344
+ ]
345
+ })
346
+ ]
347
+ })
348
+ ]
349
+ });
350
+ }
351
+ var Game2048 = forwardRef(Game2048Inner);
352
+ Game2048.displayName = "Game2048";
353
+ export { Game2048, useGame };
354
+
355
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["Game2048","aiBestMove"],"sources":["../src/useGame.ts","../src/Game2048.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\nimport {\n bestMove as aiBestMove,\n Game2048,\n type Direction,\n type GameOptions,\n type GameState\n} from '@my-games/2048-core';\n\n/**\n * `useGame` —— React Hook 版引擎桥接。\n *\n * - 引擎实例在 `useMemo` 里按 `size`/`saveKey` 等关键 prop 缓存,避免每次 render\n * 重新构造;这些 prop 变化 = 重开一局,视为预期语义。\n * - `useState` 订阅引擎快照;`useEffect` 里挂 unsubscribe 防泄漏。\n * - 用 `useRef` 保留最新 game 实例给 imperative handler(move / undo)用,\n * 防止闭包过期。\n */\nexport interface UseGameOptions extends GameOptions {\n aiDepth?: number;\n}\n\nexport interface UseGameReturn {\n state: GameState;\n game: Game2048;\n move: (dir: Direction) => boolean;\n newGame: () => void;\n undo: () => boolean;\n continuePlaying: () => void;\n suggestMove: () => Direction | null;\n aiMove: () => Direction | null;\n}\n\nexport function useGame(options: UseGameOptions = {}): UseGameReturn {\n const { aiDepth = 3, size, storage, saveKey, bestKey, freshStart, target, undoLimit, rng } = options;\n\n // useMemo 依赖里不放 rng / storage(函数/对象引用不稳定;重开一次即可)\n const game = useMemo(\n () => new Game2048({ size, storage, saveKey, bestKey, freshStart, target, undoLimit, rng }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [size, saveKey, bestKey, target, undoLimit]\n );\n\n const gameRef = useRef(game);\n gameRef.current = game;\n\n const [state, setState] = useState<GameState>(() => game.getState());\n\n useEffect(() => {\n // 引擎替换时重新订阅;先把 state 拉齐到最新,防止首帧错位\n setState(game.getState());\n const unsub = game.subscribe((s) => setState(s));\n return unsub;\n }, [game]);\n\n return {\n state,\n game,\n move: (dir) => gameRef.current.move(dir),\n newGame: () => gameRef.current.newGame(),\n undo: () => gameRef.current.undo(),\n continuePlaying: () => gameRef.current.continuePlaying(),\n suggestMove: () => aiBestMove(gameRef.current.getGridValues(), { depth: aiDepth }),\n aiMove: () => {\n const dir = aiBestMove(gameRef.current.getGridValues(), { depth: aiDepth });\n if (dir) gameRef.current.move(dir);\n return dir;\n }\n };\n}\n","import {\n type CSSProperties,\n type Ref,\n type TouchEvent as ReactTouchEvent,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState\n} from 'react';\nimport '@my-games/2048-core/styles.css';\nimport type { Direction, SaveStorage } from '@my-games/2048-core';\nimport { useGame } from './useGame';\n\n/**\n * Game2048 —— React 18 组件。与 Vue 版行为对齐:\n * - 键盘:window keydown + 严格 focus 判定(多实例并存只活动那个响应);\n * 方向键 / WASD。\n * - 触摸:单指 swipe 主导轴 ≥24px;touchstart 时把焦点抢过来。\n * - 动画:新块 / 合并 / 位移全走 core 的 styles.css。\n * - AI:`enableAI` prop 控制按钮渲染;通过 ref 一直可以命令式访问。\n */\n\nexport interface Game2048Props {\n size?: 3 | 4 | 5 | 6;\n storage?: SaveStorage | null;\n saveKey?: string;\n bestKey?: string;\n freshStart?: boolean;\n autofocus?: boolean;\n enableAI?: boolean;\n aiDepth?: number;\n title?: string;\n onMove?: (dir: Direction, gained: number) => void;\n onWon?: () => void;\n onLost?: () => void;\n className?: string;\n}\n\nexport interface Game2048Handle {\n suggestMove(): Direction | null;\n aiMove(): Direction | null;\n newGame(): void;\n undo(): boolean;\n move(dir: Direction): boolean;\n continuePlaying(): void;\n}\n\nconst KEY_TO_DIR: Record<string, Direction> = {\n ArrowUp: 'up',\n ArrowDown: 'down',\n ArrowLeft: 'left',\n ArrowRight: 'right',\n w: 'up',\n a: 'left',\n s: 'down',\n d: 'right',\n W: 'up',\n A: 'left',\n S: 'down',\n D: 'right'\n};\n\nfunction cssVars(vars: Record<string, string | number>): CSSProperties {\n return vars as CSSProperties;\n}\n\nfunction Game2048Inner(props: Game2048Props, ref: Ref<Game2048Handle>) {\n const {\n size = 4,\n storage,\n saveKey,\n bestKey,\n freshStart = false,\n autofocus = true,\n enableAI = false,\n aiDepth = 3,\n title = '2048',\n onMove,\n onWon,\n onLost,\n className\n } = props;\n\n const { state, move, newGame, undo, continuePlaying, suggestMove, aiMove } = useGame({\n size,\n storage,\n saveKey,\n bestKey,\n freshStart,\n aiDepth\n });\n\n const boardRef = useRef<HTMLDivElement>(null);\n const touchStartPoint = useRef<{ x: number; y: number } | null>(null);\n const lastScoreRef = useRef(state.score);\n const lastStatusRef = useRef(state.status);\n\n const [scoreDelta, setScoreDelta] = useState<{ amount: number; key: number } | null>(null);\n const [aiHint, setAiHint] = useState<Direction | null>(null);\n const deltaTimer = useRef<number | undefined>(undefined);\n\n // --- 键盘 ---\n const performMove = useCallback(\n (dir: Direction) => {\n const before = lastScoreRef.current;\n const ok = move(dir);\n if (ok) {\n onMove?.(dir, state.score - before);\n if (enableAI) setAiHint(null);\n }\n },\n [move, onMove, state.score, enableAI]\n );\n\n useEffect(() => {\n const handler = (ev: KeyboardEvent) => {\n const dir = KEY_TO_DIR[ev.key];\n if (!dir) return;\n // 只有本实例 board 有 DOM 焦点时才响应\n if (document.activeElement !== boardRef.current) return;\n ev.preventDefault();\n performMove(dir);\n };\n window.addEventListener('keydown', handler, { passive: false });\n return () => window.removeEventListener('keydown', handler);\n }, [performMove]);\n\n useEffect(() => {\n if (autofocus) boardRef.current?.focus({ preventScroll: true });\n }, [autofocus]);\n\n // --- 触摸 ---\n const onTouchStart = (ev: ReactTouchEvent<HTMLDivElement>) => {\n if (ev.touches.length !== 1) return;\n const t = ev.touches[0];\n if (!t) return;\n touchStartPoint.current = { x: t.clientX, y: t.clientY };\n boardRef.current?.focus({ preventScroll: true });\n };\n const onTouchEnd = (ev: ReactTouchEvent<HTMLDivElement>) => {\n const start = touchStartPoint.current;\n touchStartPoint.current = null;\n if (!start) return;\n const t = ev.changedTouches[0];\n if (!t) return;\n const dx = t.clientX - start.x;\n const dy = t.clientY - start.y;\n const adx = Math.abs(dx);\n const ady = Math.abs(dy);\n if (Math.max(adx, ady) < 24) return;\n const dir: Direction = adx > ady ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up';\n performMove(dir);\n };\n\n // --- 分数 delta 与状态副作用 ---\n useEffect(() => {\n const gained = state.score - lastScoreRef.current;\n if (gained > 0) {\n setScoreDelta({ amount: gained, key: Date.now() + Math.random() });\n if (deltaTimer.current) window.clearTimeout(deltaTimer.current);\n deltaTimer.current = window.setTimeout(() => setScoreDelta(null), 700);\n }\n lastScoreRef.current = state.score;\n }, [state.score]);\n\n useEffect(() => {\n if (state.status === lastStatusRef.current) return;\n if (state.status === 'won') onWon?.();\n else if (state.status === 'lost') onLost?.();\n lastStatusRef.current = state.status;\n }, [state.status, onWon, onLost]);\n\n useEffect(\n () => () => {\n if (deltaTimer.current) window.clearTimeout(deltaTimer.current);\n },\n []\n );\n\n // --- 渲染派生 ---\n const gridStyle = useMemo(\n () =>\n cssVars({\n gridTemplateColumns: `repeat(${state.size}, 1fr)`,\n gridTemplateRows: `repeat(${state.size}, 1fr)`\n }),\n [state.size]\n );\n const boardVars = useMemo(() => cssVars({ '--cols': state.size }), [state.size]);\n const undoDisabled = state.historySize === 0;\n const overlayVisible = state.status !== 'playing';\n const isWon = state.status === 'won';\n const isLost = state.status === 'lost';\n\n useImperativeHandle(\n ref,\n () => ({\n suggestMove,\n aiMove,\n newGame,\n undo,\n move,\n continuePlaying\n }),\n [suggestMove, aiMove, newGame, undo, move, continuePlaying]\n );\n\n return (\n <div className={['game-2048', className].filter(Boolean).join(' ')}>\n {title ? (\n <header className=\"game-2048-header\">\n <h1 className=\"game-2048-title\">{title}</h1>\n <div className=\"game-2048-scores\">\n <div className=\"game-2048-score-box\">\n <span className=\"label\">Score</span>\n <span className=\"value\">{state.score}</span>\n {scoreDelta ? (\n <span key={scoreDelta.key} className=\"delta\">\n +{scoreDelta.amount}\n </span>\n ) : null}\n </div>\n <div className=\"game-2048-score-box\">\n <span className=\"label\">Best</span>\n <span className=\"value\">{state.bestScore}</span>\n </div>\n </div>\n </header>\n ) : null}\n\n <div className=\"game-2048-toolbar\">\n <p className=\"game-2048-desc\">\n 合并相同数字,冲过 <b>2048</b>。方向键 / WASD / 触屏滑动。\n </p>\n <div className=\"game-2048-actions\">\n {enableAI ? (\n <button\n className=\"game-2048-button\"\n type=\"button\"\n disabled={isLost}\n onClick={() => setAiHint(suggestMove())}\n >\n 提示\n </button>\n ) : null}\n {enableAI ? (\n <button\n className=\"game-2048-button\"\n type=\"button\"\n disabled={isLost}\n onClick={() => {\n const before = state.score;\n const dir = aiMove();\n if (dir) {\n onMove?.(dir, state.score - before);\n setAiHint(null);\n }\n }}\n >\n AI 帮走\n </button>\n ) : null}\n <button\n className=\"game-2048-button\"\n type=\"button\"\n disabled={undoDisabled}\n onClick={() => undo()}\n >\n 撤销\n </button>\n <button\n className=\"game-2048-button is-primary\"\n type=\"button\"\n onClick={() => newGame()}\n >\n 新游戏\n </button>\n </div>\n </div>\n\n <div\n ref={boardRef}\n className=\"game-2048-board\"\n style={boardVars}\n tabIndex={0}\n role=\"application\"\n aria-label={`2048 游戏板 ${state.status}`}\n onTouchStart={onTouchStart}\n onTouchEnd={onTouchEnd}\n >\n <div className=\"game-2048-grid\" style={gridStyle}>\n {Array.from({ length: state.size * state.size }).map((_, i) => (\n <div key={i} className=\"game-2048-cell\" />\n ))}\n </div>\n <div className=\"game-2048-tile-layer\">\n {state.tiles.map((t) => {\n const cls = [\n 'game-2048-tile',\n t.isNew ? 'is-new' : '',\n t.merged ? 'is-merged' : '',\n t.value > 2048 ? 'is-super' : ''\n ]\n .filter(Boolean)\n .join(' ');\n return (\n <div\n key={t.id}\n className={cls}\n style={cssVars({ '--row': t.row, '--col': t.col })}\n data-value={t.value}\n {...(t.value > 2048 ? { 'data-super': '1' } : {})}\n >\n {t.value}\n </div>\n );\n })}\n </div>\n\n {enableAI && aiHint ? (\n <div\n className=\"game-2048-ai-indicator\"\n style={cssVars({ position: 'absolute', top: '8px', left: '8px', zIndex: 3 })}\n >\n 推荐:{aiHint}\n </div>\n ) : null}\n\n <div\n className={[\n 'game-2048-overlay',\n overlayVisible ? 'is-visible' : '',\n isWon ? 'is-won' : '',\n isLost ? 'is-lost' : ''\n ]\n .filter(Boolean)\n .join(' ')}\n >\n {isWon ? <h2>你赢了!</h2> : null}\n {isLost ? <h2>游戏结束</h2> : null}\n <div className=\"row\">\n {isWon ? (\n <button\n className=\"game-2048-button\"\n type=\"button\"\n onClick={() => continuePlaying()}\n >\n 继续游戏\n </button>\n ) : null}\n {isLost && !undoDisabled ? (\n <button\n className=\"game-2048-button\"\n type=\"button\"\n onClick={() => undo()}\n >\n 悔一步\n </button>\n ) : null}\n {overlayVisible ? (\n <button\n className=\"game-2048-button is-primary\"\n type=\"button\"\n onClick={() => newGame()}\n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f,KAAK,GAAG;OACX,OACE,oBAAC,OAAD;QAEE,WAAW;QACX,OAAO,QAAQ;SAAE,SAAS,EAAE;SAAK,SAAS,EAAE;QAAI,CAAC;QACjD,cAAY,EAAE;QACd,GAAK,EAAE,QAAQ,OAAO,EAAE,cAAc,IAAI,IAAI,CAAC;QAE9C,UAAA,EAAE;OACA,GAPE,EAAE,EAOJ;MAET,CAAC;KACE,CAAA;KAEJ,YAAY,SACX,qBAAC,OAAD;MACE,WAAU;MACV,OAAO,QAAQ;OAAE,UAAU;OAAY,KAAK;OAAO,MAAM;OAAO,QAAQ;MAAE,CAAC;MAF7E,UAAA,CAGC,OACK,MACD;KACH,CAAA,IAAA;KAEJ,qBAAC,OAAD;MACE,WAAW;OACT;OACA,iBAAiB,eAAe;OAChC,QAAQ,WAAW;OACnB,SAAS,YAAY;MACvB,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;MARb,UAAA;OAUG,QAAQ,oBAAC,MAAD,EAAA,UAAI,OAAQ,CAAA,IAAI;OACxB,SAAS,oBAAC,MAAD,EAAA,UAAI,OAAQ,CAAA,IAAI;OAC1B,qBAAC,OAAD;QAAK,WAAU;QAAf,UAAA;SACG,QACC,oBAAC,UAAD;UACE,WAAU;UACV,MAAK;UACL,eAAe,gBAAgB;UAChC,UAAA;SAEO,CAAA,IACN;SACH,UAAU,CAAC,eACV,oBAAC,UAAD;UACE,WAAU;UACV,MAAK;UACL,eAAe,KAAK;UACrB,UAAA;SAEO,CAAA,IACN;SACH,iBACC,oBAAC,UAAD;UACE,WAAU;UACV,MAAK;UACL,eAAe,QAAQ;UACxB,UAAA;SAEO,CAAA,IACN;QACD;;MACF;;IACF;;EACF;;AAET;AAEA,IAAa,WAAW,WAAW,aAAa;AAChD,SAAS,cAAc"}
@@ -0,0 +1,25 @@
1
+ import { Game2048, Direction, GameOptions, GameState } from '@my-games/2048-core';
2
+ /**
3
+ * `useGame` —— React Hook 版引擎桥接。
4
+ *
5
+ * - 引擎实例在 `useMemo` 里按 `size`/`saveKey` 等关键 prop 缓存,避免每次 render
6
+ * 重新构造;这些 prop 变化 = 重开一局,视为预期语义。
7
+ * - `useState` 订阅引擎快照;`useEffect` 里挂 unsubscribe 防泄漏。
8
+ * - 用 `useRef` 保留最新 game 实例给 imperative handler(move / undo)用,
9
+ * 防止闭包过期。
10
+ */
11
+ export interface UseGameOptions extends GameOptions {
12
+ aiDepth?: number;
13
+ }
14
+ export interface UseGameReturn {
15
+ state: GameState;
16
+ game: Game2048;
17
+ move: (dir: Direction) => boolean;
18
+ newGame: () => void;
19
+ undo: () => boolean;
20
+ continuePlaying: () => void;
21
+ suggestMove: () => Direction | null;
22
+ aiMove: () => Direction | null;
23
+ }
24
+ export declare function useGame(options?: UseGameOptions): UseGameReturn;
25
+ //# sourceMappingURL=useGame.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGame.d.ts","sourceRoot":"","sources":["../src/useGame.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,QAAQ,EACR,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,SAAS,EACf,MAAM,qBAAqB,CAAC;AAE7B;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAe,SAAQ,WAAW;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,SAAS,CAAC;IACjB,IAAI,EAAE,QAAQ,CAAC;IACf,IAAI,EAAE,CAAC,GAAG,EAAE,SAAS,KAAK,OAAO,CAAC;IAClC,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,IAAI,EAAE,MAAM,OAAO,CAAC;IACpB,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,WAAW,EAAE,MAAM,SAAS,GAAG,IAAI,CAAC;IACpC,MAAM,EAAE,MAAM,SAAS,GAAG,IAAI,CAAC;CAChC;AAED,wBAAgB,OAAO,CAAC,OAAO,GAAE,cAAmB,GAAG,aAAa,CAoCnE"}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@my-games/2048-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "2048 游戏的 React 18/19 组件适配器(函数组件 + Hooks + forwardRef)。",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./style.css": "./dist/index.css",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "src",
20
+ "README.md"
21
+ ],
22
+ "sideEffects": false,
23
+ "peerDependencies": {
24
+ "react": "^18.2.0 || ^19.0.0",
25
+ "react-dom": "^18.2.0 || ^19.0.0"
26
+ },
27
+ "dependencies": {
28
+ "@my-games/2048-core": "0.2.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/react": "^19.3.0",
32
+ "@types/react-dom": "^19.3.0",
33
+ "@vitejs/plugin-react": "^6.1.2",
34
+ "react": "^19.3.1",
35
+ "react-dom": "^19.3.1",
36
+ "typescript": "^7.0.2",
37
+ "vite": "^8.3.5",
38
+ "vite-plugin-dts": "^5.1.2"
39
+ },
40
+ "keywords": [
41
+ "2048",
42
+ "react",
43
+ "react18",
44
+ "react19",
45
+ "game",
46
+ "puzzle",
47
+ "component",
48
+ "hooks"
49
+ ],
50
+ "license": "MIT",
51
+ "author": {
52
+ "name": "xyj2156"
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/my-gam/2048.git",
57
+ "directory": "packages/react"
58
+ },
59
+ "homepage": "https://github.com/my-gam/2048/tree/main/packages/react#readme",
60
+ "bugs": {
61
+ "url": "https://github.com/my-gam/2048/issues"
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ },
66
+ "scripts": {
67
+ "build": "vite build --mode lib",
68
+ "dev": "vite build --mode lib --watch",
69
+ "typecheck": "tsc --noEmit -p tsconfig.json"
70
+ }
6
71
  }