-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1773 lines (1559 loc) · 55.2 KB
/
Copy pathscript.js
File metadata and controls
1773 lines (1559 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const LEVELS = {
beginner: { label: "初级", rows: 9, cols: 9, mines: 10 },
intermediate: { label: "中级", rows: 16, cols: 16, mines: 40 },
expert: { label: "高级", rows: 16, cols: 30, mines: 99 }
};
const APP_BASE_PATH = getAppBasePath();
const API_BASE_PATH = `${APP_BASE_PATH}api`;
const ADMIN_PATH = `${APP_BASE_PATH}admin`;
const APP_HOME_PATH = APP_BASE_PATH || "/";
const app = document.querySelector("#app");
const board = document.querySelector("#board");
const boardWrap = document.querySelector(".board-wrap");
const mineCounter = document.querySelector("#mineCounter");
const timerText = document.querySelector("#timer");
const resetButton = document.querySelector("#resetButton");
const restartRoundButton = document.querySelector("#restartRoundButton");
const stateText = document.querySelector("#stateText");
const bestText = document.querySelector("#bestText");
const cloudText = document.querySelector("#cloudText");
const cloudToggle = document.querySelector("#cloudToggle");
const authModal = document.querySelector("#authModal");
const closeAuthModal = document.querySelector("#closeAuthModal");
const authForm = document.querySelector("#authForm");
const usernameInput = document.querySelector("#usernameInput");
const passwordInput = document.querySelector("#passwordInput");
const cloudAccount = document.querySelector("#cloudAccount");
const cloudUser = document.querySelector("#cloudUser");
const logoutButton = document.querySelector("#logoutButton");
const linuxdoLogin = document.querySelector("#linuxdoLogin");
const userCard = document.querySelector("#userCard");
const userAvatar = document.querySelector("#userAvatar");
const userName = document.querySelector("#userName");
const userProvider = document.querySelector("#userProvider");
const userSyncState = document.querySelector("#userSyncState");
const adminModal = document.querySelector("#adminModal");
const closeAdminModal = document.querySelector("#closeAdminModal");
const adminStatus = document.querySelector("#adminStatus");
const adminStats = document.querySelector("#adminStats");
const adminLevels = document.querySelector("#adminLevels");
const adminScores = document.querySelector("#adminScores");
const adminUsers = document.querySelector("#adminUsers");
const adminUserCount = document.querySelector("#adminUserCount");
const adminOverviewNote = document.querySelector("#adminOverviewNote");
const adminModuleSummary = document.querySelector("#adminModuleSummary");
const adminModuleButtons = [...document.querySelectorAll("[data-admin-module]")];
const adminModulePanels = [...document.querySelectorAll("[data-admin-panel]")];
const leaderboardSelectAll = document.querySelector("#leaderboardSelectAll");
const leaderboardClearSelected = document.querySelector("#leaderboardClearSelected");
const userSelectAll = document.querySelector("#userSelectAll");
const userDeleteSyncSelected = document.querySelector("#userDeleteSyncSelected");
const userDeleteSelected = document.querySelector("#userDeleteSelected");
const leaderboardStatus = document.querySelector("#leaderboardStatus");
const leaderboardList = document.querySelector("#leaderboardList");
const myRankText = document.querySelector("#myRank");
const learnList = document.querySelector("#learnList");
const leaderboardPane = document.querySelector("#leaderboardPane");
const learnPane = document.querySelector("#learnPane");
const campaignCard = document.querySelector("#campaignCard");
const campaignTitle = document.querySelector("#campaignTitle");
const campaignText = document.querySelector("#campaignText");
const campaignCoupons = document.querySelector("#campaignCoupons");
const sideTabs = [...document.querySelectorAll("[data-side-tab]")];
const levelButtons = [...document.querySelectorAll("[data-level-button]")];
if (isAdminPath()) {
location.replace("/admin?tab=minesweeper");
}
const STORE_KEY = "minesweeper-state-v2";
const BEST_KEY = "minesweeper-best-v1";
const SYNC_META_KEY = "minesweeper-sync-meta-v1";
const LONG_PRESS_MS = 520;
const MOVE_TOLERANCE = 12;
const EXPRESSION_LESSONS = {
"√1": { value: 1, title: "平方根", method: "平方根表示哪个数平方后等于被开方数。因为 1×1=1,所以 √1=1。" },
"log₂2": { value: 1, title: "以 2 为底的对数", method: "log₂2 表示 2 的几次方等于 2。因为 2¹=2,所以 log₂2=1。" },
"0!": { value: 1, title: "阶乘", method: "0! 是阶乘的规定值,等于 1。它让组合公式在边界情况也成立。" },
"sin90°": { value: 1, title: "三角函数", method: "在单位圆中,90° 对应点的纵坐标是 1,所以 sin90°=1。" },
"C(1,1)": { value: 1, title: "组合数", method: "C(n,k) 表示从 n 个对象中选 k 个。1 个里选 1 个只有 1 种,所以 C(1,1)=1。" },
"√4": { value: 2, title: "平方根", method: "因为 2×2=4,所以 √4=2。" },
"log₂4": { value: 2, title: "以 2 为底的对数", method: "log₂4 表示 2 的几次方等于 4。因为 2²=4,所以结果是 2。" },
"2!": { value: 2, title: "阶乘", method: "2! 表示 2×1,所以 2!=2。" },
"C(2,1)": { value: 2, title: "组合数", method: "从 2 个对象中选 1 个,有 2 种选法,所以 C(2,1)=2。" },
"⌈1.2⌉": { value: 2, title: "上取整", method: "⌈x⌉ 表示不小于 x 的最小整数。不小于 1.2 的最小整数是 2。" },
"√9": { value: 3, title: "平方根", method: "因为 3×3=9,所以 √9=3。" },
"log₂8": { value: 3, title: "以 2 为底的对数", method: "因为 2³=8,所以 log₂8=3。" },
"C(3,1)": { value: 3, title: "组合数", method: "从 3 个对象中选 1 个,有 3 种选法,所以 C(3,1)=3。" },
"⌈2.1⌉": { value: 3, title: "上取整", method: "不小于 2.1 的最小整数是 3,所以 ⌈2.1⌉=3。" },
"⌊3.9⌋": { value: 3, title: "下取整", method: "⌊x⌋ 表示不大于 x 的最大整数。不大于 3.9 的最大整数是 3。" },
"√16": { value: 4, title: "平方根", method: "因为 4×4=16,所以 √16=4。" },
"log₂16": { value: 4, title: "以 2 为底的对数", method: "因为 2⁴=16,所以 log₂16=4。" },
"2²": { value: 4, title: "乘方", method: "2² 表示两个 2 相乘,即 2×2=4。" },
"C(4,1)": { value: 4, title: "组合数", method: "从 4 个对象中选 1 个,有 4 种选法,所以 C(4,1)=4。" },
"⌈3.1⌉": { value: 4, title: "上取整", method: "不小于 3.1 的最小整数是 4,所以 ⌈3.1⌉=4。" },
"√25": { value: 5, title: "平方根", method: "因为 5×5=25,所以 √25=5。" },
"log₂32": { value: 5, title: "以 2 为底的对数", method: "因为 2⁵=32,所以 log₂32=5。" },
"C(5,1)": { value: 5, title: "组合数", method: "从 5 个对象中选 1 个,有 5 种选法,所以 C(5,1)=5。" },
"⌊5.9⌋": { value: 5, title: "下取整", method: "不大于 5.9 的最大整数是 5,所以 ⌊5.9⌋=5。" },
"⌈4.1⌉": { value: 5, title: "上取整", method: "不小于 4.1 的最小整数是 5,所以 ⌈4.1⌉=5。" },
"√36": { value: 6, title: "平方根", method: "因为 6×6=36,所以 √36=6。" },
"log₂64": { value: 6, title: "以 2 为底的对数", method: "因为 2⁶=64,所以 log₂64=6。" },
"3!": { value: 6, title: "阶乘", method: "3! 表示 3×2×1,所以 3!=6。" },
"C(6,1)": { value: 6, title: "组合数", method: "从 6 个对象中选 1 个,有 6 种选法,所以 C(6,1)=6。" },
"⌈5.1⌉": { value: 6, title: "上取整", method: "不小于 5.1 的最小整数是 6,所以 ⌈5.1⌉=6。" },
"√49": { value: 7, title: "平方根", method: "因为 7×7=49,所以 √49=7。" },
"log₂128": { value: 7, title: "以 2 为底的对数", method: "因为 2⁷=128,所以 log₂128=7。" },
"C(7,1)": { value: 7, title: "组合数", method: "从 7 个对象中选 1 个,有 7 种选法,所以 C(7,1)=7。" },
"⌊7.9⌋": { value: 7, title: "下取整", method: "不大于 7.9 的最大整数是 7,所以 ⌊7.9⌋=7。" },
"⌈6.1⌉": { value: 7, title: "上取整", method: "不小于 6.1 的最小整数是 7,所以 ⌈6.1⌉=7。" },
"√64": { value: 8, title: "平方根", method: "因为 8×8=64,所以 √64=8。" },
"log₂256": { value: 8, title: "以 2 为底的对数", method: "因为 2⁸=256,所以 log₂256=8。" },
"C(8,1)": { value: 8, title: "组合数", method: "从 8 个对象中选 1 个,有 8 种选法,所以 C(8,1)=8。" },
"⌈7.1⌉": { value: 8, title: "上取整", method: "不小于 7.1 的最小整数是 8,所以 ⌈7.1⌉=8。" },
"⌊8.9⌋": { value: 8, title: "下取整", method: "不大于 8.9 的最大整数是 8,所以 ⌊8.9⌋=8。" }
};
const NUMBER_EXPRESSIONS = {
1: ["√1", "log₂2", "0!", "sin90°", "C(1,1)"],
2: ["√4", "log₂4", "2!", "C(2,1)", "⌈1.2⌉"],
3: ["√9", "log₂8", "C(3,1)", "⌈2.1⌉", "⌊3.9⌋"],
4: ["√16", "log₂16", "2²", "C(4,1)", "⌈3.1⌉"],
5: ["√25", "log₂32", "C(5,1)", "⌊5.9⌋", "⌈4.1⌉"],
6: ["√36", "log₂64", "3!", "C(6,1)", "⌈5.1⌉"],
7: ["√49", "log₂128", "C(7,1)", "⌊7.9⌋", "⌈6.1⌉"],
8: ["√64", "log₂256", "C(8,1)", "⌈7.1⌉", "⌊8.9⌋"]
};
let state = createState("beginner");
let timerId = null;
let longPressTimer = null;
let longPressPointerId = null;
let longPressStart = null;
let suppressNextClick = false;
let suppressNextContextMenu = false;
let currentUser = null;
let syncStatus = "local";
let syncTimer = null;
let isSyncing = false;
let pendingSync = false;
let lastFocusedElement = null;
let leaderboard = [];
let myRank = null;
let adminData = null;
let selectedAdminScores = new Set();
let selectedAdminUsers = new Set();
let couponCampaign = null;
function campaignCurrency() {
const currency = couponCampaign?.currency || {};
return {
mode: currency.mode === "image" ? "image" : "text",
symbol: String(currency.symbol || "L").trim() || "L",
imageUrl: String(currency.imageUrl || "").trim()
};
}
function renderCampaignCurrencyPrefix() {
const currency = campaignCurrency();
if (currency.mode === "image" && currency.imageUrl) {
return `<img class="currency-icon" src="${escapeAttr(currency.imageUrl)}" alt="${escapeAttr(currency.symbol || "货币")}" loading="lazy">`;
}
return escapeHtml(currency.symbol);
}
function renderCampaignMoney(value) {
return `<span class="money-value">${renderCampaignCurrencyPrefix()} <span>${Number(value || 0).toLocaleString("zh-CN")}</span></span>`;
}
function formatCampaignMoneyText(value) {
return `${Number(value || 0).toLocaleString("zh-CN")} ${campaignCurrency().symbol}`;
}
function createState(level) {
const config = LEVELS[level];
return {
level,
rows: config.rows,
cols: config.cols,
mines: config.mines,
cells: Array.from({ length: config.rows * config.cols }, (_, index) => ({
index,
mine: false,
open: false,
flagged: false,
question: false,
value: 0
})),
status: "ready",
startedAt: null,
elapsed: 0,
flags: 0,
opened: 0,
firstClick: true
};
}
function saveState() {
persistLocalState(Date.now());
queueCloudSync();
}
function persistLocalState(clientUpdatedAt) {
try {
localStorage.setItem(STORE_KEY, JSON.stringify(state));
setLocalUpdatedAt(clientUpdatedAt);
} catch {
// Storage can be blocked in private modes or unusual file:// policies.
}
}
function loadState() {
try {
const parsed = JSON.parse(localStorage.getItem(STORE_KEY));
if (!parsed || !LEVELS[parsed.level] || !Array.isArray(parsed.cells)) {
return null;
}
const expected = parsed.rows * parsed.cols;
return parsed.cells.length === expected ? parsed : null;
} catch {
return null;
}
}
function getBestTimes() {
try {
return JSON.parse(localStorage.getItem(BEST_KEY)) || {};
} catch {
return {};
}
}
function setBestTime(level, seconds) {
const best = getBestTimes();
const scoreSeconds = Math.max(1, Math.min(999, Math.trunc(seconds)));
if (!best[level] || scoreSeconds < best[level]) {
best[level] = scoreSeconds;
try {
localStorage.setItem(BEST_KEY, JSON.stringify(best));
} catch {
// Best time is optional; gameplay should continue without storage.
}
}
queueCloudSync();
submitLeaderboardScore(level, scoreSeconds);
}
function setBestTimes(best) {
try {
localStorage.setItem(BEST_KEY, JSON.stringify(best || {}));
} catch {
// Best time is optional; gameplay should continue without storage.
}
}
function startTimer() {
stopTimer();
timerId = setInterval(() => {
if (state.status !== "playing") {
stopTimer();
return;
}
state.elapsed = Math.min(999, Math.floor((Date.now() - state.startedAt) / 1000));
syncHud();
saveState();
}, 500);
}
function stopTimer() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function startGameIfNeeded(firstIndex) {
if (!state.firstClick) {
return;
}
state.firstClick = false;
state.status = "playing";
state.startedAt = Date.now() - state.elapsed * 1000;
placeMines(firstIndex);
calculateValues();
startTimer();
}
function placeMines(safeIndex) {
const safe = new Set([safeIndex, ...neighborsOf(safeIndex)]);
const candidates = state.cells
.map((cell) => cell.index)
.filter((index) => !safe.has(index));
shuffle(candidates);
for (const index of candidates.slice(0, state.mines)) {
state.cells[index].mine = true;
}
}
function calculateValues() {
for (const cell of state.cells) {
if (cell.mine) {
continue;
}
cell.value = neighborsOf(cell.index).filter((index) => state.cells[index].mine).length;
}
}
function shuffle(items) {
for (let index = items.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(Math.random() * (index + 1));
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
}
}
function neighborsOf(index) {
const row = Math.floor(index / state.cols);
const col = index % state.cols;
const result = [];
for (let rowOffset = -1; rowOffset <= 1; rowOffset += 1) {
for (let colOffset = -1; colOffset <= 1; colOffset += 1) {
if (rowOffset === 0 && colOffset === 0) {
continue;
}
const nextRow = row + rowOffset;
const nextCol = col + colOffset;
if (nextRow >= 0 && nextRow < state.rows && nextCol >= 0 && nextCol < state.cols) {
result.push(nextRow * state.cols + nextCol);
}
}
}
return result;
}
function openCell(index) {
if (state.status === "won" || state.status === "lost") {
return;
}
const cell = state.cells[index];
if (!cell || cell.open || cell.flagged) {
return;
}
startGameIfNeeded(index);
cell.question = false;
cell.open = true;
state.opened += 1;
if (cell.mine) {
loseGame(index);
return;
}
if (cell.value === 0) {
floodOpen(index);
}
checkWin();
syncAll();
}
function floodOpen(startIndex) {
const queue = [startIndex];
const visited = new Set(queue);
while (queue.length > 0) {
const current = queue.shift();
for (const nextIndex of neighborsOf(current)) {
const next = state.cells[nextIndex];
if (visited.has(nextIndex) || next.open || next.flagged || next.mine) {
continue;
}
visited.add(nextIndex);
next.question = false;
next.open = true;
state.opened += 1;
if (next.value === 0) {
queue.push(nextIndex);
}
}
}
}
function toggleMark(index) {
if (state.status === "won" || state.status === "lost") {
return;
}
const cell = state.cells[index];
if (!cell || cell.open) {
return;
}
if (cell.flagged) {
cell.flagged = false;
cell.question = true;
state.flags -= 1;
} else if (cell.question) {
cell.question = false;
} else {
cell.flagged = true;
state.flags += 1;
}
syncAll();
}
function chordOpen(index) {
if (state.status !== "playing") {
return;
}
const cell = state.cells[index];
if (!cell?.open || cell.value === 0) {
return;
}
const neighbors = neighborsOf(index);
const flaggedCount = neighbors.filter((nextIndex) => state.cells[nextIndex].flagged).length;
if (flaggedCount !== cell.value) {
return;
}
for (const nextIndex of neighbors) {
const next = state.cells[nextIndex];
if (!next.open && !next.flagged) {
openCell(nextIndex);
}
}
}
function loseGame(blastIndex) {
state.status = "lost";
stopTimer();
for (const cell of state.cells) {
if (cell.mine) {
cell.open = true;
}
}
syncAll(blastIndex);
}
function checkWin() {
const safeCells = state.rows * state.cols - state.mines;
if (state.opened !== safeCells) {
return;
}
state.status = "won";
state.flags = state.mines;
state.elapsed = Math.min(999, Math.floor((Date.now() - state.startedAt) / 1000));
stopTimer();
setBestTime(state.level, state.elapsed);
for (const cell of state.cells) {
if (cell.mine) {
cell.flagged = true;
cell.question = false;
}
}
}
function resetGame(level = state.level) {
stopTimer();
state = createState(level);
syncAll();
}
function changeLevel(level) {
if (!LEVELS[level] || state.level === level) {
return;
}
resetGame(level);
loadLeaderboard();
}
function syncAll(blastIndex = null, shouldSave = true) {
syncAppState();
syncBoard(blastIndex);
syncHud();
if (shouldSave) {
saveState();
}
}
function syncAppState() {
app.dataset.gameState = state.status;
app.dataset.level = state.level;
for (const button of levelButtons) {
const isActive = button.dataset.levelButton === state.level;
button.classList.toggle("is-active", isActive);
button.setAttribute("aria-pressed", String(isActive));
}
}
function syncBoard(blastIndex = null) {
board.style.setProperty("--cols", state.cols);
fitBoardToViewport();
board.innerHTML = "";
for (const cell of state.cells) {
const expression = cell.open && !cell.mine && cell.value > 0 ? getNumberExpression(cell) : "";
const button = document.createElement("button");
button.type = "button";
button.className = "cell";
button.dataset.index = String(cell.index);
button.dataset.open = String(cell.open);
button.dataset.flagged = String(cell.flagged);
button.dataset.question = String(cell.question);
button.dataset.mine = String(cell.mine && (cell.open || state.status === "won" || state.status === "lost"));
button.dataset.value = String(cell.value);
button.dataset.expression = expression;
button.dataset.blast = String(blastIndex === cell.index);
button.setAttribute("role", "gridcell");
button.setAttribute("aria-label", describeCell(cell, expression));
button.disabled = state.status === "won" || state.status === "lost";
if (expression) {
const expressionText = document.createElement("span");
expressionText.className = "math-expression";
expressionText.dataset.length = String(expression.length);
expressionText.textContent = expression;
button.appendChild(expressionText);
}
board.appendChild(button);
}
}
function fitBoardToViewport() {
const bounds = boardWrap.getBoundingClientRect();
const gap = 3;
const horizontalPadding = 8;
const verticalPadding = 12;
const maxByWidth = Math.floor((bounds.width - horizontalPadding - gap * (state.cols - 1)) / state.cols);
const maxByHeight = Math.floor((bounds.height - verticalPadding - gap * (state.rows - 1)) / state.rows);
const minReadableSize = state.cols >= 30 ? 20 : 26;
const cellSize = Math.max(minReadableSize, Math.min(52, maxByWidth || 52, maxByHeight || 52));
board.style.setProperty("--cell-size", `${cellSize}px`);
board.dataset.compactMath = String(cellSize < 23);
}
window.addEventListener("resize", () => {
fitBoardToViewport();
});
function syncHud() {
syncMineCounter();
timerText.textContent = padNumber(state.elapsed);
const best = getBestTimes()[state.level];
bestText.textContent = best ? `最佳: ${best}s` : "最佳: --";
const messages = {
ready: "点击格子开始,数字会以高中公式显示",
playing: `${LEVELS[state.level].label}局进行中,公式结果就是相邻雷数`,
won: `完成,用时 ${state.elapsed}s`,
lost: "踩雷了,点击表情重开"
};
stateText.textContent = messages[state.status];
syncCloudHud();
}
function syncCloudHud() {
const labels = {
local: "本地",
online: "云端已连接",
syncing: "同步中",
saved: "云端已保存",
offline: "云端暂不可用",
error: "同步失败"
};
cloudText.textContent = labels[syncStatus] || labels.local;
cloudToggle.textContent = currentUser ? "云端同步" : "返回商城登录";
cloudUser.textContent = currentUser ? `${currentUser.username}` : "未登录";
cloudAccount.hidden = !currentUser;
authForm.hidden = true;
userCard.dataset.loggedIn = String(Boolean(currentUser));
const displayName = currentUser?.linuxdo?.username || currentUser?.username || "";
userAvatar.textContent = currentUser ? displayName.slice(0, 1).toUpperCase() : "未";
userName.textContent = currentUser ? displayName : "未登录";
userProvider.textContent = currentUser ? getProviderLabel(currentUser.provider) : "本地游玩";
userSyncState.textContent = currentUser?.linuxdo?.id
? `Linux.do ID: ${currentUser.linuxdo.id}`
: currentUser
? labels[syncStatus] || labels.online
: "请先登录商城";
renderCouponCampaign();
renderLeaderboard();
}
function renderCouponCampaign() {
if (!campaignCard) return;
const campaign = couponCampaign?.campaign || {};
if (campaign.enabled === false) {
campaignCard.hidden = true;
return;
}
campaignCard.hidden = false;
const coupons = Array.isArray(couponCampaign?.userCoupons) ? couponCampaign.userCoupons : [];
const ranks = Array.isArray(couponCampaign?.ranks) ? couponCampaign.ranks : [];
const currentRank = ranks.find((item) => item.level === state.level) || couponCampaign?.rank || null;
campaignTitle.textContent = currentRank?.rank ? `${LEVELS[state.level].label}首通第 ${currentRank.rank} 名` : `${LEVELS[state.level].label}首通领券`;
const start = formatShortDate(campaign.startAt || "2026-05-18 00:00:00");
const end = formatShortDate(campaign.endsAt || "2026-05-25 00:00:00");
const percentValue = getCampaignRewardValue(campaign, "levelPercentCoupons", state.level);
const fixedValue = getCampaignRewardValue(campaign, "levelFirstFixedCoupons", state.level);
campaignText.innerHTML = `${escapeHtml(start)}-${escapeHtml(end)} · 当前难度首通 ${Number(percentValue || 0)}% · 第一名 ${renderCampaignMoney(fixedValue || 0)}`;
const activeCoupons = coupons.filter((coupon) => coupon.status === "active").slice(0, 2);
campaignCoupons.innerHTML = activeCoupons.length ? activeCoupons.map((coupon) => `
<span class="campaign-coupon ${coupon.status === "active" ? "is-active" : ""}">
<strong>${escapeHtml(coupon.label || coupon.code)}</strong>
<small>${coupon.type === "percent" ? `${Number(coupon.value || 0)}%` : renderCampaignMoney(coupon.value || 0)} · ${couponStatusLabel(coupon.status)} · ${formatShortDate(coupon.expiresAt)} 到期</small>
</span>
`).join("") : `<span class="campaign-empty">${currentUser ? "通关后自动发券" : "登录后参与"}</span>`;
}
function getCampaignRewardValue(campaign, key, level) {
const source = campaign?.[key];
if (source && typeof source === "object" && !Array.isArray(source)) {
return Number(source[level] || 0);
}
const rows = Array.isArray(source) ? source : [];
const item = rows.find((row) => row.level === level);
return Number(item?.value || 0);
}
function couponStatusLabel(status) {
return ({ active: "可用", reserved: "已锁定", used: "已使用", expired: "已过期", inactive: "已停用" })[status] || status || "未知";
}
function formatShortDate(value) {
if (!value) return "-";
const date = parseAppDate(value);
if (Number.isNaN(date.getTime())) return String(value);
return new Intl.DateTimeFormat("zh-CN", {
timeZone: "Asia/Shanghai",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23"
}).format(date);
}
function parseAppDate(value) {
if (value instanceof Date) return value;
const text = String(value || "").trim();
if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/.test(text)) {
return new Date(`${text.replace(" ", "T")}${text.length === 16 ? ":00" : ""}Z`);
}
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(text)) {
return new Date(`${text}${text.length === 16 ? ":00" : ""}Z`);
}
return new Date(text);
}
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function escapeAttr(value) {
return escapeHtml(value);
}
function getProviderLabel(provider) {
if (provider === "linuxdo") {
return "Linux.do 登录";
}
if (provider === "password") {
return "账号密码登录";
}
return "云端账号";
}
function syncMineCounter() {
const markedCells = countMarkedCells();
const remainingMines = calculateRemainingMines(state.mines, markedCells);
state.flags = markedCells;
const ruleText = "f(m,b)=m-b";
const valueText = `f(${state.mines},${markedCells})=${padNumber(remainingMines)}`;
mineCounter.querySelector(".function-rule").textContent = ruleText;
mineCounter.querySelector(".function-value").textContent = valueText;
mineCounter.dataset.totalMines = String(state.mines);
mineCounter.dataset.markedCells = String(markedCells);
mineCounter.dataset.remainingMines = String(remainingMines);
mineCounter.title = `${ruleText}; ${state.mines} - ${markedCells} = ${remainingMines}`;
mineCounter.setAttribute("aria-label", `剩余雷数函数 ${valueText}`);
}
function calculateRemainingMines(totalMines, markedCells) {
return Math.max(0, Math.min(999, Math.trunc(totalMines - markedCells)));
}
function countMarkedCells() {
return state.cells.reduce((total, cell) => total + Number(cell.flagged), 0);
}
function padNumber(value) {
return String(Math.max(0, Math.min(999, Math.trunc(value)))).padStart(3, "0");
}
function getNumberExpression(cell) {
const expressions = NUMBER_EXPRESSIONS[cell.value] || [String(cell.value)];
const expressionIndex = Math.abs(cell.index * 31 + cell.value * 17 + state.rows * 7 + state.cols * 11) % expressions.length;
return expressions[expressionIndex];
}
function describeCell(cell, expression = "") {
if (cell.flagged) {
return "已标记为雷";
}
if (!cell.open) {
return "未打开格子";
}
if (cell.mine) {
return "地雷";
}
if (cell.value === 0) {
return "空白格";
}
return expression ? `公式 ${expression},表示相邻地雷数量` : "已打开数字格";
}
function clearLongPress() {
if (longPressTimer) {
clearTimeout(longPressTimer);
}
longPressTimer = null;
longPressPointerId = null;
longPressStart = null;
}
function registerServiceWorker() {
if (!("serviceWorker" in navigator) || !location.protocol.startsWith("http")) {
return;
}
navigator.serviceWorker.register(toAppPath("sw.js"), { scope: APP_BASE_PATH || "./" }).catch(() => {
// Offline mode is an enhancement; local gameplay remains available.
});
}
async function checkCloudSession({ silent = false } = {}) {
setSyncStatus("local");
try {
const response = await apiFetch(`/auth/me?_=${Date.now()}`, {
cache: "no-store"
});
if (!response.ok) {
setCurrentUser(null);
if (!silent) {
stateText.textContent = "请先登录";
}
return;
}
const data = await response.json();
setCurrentUser(data.user);
await pullCloudSync();
await loadCouponCampaign();
await loadLeaderboard();
} catch {
setSyncStatus("offline");
}
}
async function handleAuth(action) {
const username = usernameInput.value.trim();
const password = passwordInput.value;
setSyncStatus("syncing");
try {
const response = await apiFetch(`/auth/${action}`, {
method: "POST",
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "登录失败");
}
passwordInput.value = "";
setCurrentUser(data.user);
await pullCloudSync();
await loadCouponCampaign();
await loadLeaderboard();
queueCloudSync(true);
closeAuthModalDialog();
} catch (error) {
setSyncStatus("error");
stateText.textContent = error.message || "登录失败";
}
}
async function logoutCloud() {
try {
await apiFetch("/auth/logout", { method: "POST" });
} finally {
setCurrentUser(null);
setSyncStatus("local");
syncHud();
loadLeaderboard();
location.href = "/";
}
}
async function pullCloudSync() {
if (!currentUser) {
return;
}
setSyncStatus("syncing");
const response = await apiFetch("/sync");
if (!response.ok) {
setSyncStatus("error");
return;
}
const remote = await response.json();
const localUpdatedAt = getLocalUpdatedAt();
const remoteUpdatedAt = Number(remote.clientUpdatedAt || 0);
if (remote.state && remoteUpdatedAt > localUpdatedAt && isValidState(remote.state)) {
stopTimer();
state = remote.state;
if (state.status === "playing") {
state.startedAt = Date.now() - state.elapsed * 1000;
startTimer();
}
}
if (remote.best && remoteUpdatedAt >= localUpdatedAt) {
setBestTimes(remote.best);
}
persistLocalState(Math.max(localUpdatedAt, remoteUpdatedAt));
syncAppState();
syncBoard();
syncHud();
setSyncStatus("online");
}
function queueCloudSync(immediate = false) {
if (!currentUser) {
return;
}
pendingSync = true;
clearTimeout(syncTimer);
syncTimer = setTimeout(pushCloudSync, immediate ? 0 : 700);
}
async function pushCloudSync() {
if (!currentUser || isSyncing || !pendingSync) {
return;
}
isSyncing = true;
pendingSync = false;
setSyncStatus("syncing");
try {
const response = await apiFetch("/sync", {
method: "PUT",
body: JSON.stringify({
state,
best: getBestTimes(),
clientUpdatedAt: getLocalUpdatedAt()
})
});
if (!response.ok) {
throw new Error("sync failed");
}
setSyncStatus("saved");
} catch {
pendingSync = true;
setSyncStatus("offline");
} finally {
isSyncing = false;
}
}
async function loadLeaderboard() {
leaderboardStatus.textContent = `${LEVELS[state.level].label}榜单`;
try {
const response = await apiFetch(`/leaderboard?level=${encodeURIComponent(state.level)}&_=${Date.now()}`, {
cache: "no-store"
});
if (!response.ok) {
throw new Error("leaderboard failed");
}
const data = await response.json();
leaderboard = Array.isArray(data.leaders) ? data.leaders : [];
myRank = data.myRank || null;
leaderboardStatus.textContent = `${LEVELS[state.level].label}前 10`;
renderLeaderboard();
} catch {
leaderboard = [];
myRank = null;
leaderboardStatus.textContent = "榜单暂不可用";
renderLeaderboard("暂时无法读取排行榜");
}
}
async function submitLeaderboardScore(level, seconds) {
if (!currentUser) {
return;
}
try {
const response = await apiFetch("/leaderboard", {
method: "POST",
body: JSON.stringify({ level, seconds })
});
if (!response.ok) {
throw new Error("leaderboard submit failed");
}
const data = await response.json();
if (data.campaign) {
couponCampaign = {
campaign: data.campaign,
rank: data.campaignRank || null,
ranks: data.campaignRanks || data.campaignRank?.ranks || [],
userCoupons: data.userCoupons || []
};
renderCouponCampaign();
const activeCoupons = (couponCampaign.userCoupons || []).filter((coupon) => coupon.status === "active");
if (activeCoupons.length) {
stateText.textContent = `成绩已写入,扫雷活动券已发放 ${activeCoupons.length} 张`;
}
}
if (data.level === state.level) {
leaderboard = Array.isArray(data.leaders) ? data.leaders : [];
myRank = data.myRank || null;
leaderboardStatus.textContent = `${LEVELS[state.level].label}前 10`;
renderLeaderboard();
}
} catch {
leaderboardStatus.textContent = "成绩未写入榜单";
}
}
async function loadCouponCampaign() {
try {
const response = await apiFetch(`/minesweeper/campaign?_=${Date.now()}`, { cache: "no-store" });
if (!response.ok) throw new Error("campaign failed");
couponCampaign = await response.json();
} catch {
couponCampaign = { campaign: null, currency: { mode: "text", symbol: "L", imageUrl: "" }, rank: null, ranks: [], userCoupons: [] };
}
renderCouponCampaign();
}
function renderLeaderboard(message = "") {
leaderboardList.innerHTML = "";
renderMyRank();
if (message || leaderboard.length === 0) {
const empty = document.createElement("li");
empty.className = "leaderboard-empty";
empty.textContent = message || "暂无成绩,登录后完成一局即可上榜";
leaderboardList.appendChild(empty);
return;
}
for (const entry of leaderboard) {
const row = document.createElement("li");
row.className = "leaderboard-row";
row.classList.toggle("is-me", currentUser?.id === entry.userId);
const rank = document.createElement("span");
rank.className = "leaderboard-rank";
rank.textContent = `#${entry.rank}`;
const name = document.createElement("span");
name.className = "leaderboard-name";
name.textContent = entry.username;
const time = document.createElement("span");