@my-games/2048-react 0.1.0 → 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/README.md CHANGED
@@ -12,6 +12,7 @@ pnpm add @my-games/2048-react react react-dom
12
12
 
13
13
  ```tsx
14
14
  import { Game2048 } from '@my-games/2048-react';
15
+ import '@my-games/2048-react/style.css';
15
16
 
16
17
  export function Demo() {
17
18
  return (
@@ -27,7 +28,9 @@ export function Demo() {
27
28
  }
28
29
  ```
29
30
 
30
- 组件样式已经内嵌(`import '@my-games/2048-core/styles.css'`),不用额外引 CSS。
31
+ **样式必须显式引入**:vite lib 模式把内部 CSS import 抽到 `dist/index.css`,
32
+ JS bundle 不再引用。消费者入口加一次 `import '@my-games/2048-react/style.css'`
33
+ (或从 core 引 `import '@my-games/2048-core/styles.css'`,内容一致)。
31
34
 
32
35
  ## Props
33
36
 
@@ -1,5 +1,4 @@
1
- import '@my-games/2048-core/styles.css';
2
- import type { Direction, SaveStorage } from '@my-games/2048-core';
1
+ import { Direction, SaveStorage } from '@my-games/2048-core';
3
2
  /**
4
3
  * Game2048 —— React 18 组件。与 Vue 版行为对齐:
5
4
  * - 键盘:window keydown + 严格 focus 判定(多实例并存只活动那个响应);
@@ -31,5 +30,5 @@ export interface Game2048Handle {
31
30
  move(dir: Direction): boolean;
32
31
  continuePlaying(): void;
33
32
  }
34
- export declare const Game2048: import("react").ForwardRefExoticComponent<Game2048Props & import("react").RefAttributes<Game2048Handle>>;
33
+ export declare const Game2048: import('react').ForwardRefExoticComponent<Game2048Props & import('react').RefAttributes<Game2048Handle>>;
35
34
  //# sourceMappingURL=Game2048.d.ts.map
package/dist/index.css ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * game-2048 通用样式表。
3
+ *
4
+ * 由 `@my-games/2048-core/styles.css` 暴露,Vue / React 适配器都直接 import 这一份,
5
+ * 保持视觉一致(避免两包各自漂移)。
6
+ *
7
+ * 关键约定:
8
+ * - 棋盘外圈 .game-2048-board 承担 pointer 事件(触摸/鼠标),内部 .tile 全部 pointer-events:none
9
+ * 防止子元素吞掉滑动检测。
10
+ * - Tile 定位用 translate,row/col 通过 --row / --col CSS 变量注入到 style 里;
11
+ * `transition: transform 120ms` 让滑动有平滑感,scale 关键帧负责新块与合并 pop。
12
+ * - 尺寸自适应:容器宽度决定一切;cell 与 gap 用比例 + clamp() 缩放,
13
+ * 最小 320px、最大 520px 之间保持视觉合理。
14
+ */
15
+
16
+ .game-2048 {
17
+ --board-size: min(90vw, 520px);
18
+ --gap: clamp(6px, 2.5vw, 12px);
19
+ --radius: clamp(4px, 1.2vw, 8px);
20
+ --bg-board: #bbada0;
21
+ --bg-empty: rgba(238, 228, 218, 0.35);
22
+ --text-dark: #776e65;
23
+ --text-light: #f9f6f2;
24
+ --accent: #8f7a66;
25
+
26
+ display: inline-flex;
27
+ flex-direction: column;
28
+ gap: var(--gap);
29
+ font-family: 'Helvetica Neue', 'Segoe UI', system-ui, -apple-system, sans-serif;
30
+ color: var(--text-dark);
31
+ user-select: none;
32
+ -webkit-tap-highlight-color: transparent;
33
+ }
34
+
35
+ .game-2048-header {
36
+ display: flex;
37
+ align-items: center;
38
+ justify-content: space-between;
39
+ gap: var(--gap);
40
+ width: var(--board-size);
41
+ max-width: 90vw;
42
+ }
43
+
44
+ .game-2048-title {
45
+ margin: 0;
46
+ font-size: clamp(28px, 8vw, 44px);
47
+ font-weight: 800;
48
+ letter-spacing: -1px;
49
+ color: var(--text-dark);
50
+ }
51
+
52
+ .game-2048-scores {
53
+ display: flex;
54
+ gap: 6px;
55
+ }
56
+
57
+ .game-2048-score-box {
58
+ position: relative;
59
+ min-width: 74px;
60
+ padding: 6px 12px 8px;
61
+ border-radius: var(--radius);
62
+ background: var(--bg-board);
63
+ color: var(--text-light);
64
+ text-align: center;
65
+ font-variant-numeric: tabular-nums;
66
+ }
67
+
68
+ .game-2048-score-box .label {
69
+ display: block;
70
+ font-size: 11px;
71
+ letter-spacing: 1px;
72
+ color: #eee4da;
73
+ text-transform: uppercase;
74
+ }
75
+
76
+ .game-2048-score-box .value {
77
+ display: block;
78
+ font-size: 22px;
79
+ font-weight: 700;
80
+ line-height: 1.2;
81
+ }
82
+
83
+ .game-2048-score-box .delta {
84
+ position: absolute;
85
+ top: 4px;
86
+ right: 8px;
87
+ color: rgba(119, 110, 101, 1);
88
+ font-weight: 700;
89
+ font-size: 14px;
90
+ animation: game-2048-score-pop 700ms ease-out forwards;
91
+ pointer-events: none;
92
+ }
93
+
94
+ @keyframes game-2048-score-pop {
95
+ 0% { opacity: 1; transform: translateY(0); }
96
+ 100% { opacity: 0; transform: translateY(-24px); }
97
+ }
98
+
99
+ .game-2048-toolbar {
100
+ display: flex;
101
+ align-items: center;
102
+ justify-content: space-between;
103
+ gap: var(--gap);
104
+ width: var(--board-size);
105
+ max-width: 90vw;
106
+ }
107
+
108
+ .game-2048-desc {
109
+ margin: 0;
110
+ font-size: 13px;
111
+ line-height: 1.5;
112
+ color: var(--text-dark);
113
+ opacity: 0.9;
114
+ }
115
+
116
+ .game-2048-actions {
117
+ display: flex;
118
+ gap: 6px;
119
+ flex-shrink: 0;
120
+ }
121
+
122
+ .game-2048-button {
123
+ padding: 8px 14px;
124
+ border: 0;
125
+ border-radius: var(--radius);
126
+ background: var(--accent);
127
+ color: var(--text-light);
128
+ font: inherit;
129
+ font-weight: 700;
130
+ font-size: 14px;
131
+ cursor: pointer;
132
+ transition: background 120ms, transform 80ms;
133
+ }
134
+
135
+ .game-2048-button:hover:not(:disabled) {
136
+ background: #a68472;
137
+ }
138
+
139
+ .game-2048-button:active:not(:disabled) {
140
+ transform: translateY(1px);
141
+ }
142
+
143
+ .game-2048-button:disabled {
144
+ opacity: 0.4;
145
+ cursor: not-allowed;
146
+ }
147
+
148
+ .game-2048-button.is-primary {
149
+ background: #f2b179;
150
+ color: #776e65;
151
+ }
152
+
153
+ .game-2048-button.is-primary:hover:not(:disabled) {
154
+ background: #f59563;
155
+ }
156
+
157
+ .game-2048-board {
158
+ position: relative;
159
+ width: var(--board-size);
160
+ max-width: 90vw;
161
+ aspect-ratio: 1;
162
+ padding: var(--gap);
163
+ border-radius: var(--radius);
164
+ background: var(--bg-board);
165
+ touch-action: none;
166
+ outline: none;
167
+ box-sizing: content-box;
168
+ }
169
+
170
+ .game-2048-board:focus-visible {
171
+ box-shadow: 0 0 0 3px rgba(143, 122, 102, 0.5);
172
+ }
173
+
174
+ .game-2048-grid {
175
+ display: grid;
176
+ width: 100%;
177
+ height: 100%;
178
+ gap: var(--gap);
179
+ }
180
+
181
+ .game-2048-cell {
182
+ border-radius: var(--radius);
183
+ background: var(--bg-empty);
184
+ }
185
+
186
+ .game-2048-tile-layer {
187
+ position: absolute;
188
+ inset: var(--gap);
189
+ pointer-events: none;
190
+ }
191
+
192
+ .game-2048-tile {
193
+ --pitch-x: calc(100% + var(--gap));
194
+ --pitch-y: calc(100% + var(--gap));
195
+ position: absolute;
196
+ top: 0;
197
+ left: 0;
198
+ display: flex;
199
+ align-items: center;
200
+ justify-content: center;
201
+ border-radius: var(--radius);
202
+ background: #eee4da;
203
+ color: var(--text-dark);
204
+ font-weight: 800;
205
+ font-size: clamp(24px, 8vw, 44px);
206
+ line-height: 1;
207
+ /* 注意 --cols 由 board 内联 style 提供 */
208
+ width: calc((100% - var(--gap) * (var(--cols) - 1)) / var(--cols));
209
+ height: calc((100% - var(--gap) * (var(--cols) - 1)) / var(--cols));
210
+ transform: translate(
211
+ calc(var(--col) * var(--pitch-x)),
212
+ calc(var(--row) * var(--pitch-y))
213
+ );
214
+ transition: transform 120ms ease-in-out;
215
+ will-change: transform;
216
+ }
217
+
218
+ .game-2048-tile.is-new {
219
+ animation: game-2048-tile-spawn 180ms ease-out;
220
+ }
221
+
222
+ .game-2048-tile.is-merged {
223
+ animation: game-2048-tile-pop 180ms ease-out;
224
+ z-index: 2;
225
+ }
226
+
227
+ @keyframes game-2048-tile-spawn {
228
+ 0% { opacity: 0; transform: translate(calc(var(--col) * var(--pitch-x)), calc(var(--row) * var(--pitch-y))) scale(0.3); }
229
+ 100% { opacity: 1; transform: translate(calc(var(--col) * var(--pitch-x)), calc(var(--row) * var(--pitch-y))) scale(1); }
230
+ }
231
+
232
+ @keyframes game-2048-tile-pop {
233
+ 0% { transform: translate(calc(var(--col) * var(--pitch-x)), calc(var(--row) * var(--pitch-y))) scale(1); }
234
+ 50% { transform: translate(calc(var(--col) * var(--pitch-x)), calc(var(--row) * var(--pitch-y))) scale(1.18); }
235
+ 100% { transform: translate(calc(var(--col) * var(--pitch-x)), calc(var(--row) * var(--pitch-y))) scale(1); }
236
+ }
237
+
238
+ /* 数值配色(沿用 2048 官方色板) */
239
+ .game-2048-tile[data-value='2'] { background: #eee4da; color: var(--text-dark); }
240
+ .game-2048-tile[data-value='4'] { background: #ede0c8; color: var(--text-dark); }
241
+ .game-2048-tile[data-value='8'] { background: #f2b179; color: var(--text-light); }
242
+ .game-2048-tile[data-value='16'] { background: #f59563; color: var(--text-light); }
243
+ .game-2048-tile[data-value='32'] { background: #f67c5f; color: var(--text-light); }
244
+ .game-2048-tile[data-value='64'] { background: #f65e3b; color: var(--text-light); }
245
+ .game-2048-tile[data-value='128'] { background: #edcf72; color: var(--text-light); font-size: clamp(20px, 6.5vw, 38px); }
246
+ .game-2048-tile[data-value='256'] { background: #edcc61; color: var(--text-light); font-size: clamp(20px, 6.5vw, 38px); }
247
+ .game-2048-tile[data-value='512'] { background: #edc850; color: var(--text-light); font-size: clamp(20px, 6.5vw, 38px); }
248
+ .game-2048-tile[data-value='1024'] { background: #edc53f; color: var(--text-light); font-size: clamp(16px, 5.5vw, 32px); }
249
+ .game-2048-tile[data-value='2048'] { background: #edc22e; color: var(--text-light); font-size: clamp(16px, 5.5vw, 32px); box-shadow: 0 0 24px rgba(243, 215, 116, 0.6); }
250
+ .game-2048-tile[data-super='1'] { background: #3c3a33; color: var(--text-light); font-size: clamp(14px, 5vw, 28px); }
251
+
252
+ .game-2048-overlay {
253
+ position: absolute;
254
+ inset: 0;
255
+ display: flex;
256
+ flex-direction: column;
257
+ align-items: center;
258
+ justify-content: center;
259
+ gap: 12px;
260
+ border-radius: var(--radius);
261
+ background: rgba(238, 228, 218, 0.73);
262
+ color: var(--text-dark);
263
+ text-align: center;
264
+ opacity: 0;
265
+ pointer-events: none;
266
+ transition: opacity 220ms ease-in;
267
+ z-index: 10;
268
+ }
269
+
270
+ .game-2048-overlay.is-visible {
271
+ opacity: 1;
272
+ pointer-events: auto;
273
+ }
274
+
275
+ .game-2048-overlay.is-lost {
276
+ background: rgba(238, 228, 218, 0.5);
277
+ }
278
+
279
+ .game-2048-overlay h2 {
280
+ margin: 0;
281
+ font-size: clamp(32px, 9vw, 52px);
282
+ font-weight: 800;
283
+ color: var(--text-dark);
284
+ }
285
+
286
+ .game-2048-overlay.is-won h2 {
287
+ color: #f9f6f2;
288
+ text-shadow: 0 0 12px rgba(237, 194, 46, 0.6);
289
+ }
290
+
291
+ .game-2048-overlay .row {
292
+ display: flex;
293
+ gap: 8px;
294
+ }
295
+
296
+ .game-2048-ai-indicator {
297
+ display: inline-flex;
298
+ align-items: center;
299
+ gap: 6px;
300
+ padding: 4px 10px;
301
+ border-radius: 999px;
302
+ background: rgba(143, 122, 102, 0.14);
303
+ font-size: 12px;
304
+ color: var(--text-dark);
305
+ }
306
+
307
+ @media (prefers-reduced-motion: reduce) {
308
+ .game-2048-tile,
309
+ .game-2048-overlay {
310
+ transition: none;
311
+ }
312
+ .game-2048-tile.is-new,
313
+ .game-2048-tile.is-merged {
314
+ animation: none;
315
+ }
316
+ }
317
+ /*$vite$:1*/
package/dist/index.js CHANGED
@@ -1,3 +1,355 @@
1
- export { Game2048 } from './Game2048';
2
- export { useGame } from './useGame';
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
+
3
355
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAA2C,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,OAAO,EAA2C,MAAM,WAAW,CAAC"}
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 >\n 再来一局\n </button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n );\n}\n\nexport const Game2048 = forwardRef(Game2048Inner);\nGame2048.displayName = 'Game2048';\n"],"mappings":";;;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AY,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"}
package/dist/useGame.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Game2048, type Direction, type GameOptions, type GameState } from '@my-games/2048-core';
1
+ import { Game2048, Direction, GameOptions, GameState } from '@my-games/2048-core';
2
2
  /**
3
3
  * `useGame` —— React Hook 版引擎桥接。
4
4
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@my-games/2048-react",
3
- "version": "0.1.0",
4
- "description": "2048 游戏的 React 18 组件适配器(函数组件 + Hooks)。",
3
+ "version": "0.2.0",
4
+ "description": "2048 游戏的 React 18/19 组件适配器(函数组件 + Hooks + forwardRef)。",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
@@ -11,7 +11,8 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js"
13
13
  },
14
- "./style.css": "@my-games/2048-core/styles.css"
14
+ "./style.css": "./dist/index.css",
15
+ "./package.json": "./package.json"
15
16
  },
16
17
  "files": [
17
18
  "dist",
@@ -20,23 +21,27 @@
20
21
  ],
21
22
  "sideEffects": false,
22
23
  "peerDependencies": {
23
- "react": "^18.2.0",
24
- "react-dom": "^18.2.0"
24
+ "react": "^18.2.0 || ^19.0.0",
25
+ "react-dom": "^18.2.0 || ^19.0.0"
25
26
  },
26
27
  "dependencies": {
27
- "@my-games/2048-core": "0.1.0"
28
+ "@my-games/2048-core": "0.2.0"
28
29
  },
29
30
  "devDependencies": {
30
- "@types/react": "^18.3.11",
31
- "@types/react-dom": "^18.3.1",
32
- "react": "^18.3.1",
33
- "react-dom": "^18.3.1",
34
- "typescript": "^5.9.3"
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"
35
39
  },
36
40
  "keywords": [
37
41
  "2048",
38
42
  "react",
39
43
  "react18",
44
+ "react19",
40
45
  "game",
41
46
  "puzzle",
42
47
  "component",
@@ -59,7 +64,8 @@
59
64
  "access": "public"
60
65
  },
61
66
  "scripts": {
62
- "build": "tsc -p tsconfig.build.json",
67
+ "build": "vite build --mode lib",
68
+ "dev": "vite build --mode lib --watch",
63
69
  "typecheck": "tsc --noEmit -p tsconfig.json"
64
70
  }
65
71
  }
package/dist/Game2048.js DELETED
@@ -1,164 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
3
- import '@my-games/2048-core/styles.css';
4
- import { useGame } from './useGame';
5
- const KEY_TO_DIR = {
6
- ArrowUp: 'up',
7
- ArrowDown: 'down',
8
- ArrowLeft: 'left',
9
- ArrowRight: 'right',
10
- w: 'up',
11
- a: 'left',
12
- s: 'down',
13
- d: 'right',
14
- W: 'up',
15
- A: 'left',
16
- S: 'down',
17
- D: 'right'
18
- };
19
- function cssVars(vars) {
20
- return vars;
21
- }
22
- function Game2048Inner(props, ref) {
23
- const { size = 4, storage, saveKey, bestKey, freshStart = false, autofocus = true, enableAI = false, aiDepth = 3, title = '2048', onMove, onWon, onLost, className } = props;
24
- const { state, move, newGame, undo, continuePlaying, suggestMove, aiMove } = useGame({
25
- size,
26
- storage,
27
- saveKey,
28
- bestKey,
29
- freshStart,
30
- aiDepth
31
- });
32
- const boardRef = useRef(null);
33
- const touchStartPoint = useRef(null);
34
- const lastScoreRef = useRef(state.score);
35
- const lastStatusRef = useRef(state.status);
36
- const [scoreDelta, setScoreDelta] = useState(null);
37
- const [aiHint, setAiHint] = useState(null);
38
- const deltaTimer = useRef(undefined);
39
- // --- 键盘 ---
40
- const performMove = useCallback((dir) => {
41
- const before = lastScoreRef.current;
42
- const ok = move(dir);
43
- if (ok) {
44
- onMove?.(dir, state.score - before);
45
- if (enableAI)
46
- setAiHint(null);
47
- }
48
- }, [move, onMove, state.score, enableAI]);
49
- useEffect(() => {
50
- const handler = (ev) => {
51
- const dir = KEY_TO_DIR[ev.key];
52
- if (!dir)
53
- return;
54
- // 只有本实例 board 有 DOM 焦点时才响应
55
- if (document.activeElement !== boardRef.current)
56
- return;
57
- ev.preventDefault();
58
- performMove(dir);
59
- };
60
- window.addEventListener('keydown', handler, { passive: false });
61
- return () => window.removeEventListener('keydown', handler);
62
- }, [performMove]);
63
- useEffect(() => {
64
- if (autofocus)
65
- boardRef.current?.focus({ preventScroll: true });
66
- }, [autofocus]);
67
- // --- 触摸 ---
68
- const onTouchStart = (ev) => {
69
- if (ev.touches.length !== 1)
70
- return;
71
- const t = ev.touches[0];
72
- if (!t)
73
- return;
74
- touchStartPoint.current = { x: t.clientX, y: t.clientY };
75
- boardRef.current?.focus({ preventScroll: true });
76
- };
77
- const onTouchEnd = (ev) => {
78
- const start = touchStartPoint.current;
79
- touchStartPoint.current = null;
80
- if (!start)
81
- return;
82
- const t = ev.changedTouches[0];
83
- if (!t)
84
- return;
85
- const dx = t.clientX - start.x;
86
- const dy = t.clientY - start.y;
87
- const adx = Math.abs(dx);
88
- const ady = Math.abs(dy);
89
- if (Math.max(adx, ady) < 24)
90
- return;
91
- const dir = adx > ady ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up';
92
- performMove(dir);
93
- };
94
- // --- 分数 delta 与状态副作用 ---
95
- useEffect(() => {
96
- const gained = state.score - lastScoreRef.current;
97
- if (gained > 0) {
98
- setScoreDelta({ amount: gained, key: Date.now() + Math.random() });
99
- if (deltaTimer.current)
100
- window.clearTimeout(deltaTimer.current);
101
- deltaTimer.current = window.setTimeout(() => setScoreDelta(null), 700);
102
- }
103
- lastScoreRef.current = state.score;
104
- }, [state.score]);
105
- useEffect(() => {
106
- if (state.status === lastStatusRef.current)
107
- return;
108
- if (state.status === 'won')
109
- onWon?.();
110
- else if (state.status === 'lost')
111
- onLost?.();
112
- lastStatusRef.current = state.status;
113
- }, [state.status, onWon, onLost]);
114
- useEffect(() => () => {
115
- if (deltaTimer.current)
116
- window.clearTimeout(deltaTimer.current);
117
- }, []);
118
- // --- 渲染派生 ---
119
- const gridStyle = useMemo(() => cssVars({
120
- gridTemplateColumns: `repeat(${state.size}, 1fr)`,
121
- gridTemplateRows: `repeat(${state.size}, 1fr)`
122
- }), [state.size]);
123
- const boardVars = useMemo(() => cssVars({ '--cols': state.size }), [state.size]);
124
- const undoDisabled = state.historySize === 0;
125
- const overlayVisible = state.status !== 'playing';
126
- const isWon = state.status === 'won';
127
- const isLost = state.status === 'lost';
128
- useImperativeHandle(ref, () => ({
129
- suggestMove,
130
- aiMove,
131
- newGame,
132
- undo,
133
- move,
134
- continuePlaying
135
- }), [suggestMove, aiMove, newGame, undo, move, continuePlaying]);
136
- return (_jsxs("div", { className: ['game-2048', className].filter(Boolean).join(' '), children: [title ? (_jsxs("header", { className: "game-2048-header", children: [_jsx("h1", { className: "game-2048-title", children: title }), _jsxs("div", { className: "game-2048-scores", children: [_jsxs("div", { className: "game-2048-score-box", children: [_jsx("span", { className: "label", children: "Score" }), _jsx("span", { className: "value", children: state.score }), scoreDelta ? (_jsxs("span", { className: "delta", children: ["+", scoreDelta.amount] }, scoreDelta.key)) : null] }), _jsxs("div", { className: "game-2048-score-box", children: [_jsx("span", { className: "label", children: "Best" }), _jsx("span", { className: "value", children: state.bestScore })] })] })] })) : null, _jsxs("div", { className: "game-2048-toolbar", children: [_jsxs("p", { className: "game-2048-desc", children: ["\u5408\u5E76\u76F8\u540C\u6570\u5B57\uFF0C\u51B2\u8FC7 ", _jsx("b", { children: "2048" }), "\u3002\u65B9\u5411\u952E / WASD / \u89E6\u5C4F\u6ED1\u52A8\u3002"] }), _jsxs("div", { className: "game-2048-actions", children: [enableAI ? (_jsx("button", { className: "game-2048-button", type: "button", disabled: isLost, onClick: () => setAiHint(suggestMove()), children: "\u63D0\u793A" })) : null, enableAI ? (_jsx("button", { className: "game-2048-button", type: "button", disabled: isLost, onClick: () => {
137
- const before = state.score;
138
- const dir = aiMove();
139
- if (dir) {
140
- onMove?.(dir, state.score - before);
141
- setAiHint(null);
142
- }
143
- }, children: "AI \u5E2E\u8D70" })) : null, _jsx("button", { className: "game-2048-button", type: "button", disabled: undoDisabled, onClick: () => undo(), children: "\u64A4\u9500" }), _jsx("button", { className: "game-2048-button is-primary", type: "button", onClick: () => newGame(), children: "\u65B0\u6E38\u620F" })] })] }), _jsxs("div", { ref: boardRef, className: "game-2048-board", style: boardVars, tabIndex: 0, role: "application", "aria-label": `2048 游戏板 ${state.status}`, onTouchStart: onTouchStart, onTouchEnd: onTouchEnd, children: [_jsx("div", { className: "game-2048-grid", style: gridStyle, children: Array.from({ length: state.size * state.size }).map((_, i) => (_jsx("div", { className: "game-2048-cell" }, i))) }), _jsx("div", { className: "game-2048-tile-layer", children: state.tiles.map((t) => {
144
- const cls = [
145
- 'game-2048-tile',
146
- t.isNew ? 'is-new' : '',
147
- t.merged ? 'is-merged' : '',
148
- t.value > 2048 ? 'is-super' : ''
149
- ]
150
- .filter(Boolean)
151
- .join(' ');
152
- return (_jsx("div", { className: cls, style: cssVars({ '--row': t.row, '--col': t.col }), "data-value": t.value, ...(t.value > 2048 ? { 'data-super': '1' } : {}), children: t.value }, t.id));
153
- }) }), enableAI && aiHint ? (_jsxs("div", { className: "game-2048-ai-indicator", style: cssVars({ position: 'absolute', top: '8px', left: '8px', zIndex: 3 }), children: ["\u63A8\u8350\uFF1A", aiHint] })) : null, _jsxs("div", { className: [
154
- 'game-2048-overlay',
155
- overlayVisible ? 'is-visible' : '',
156
- isWon ? 'is-won' : '',
157
- isLost ? 'is-lost' : ''
158
- ]
159
- .filter(Boolean)
160
- .join(' '), children: [isWon ? _jsx("h2", { children: "\u4F60\u8D62\u4E86\uFF01" }) : null, isLost ? _jsx("h2", { children: "\u6E38\u620F\u7ED3\u675F" }) : null, _jsxs("div", { className: "row", children: [isWon ? (_jsx("button", { className: "game-2048-button", type: "button", onClick: () => continuePlaying(), children: "\u7EE7\u7EED\u6E38\u620F" })) : null, isLost && !undoDisabled ? (_jsx("button", { className: "game-2048-button", type: "button", onClick: () => undo(), children: "\u6094\u4E00\u6B65" })) : null, overlayVisible ? (_jsx("button", { className: "game-2048-button is-primary", type: "button", onClick: () => newGame(), children: "\u518D\u6765\u4E00\u5C40" })) : null] })] })] })] }));
161
- }
162
- export const Game2048 = forwardRef(Game2048Inner);
163
- Game2048.displayName = 'Game2048';
164
- //# sourceMappingURL=Game2048.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Game2048.js","sourceRoot":"","sources":["../src/Game2048.tsx"],"names":[],"mappings":";AAAA,OAAO,EAIL,UAAU,EACV,WAAW,EACX,SAAS,EACT,mBAAmB,EACnB,OAAO,EACP,MAAM,EACN,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,gCAAgC,CAAC;AAExC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAoCpC,MAAM,UAAU,GAA8B;IAC5C,OAAO,EAAE,IAAI;IACb,SAAS,EAAE,MAAM;IACjB,SAAS,EAAE,MAAM;IACjB,UAAU,EAAE,OAAO;IACnB,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,MAAM;IACT,CAAC,EAAE,MAAM;IACT,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,MAAM;IACT,CAAC,EAAE,MAAM;IACT,CAAC,EAAE,OAAO;CACX,CAAC;AAEF,SAAS,OAAO,CAAC,IAAqC;IACpD,OAAO,IAAqB,CAAC;AAC/B,CAAC;AAED,SAAS,aAAa,CAAC,KAAoB,EAAE,GAAwB;IACnE,MAAM,EACJ,IAAI,GAAG,CAAC,EACR,OAAO,EACP,OAAO,EACP,OAAO,EACP,UAAU,GAAG,KAAK,EAClB,SAAS,GAAG,IAAI,EAChB,QAAQ,GAAG,KAAK,EAChB,OAAO,GAAG,CAAC,EACX,KAAK,GAAG,MAAM,EACd,MAAM,EACN,KAAK,EACL,MAAM,EACN,SAAS,EACV,GAAG,KAAK,CAAC;IAEV,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QACnF,IAAI;QACJ,OAAO;QACP,OAAO;QACP,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC,CAAC;IAEH,M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AC,EAAE;4BACrB,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE;yBACxB;6BACE,MAAM,CAAC,OAAO,CAAC;6BACf,IAAI,CAAC,GAAG,CAAC,aAEX,KAAK,CAAC,CAAC,CAAC,oDAAa,CAAC,CAAC,CAAC,IAAI,EAC5B,MAAM,CAAC,CAAC,CAAC,oDAAa,CAAC,CAAC,CAAC,IAAI,EAC9B,eAAK,SAAS,EAAC,KAAK,aACjB,KAAK,CAAC,CAAC,CAAC,CACP,iBACE,SAAS,EAAC,kBAAkB,EAC5B,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,GAAG,EAAE,CAAC,eAAe,EAAE,yCAGzB,CACV,CAAC,CAAC,CAAC,IAAI,EACP,MAAM,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CACzB,iBACE,SAAS,EAAC,kBAAkB,EAC5B,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,mCAGd,CACV,CAAC,CAAC,CAAC,IAAI,EACP,cAAc,CAAC,CAAC,CAAC,CAChB,iBACE,SAAS,EAAC,6BAA6B,EACvC,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,yCAGjB,CACV,CAAC,CAAC,CAAC,IAAI,IACJ,IACF,IACF,IACF,CACP,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;AAClD,QAAQ,CAAC,WAAW,GAAG,UAAU,CAAC"}
package/dist/useGame.js DELETED
@@ -1,34 +0,0 @@
1
- import { useEffect, useMemo, useRef, useState } from 'react';
2
- import { bestMove as aiBestMove, Game2048 } from '@my-games/2048-core';
3
- export function useGame(options = {}) {
4
- const { aiDepth = 3, size, storage, saveKey, bestKey, freshStart, target, undoLimit, rng } = options;
5
- // useMemo 依赖里不放 rng / storage(函数/对象引用不稳定;重开一次即可)
6
- const game = useMemo(() => new Game2048({ size, storage, saveKey, bestKey, freshStart, target, undoLimit, rng }),
7
- // eslint-disable-next-line react-hooks/exhaustive-deps
8
- [size, saveKey, bestKey, target, undoLimit]);
9
- const gameRef = useRef(game);
10
- gameRef.current = game;
11
- const [state, setState] = useState(() => game.getState());
12
- useEffect(() => {
13
- // 引擎替换时重新订阅;先把 state 拉齐到最新,防止首帧错位
14
- setState(game.getState());
15
- const unsub = game.subscribe((s) => setState(s));
16
- return unsub;
17
- }, [game]);
18
- return {
19
- state,
20
- game,
21
- move: (dir) => gameRef.current.move(dir),
22
- newGame: () => gameRef.current.newGame(),
23
- undo: () => gameRef.current.undo(),
24
- continuePlaying: () => gameRef.current.continuePlaying(),
25
- suggestMove: () => aiBestMove(gameRef.current.getGridValues(), { depth: aiDepth }),
26
- aiMove: () => {
27
- const dir = aiBestMove(gameRef.current.getGridValues(), { depth: aiDepth });
28
- if (dir)
29
- gameRef.current.move(dir);
30
- return dir;
31
- }
32
- };
33
- }
34
- //# sourceMappingURL=useGame.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGame.js","sourceRoot":"","sources":["../src/useGame.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC7D,OAAO,EACL,QAAQ,IAAI,UAAU,EACtB,QAAQ,EAIT,MAAM,qBAAqB,CAAC;AA0B7B,MAAM,UAAU,OAAO,CAAC,UAA0B,EAAE;IAClD,MAAM,EAAE,OAAO,GAAG,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC;IAErG,iDAAiD;IACjD,MAAM,IAAI,GAAG,OAAO,CAClB,GAAG,EAAE,CAAC,IAAI,QAAQ,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UA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