@wsl233/dsh-gomoku 0.0.0-stage → 0.3.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.
@@ -0,0 +1,898 @@
1
+ /* 五子棋 - AI 搜索
2
+ * negamax + alpha-beta + 迭代加深,主线程分时让出。
3
+ * 走法生成只考虑已有棋子周围 2 格内的空位,并做启发式排序。
4
+ */
5
+ window.Gomoku = window.Gomoku || {};
6
+ (function (G) {
7
+ 'use strict';
8
+
9
+ var SIZE = 19;
10
+ var DIRS = [[1, 0], [0, 1], [1, 1], [1, -1]];
11
+ var WIN = 1e9;
12
+ var INF = 1e12;
13
+ var MATE_BOUND = WIN - 1000;
14
+
15
+ /* Zobrist 双重 32 位哈希:置换表用 (hashA, hashB) 校验,降低碰撞误判。 */
16
+ var ZOB_A = new Int32Array(SIZE * SIZE * 2);
17
+ var ZOB_B = new Int32Array(SIZE * SIZE * 2);
18
+ (function initZobrist() {
19
+ var seed = 0x1a2b3c4d | 0;
20
+ function next() {
21
+ seed ^= seed << 13;
22
+ seed ^= seed >>> 17;
23
+ seed ^= seed << 5;
24
+ return seed | 0;
25
+ }
26
+ for (var i = 0; i < ZOB_A.length; i++) {
27
+ ZOB_A[i] = next();
28
+ ZOB_B[i] = next();
29
+ }
30
+ })();
31
+
32
+ var LEVELS = {
33
+ easy: {
34
+ maxDepth: 2,
35
+ budgetMs: 350,
36
+ radius: 1,
37
+ poolLimit: 8,
38
+ branchLimit: 8,
39
+ noise: 0.15,
40
+ randomTopK: 3,
41
+ randomChance: 0.5
42
+ },
43
+ medium: {
44
+ maxDepth: 4,
45
+ budgetMs: 1200,
46
+ radius: 2,
47
+ poolLimit: 0,
48
+ branchLimit: 20,
49
+ noise: 0,
50
+ randomTopK: 0,
51
+ randomChance: 0
52
+ },
53
+ hard: {
54
+ maxDepth: 12,
55
+ budgetMs: 0,
56
+ radius: 2,
57
+ poolLimit: 28,
58
+ branchLimit: 20,
59
+ noise: 0,
60
+ randomTopK: 0,
61
+ randomChance: 0,
62
+ nodeLimit: 220000,
63
+ forced: true,
64
+ useTT: true,
65
+ useKillers: true,
66
+ quiesce: true,
67
+ adaptive: true,
68
+ earlyStop: true
69
+ }
70
+ };
71
+
72
+ var ANALYSIS = {
73
+ maxDepth: 4,
74
+ budgetMs: 450,
75
+ radius: 2,
76
+ poolLimit: 0,
77
+ branchLimit: 20
78
+ };
79
+
80
+ /* 「提示」与对局页简版演示共用这套固定参数。 */
81
+ var HINT = {
82
+ maxDepth: 4,
83
+ budgetMs: 900,
84
+ radius: 2,
85
+ poolLimit: 0,
86
+ branchLimit: 20
87
+ };
88
+
89
+ var seen = new Int32Array(SIZE * SIZE);
90
+ var stampCounter = 0;
91
+
92
+ function nowMs() {
93
+ if (typeof performance !== 'undefined' && performance.now) return performance.now();
94
+ return Date.now();
95
+ }
96
+
97
+ function yieldToUI() {
98
+ return new Promise(function (resolve) {
99
+ setTimeout(resolve, 0);
100
+ });
101
+ }
102
+
103
+ /* 走法排序用的快速启发值:假设在该点落子,能形成的连续棋型分。 */
104
+ function qValue(count, open) {
105
+ if (count >= 4.5) return 4000000;
106
+ if (count >= 4) return open === 2 ? 500000 : (open === 1 ? 60000 : 0);
107
+ if (count >= 3.5) return 300000;
108
+ if (count >= 3) return open === 2 ? 20000 : (open === 1 ? 1500 : 0);
109
+ if (count >= 2.5) return 12000;
110
+ if (count >= 2) return open === 2 ? 600 : (open === 1 ? 120 : 0);
111
+ if (count >= 1.5) return 300;
112
+ if (count >= 1) return open === 2 ? 20 : 5;
113
+ return 0;
114
+ }
115
+
116
+ var lastDirCount = 0;
117
+
118
+ function dirValue(board, x, y, dx, dy, p) {
119
+ var count = 1;
120
+ var open = 0;
121
+ for (var s = -1; s <= 1; s += 2) {
122
+ var nx = x + dx * s;
123
+ var ny = y + dy * s;
124
+ var steps = 0;
125
+ while (steps < 4 && nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE &&
126
+ board[ny * SIZE + nx] === p) {
127
+ count++;
128
+ steps++;
129
+ nx += dx * s;
130
+ ny += dy * s;
131
+ }
132
+ if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE && board[ny * SIZE + nx] === 0) {
133
+ open++;
134
+ // 空一格后仍是己方:跳型的粗略加权
135
+ var gx = nx + dx * s;
136
+ var gy = ny + dy * s;
137
+ if (gx >= 0 && gx < SIZE && gy >= 0 && gy < SIZE &&
138
+ board[gy * SIZE + gx] === p) {
139
+ count += 0.5;
140
+ }
141
+ }
142
+ }
143
+ lastDirCount = count;
144
+ return qValue(count, open);
145
+ }
146
+
147
+ function quickScore(board, x, y, side) {
148
+ var own = 0;
149
+ var opp = 0;
150
+ for (var d = 0; d < 4; d++) {
151
+ var dx = DIRS[d][0];
152
+ var dy = DIRS[d][1];
153
+ own += dirValue(board, x, y, dx, dy, side);
154
+ opp += dirValue(board, x, y, dx, dy, 3 - side);
155
+ }
156
+ return own + opp * 0.9;
157
+ }
158
+
159
+ /* 生成候选空位:已有棋子周围 radius 格内,按启发值降序。
160
+ * 每项附带 win(己方立即成五)与 block(对方立即成五)标记;
161
+ * 可选的 order 提供置换表最佳着法、killer 与 history 加分。 */
162
+ function genMoves(engine, side, radius, limit, order) {
163
+ var board = engine.board;
164
+ if (engine.cellCount === 0) {
165
+ return [{ x: 9, y: 9, score: 0, win: false, block: false }];
166
+ }
167
+ stampCounter++;
168
+ var stamp = stampCounter;
169
+ var list = [];
170
+ var r = radius || 2;
171
+ var hist = order && order.hist ? order.hist[side - 1] : null;
172
+
173
+ for (var c = 0; c < engine.cellCount; c++) {
174
+ var cx = engine.cellX[c];
175
+ var cy = engine.cellY[c];
176
+ for (var dx = -r; dx <= r; dx++) {
177
+ var nx = cx + dx;
178
+ if (nx < 0 || nx >= SIZE) continue;
179
+ for (var dy = -r; dy <= r; dy++) {
180
+ var ny = cy + dy;
181
+ if (ny < 0 || ny >= SIZE) continue;
182
+ var i = ny * SIZE + nx;
183
+ if (board[i] !== 0 || seen[i] === stamp) continue;
184
+ seen[i] = stamp;
185
+ var own = 0;
186
+ var opp = 0;
187
+ var win = false;
188
+ var block = false;
189
+ for (var d = 0; d < 4; d++) {
190
+ var ddx = DIRS[d][0];
191
+ var ddy = DIRS[d][1];
192
+ own += dirValue(board, nx, ny, ddx, ddy, side);
193
+ if (lastDirCount >= 5) win = true;
194
+ opp += dirValue(board, nx, ny, ddx, ddy, 3 - side);
195
+ if (lastDirCount >= 5) block = true;
196
+ }
197
+ var value = own + opp * 0.9;
198
+ if (order) {
199
+ if (order.tt && order.tt.x === nx && order.tt.y === ny) {
200
+ value += 1e9;
201
+ } else if (order.k1 && order.k1.x === nx && order.k1.y === ny) {
202
+ value += 400000;
203
+ } else if (order.k2 && order.k2.x === nx && order.k2.y === ny) {
204
+ value += 300000;
205
+ }
206
+ if (hist && hist[i]) value += Math.min(200000, hist[i] * 20);
207
+ }
208
+ list.push({ x: nx, y: ny, score: value, win: win, block: block });
209
+ }
210
+ }
211
+ }
212
+
213
+ list.sort(function (a, b) { return b.score - a.score; });
214
+ if (limit && list.length > limit) {
215
+ var kept = list.slice(0, limit);
216
+ // 截断不能丢掉立即成五/必须挡点,否则浅层会误判。
217
+ for (var q = limit; q < list.length; q++) {
218
+ if (list[q].win || list[q].block) kept.push(list[q]);
219
+ }
220
+ list = kept;
221
+ }
222
+ return list;
223
+ }
224
+
225
+ /* 主搜索入口(异步,深度层之间让出主线程)。 */
226
+ async function search(opts) {
227
+ var startTime = nowMs();
228
+ var budget = opts.budgetMs != null ? opts.budgetMs : 1000;
229
+ var hasDeadline = budget > 0;
230
+ var deadline = hasDeadline ? startTime + budget : Infinity;
231
+ var maxDepth = opts.maxDepth || 4;
232
+ var radius = opts.radius || 2;
233
+ var branchLimit = opts.branchLimit || 0;
234
+ var token = opts.token || null;
235
+ var shouldAbort = typeof opts.shouldAbort === 'function' ? opts.shouldAbort : null;
236
+ var board = new Uint8Array(opts.board);
237
+ var cells = opts.cells || [];
238
+ if (!cells.length) {
239
+ for (var ci = 0; ci < SIZE * SIZE; ci++) {
240
+ if (board[ci]) cells.push({ x: ci % SIZE, y: (ci / SIZE) | 0 });
241
+ }
242
+ }
243
+ var side = opts.side;
244
+ var engine = new G.Evaluate.Engine(board, cells);
245
+ var aborted = false;
246
+ var nodes = 0;
247
+
248
+ var forcedOn = opts.forced === true;
249
+ var useTT = !!opts.useTT;
250
+ var useKillers = !!opts.useKillers;
251
+ var quiesceOn = !!opts.quiesce;
252
+ var adaptive = !!opts.adaptive;
253
+ var earlyStop = !!opts.earlyStop;
254
+ var nodeLimit = opts.nodeLimit || 0;
255
+
256
+ /* 可选追踪:仅当调用方传入 opts.trace 时记录,正常对局不受影响。 */
257
+ var trace = opts.trace || null;
258
+ var traceCutoffLimit = 600;
259
+ var currentRootX = -1;
260
+ var currentRootY = -1;
261
+ var currentCutoffMap = null;
262
+ if (trace) {
263
+ trace.depths = [];
264
+ trace.cutoffs = [];
265
+ trace.cutoffCount = 0;
266
+ trace.truncated = false;
267
+ trace.aborted = false;
268
+ /* 以下字段只用于演示页展示新机制,不影响搜索决策。 */
269
+ trace.ttProbes = 0;
270
+ trace.ttHits = 0;
271
+ trace.ttStores = 0;
272
+ trace.qNodes = 0;
273
+ trace.forcedNodes = 0;
274
+ trace.forcedRoot = { win: false, block: false, loss: false };
275
+ trace.adaptive = { cap: maxDepth, reason: 'off' };
276
+ trace.stopReason = 'start';
277
+ trace.earlyStopped = false;
278
+ trace.proven = false;
279
+ trace.searchMaxDepth = maxDepth;
280
+ trace.mech = {
281
+ forced: forcedOn,
282
+ tt: useTT,
283
+ killers: useKillers,
284
+ quiesce: quiesceOn,
285
+ adaptive: adaptive,
286
+ earlyStop: earlyStop
287
+ };
288
+ }
289
+
290
+ var rootMoves = genMoves(engine, side, radius, opts.poolLimit || 0);
291
+ if (rootMoves.length === 0) {
292
+ var emptyRes = {
293
+ move: null, score: 0, depth: 0, rootValues: [], proven: false,
294
+ elapsed: nowMs() - startTime, nodes: 0
295
+ };
296
+ if (trace) emptyRes.trace = trace;
297
+ return emptyRes;
298
+ }
299
+ var fallbackMove = rootMoves[0];
300
+
301
+ /* ---------- 置换表 / killer / history / Zobrist ---------- */
302
+ var TT_LIMIT = 200000;
303
+ var TT_EXACT = 0;
304
+ var TT_LOWER = 1;
305
+ var TT_UPPER = 2;
306
+ var tt = useTT ? new Map() : null;
307
+ var ttCount = 0;
308
+ var killers = [];
309
+ var history = [new Int32Array(SIZE * SIZE), new Int32Array(SIZE * SIZE)];
310
+ var hashA = 0;
311
+ var hashB = 0;
312
+ for (var hi = 0; hi < SIZE * SIZE; hi++) {
313
+ var hv = board[hi];
314
+ if (hv) {
315
+ var hk = hi * 2 + (hv - 1);
316
+ hashA ^= ZOB_A[hk];
317
+ hashB ^= ZOB_B[hk];
318
+ }
319
+ }
320
+
321
+ function applyMove(x, y, color) {
322
+ engine.make(x, y, color);
323
+ var k = (y * SIZE + x) * 2 + (color - 1);
324
+ hashA ^= ZOB_A[k];
325
+ hashB ^= ZOB_B[k];
326
+ }
327
+
328
+ function revertMove(x, y, color) {
329
+ engine.unmake(x, y);
330
+ var k = (y * SIZE + x) * 2 + (color - 1);
331
+ hashA ^= ZOB_A[k];
332
+ hashB ^= ZOB_B[k];
333
+ }
334
+
335
+ function ttProbe(depth, alpha, beta, ply) {
336
+ if (!useTT) return null;
337
+ if (trace) trace.ttProbes++;
338
+ var bucket = tt.get(hashA >>> 0);
339
+ if (!bucket) return null;
340
+ var e = bucket.get(hashB >>> 0);
341
+ if (!e || e.depth < depth) return null;
342
+ if (trace) trace.ttHits++;
343
+ var s = e.score;
344
+ if (s >= MATE_BOUND) s -= ply;
345
+ else if (s <= -MATE_BOUND) s += ply;
346
+ if (e.flag === TT_EXACT) return { score: s, best: e.best };
347
+ if (e.flag === TT_LOWER && s >= beta) return { score: s, best: e.best };
348
+ if (e.flag === TT_UPPER && s <= alpha) return { score: s, best: e.best };
349
+ return { best: e.best };
350
+ }
351
+
352
+ function ttStore(depth, score, flag, best, ply) {
353
+ if (!useTT) return;
354
+ var s = score;
355
+ if (s >= MATE_BOUND) s += ply;
356
+ else if (s <= -MATE_BOUND) s -= ply;
357
+ var ka = hashA >>> 0;
358
+ var kb = hashB >>> 0;
359
+ var bucket = tt.get(ka);
360
+ if (!bucket) {
361
+ bucket = new Map();
362
+ tt.set(ka, bucket);
363
+ }
364
+ var old = bucket.get(kb);
365
+ if (old && old.depth > depth) return;
366
+ bucket.set(kb, {
367
+ depth: depth,
368
+ score: s,
369
+ flag: flag,
370
+ best: best ? { x: best.x, y: best.y } : null
371
+ });
372
+ if (trace) trace.ttStores++;
373
+ ttCount++;
374
+ if (ttCount > TT_LIMIT) {
375
+ tt.clear();
376
+ ttCount = 0;
377
+ }
378
+ }
379
+
380
+ function abortRequested() {
381
+ return !!(shouldAbort && shouldAbort());
382
+ }
383
+
384
+ function timeUp() {
385
+ return (hasDeadline && nowMs() > deadline) ||
386
+ (nodeLimit > 0 && nodes >= nodeLimit) ||
387
+ abortRequested();
388
+ }
389
+
390
+ function threatInfo(moves) {
391
+ var win = null;
392
+ var block = null;
393
+ var blockCount = 0;
394
+ for (var i = 0; i < moves.length; i++) {
395
+ var m = moves[i];
396
+ if (m.win && !win) win = m;
397
+ if (m.block) {
398
+ blockCount++;
399
+ if (!block) block = m;
400
+ }
401
+ }
402
+ return { win: win, block: block, blockCount: blockCount };
403
+ }
404
+
405
+ /* 叶子强制延伸:只追立即成五/必须挡点,最多 6 层,避免战术视野截断。 */
406
+ function quiesce(alpha, beta, toMove, ply, qleft) {
407
+ if (trace) trace.qNodes++;
408
+ if ((++nodes & 1023) === 0 && timeUp()) {
409
+ aborted = true;
410
+ return 0;
411
+ }
412
+ var moves = genMoves(engine, toMove, 1, 16, null);
413
+ var info = threatInfo(moves);
414
+ if (info.win) return WIN - ply;
415
+ if (info.blockCount >= 2) return -WIN + ply + 1;
416
+ if (info.blockCount === 1 && qleft > 0) {
417
+ var b = info.block;
418
+ applyMove(b.x, b.y, toMove);
419
+ var v = WIN - ply;
420
+ if (!G.Board.hasFive(engine.board, b.x, b.y, toMove)) {
421
+ v = -quiesce(-beta, -alpha, 3 - toMove, ply + 1, qleft - 1);
422
+ }
423
+ revertMove(b.x, b.y, toMove);
424
+ if (aborted) return 0;
425
+ return v;
426
+ }
427
+ var ev = engine.value();
428
+ return toMove === 1 ? ev : -ev;
429
+ }
430
+
431
+ function negamax(depth, alpha, beta, toMove, ply, pvOut) {
432
+ if ((++nodes & 1023) === 0 && timeUp()) {
433
+ aborted = true;
434
+ return 0;
435
+ }
436
+ if (depth <= 0) {
437
+ var ev = engine.value();
438
+ if (quiesceOn && Math.abs(ev) >= 90000) {
439
+ return quiesce(alpha, beta, toMove, ply, 6);
440
+ }
441
+ return toMove === 1 ? ev : -ev;
442
+ }
443
+
444
+ var alphaOrig = alpha;
445
+ var betaOrig = beta;
446
+ var ttBest = null;
447
+ if (useTT) {
448
+ var probe = ttProbe(depth, alpha, beta, ply);
449
+ if (probe) {
450
+ if (probe.score !== undefined) return probe.score;
451
+ ttBest = probe.best;
452
+ }
453
+ }
454
+
455
+ var limit = depth >= 2 ? branchLimit : (depth === 1 ? 8 : 0);
456
+ var kk = useKillers ? killers[ply] : null;
457
+ var order = null;
458
+ if (useTT || useKillers) {
459
+ order = {
460
+ tt: ttBest,
461
+ k1: kk ? kk[0] : null,
462
+ k2: kk ? kk[1] : null,
463
+ hist: history
464
+ };
465
+ }
466
+ var moves = genMoves(engine, toMove, radius, limit, order);
467
+ if (moves.length === 0) return 0;
468
+
469
+ if (forcedOn) {
470
+ var info = threatInfo(moves);
471
+ if (trace && (info.win || info.blockCount > 0)) trace.forcedNodes++;
472
+ if (info.win) {
473
+ if (trace && pvOut) {
474
+ pvOut.length = 0;
475
+ pvOut.push({ x: info.win.x, y: info.win.y });
476
+ }
477
+ return WIN - ply;
478
+ }
479
+ if (info.blockCount >= 2) {
480
+ if (trace && pvOut) pvOut.length = 0;
481
+ return -WIN + ply + 1;
482
+ }
483
+ if (info.blockCount === 1) moves = [info.block];
484
+ }
485
+
486
+ var best = -INF;
487
+ var bestMove = null;
488
+ var localPv = trace ? [] : null;
489
+ for (var i = 0; i < moves.length; i++) {
490
+ var m = moves[i];
491
+ applyMove(m.x, m.y, toMove);
492
+ var v;
493
+ var childPv = trace ? [] : null;
494
+ if (G.Board.hasFive(engine.board, m.x, m.y, toMove)) {
495
+ v = WIN - ply;
496
+ } else {
497
+ v = -negamax(depth - 1, -beta, -alpha, 3 - toMove, ply + 1, childPv);
498
+ }
499
+ revertMove(m.x, m.y, toMove);
500
+ if (aborted) return 0;
501
+ if (v > best) {
502
+ best = v;
503
+ bestMove = m;
504
+ if (trace) {
505
+ localPv.length = 0;
506
+ localPv.push({ x: m.x, y: m.y });
507
+ for (var k = 0; k < childPv.length; k++) localPv.push(childPv[k]);
508
+ }
509
+ }
510
+ if (best > alpha) alpha = best;
511
+ if (alpha >= beta) {
512
+ if (useKillers) {
513
+ var kl = killers[ply] || (killers[ply] = []);
514
+ if (!kl[0] || kl[0].x !== m.x || kl[0].y !== m.y) {
515
+ kl[1] = kl[0];
516
+ kl[0] = { x: m.x, y: m.y };
517
+ }
518
+ }
519
+ var hcell = m.y * SIZE + m.x;
520
+ var htab = history[toMove - 1];
521
+ htab[hcell] += depth * depth;
522
+ if (htab[hcell] > 500000) htab[hcell] = 500000;
523
+ if (trace) {
524
+ trace.cutoffCount++;
525
+ if (currentCutoffMap) {
526
+ var ck = currentRootX + ',' + currentRootY;
527
+ currentCutoffMap[ck] = (currentCutoffMap[ck] || 0) + 1;
528
+ }
529
+ if (trace.cutoffs.length < traceCutoffLimit) {
530
+ trace.cutoffs.push({
531
+ rootX: currentRootX,
532
+ rootY: currentRootY,
533
+ ply: ply,
534
+ depth: depth,
535
+ x: m.x,
536
+ y: m.y,
537
+ alpha: alpha,
538
+ beta: beta
539
+ });
540
+ } else {
541
+ trace.truncated = true;
542
+ }
543
+ }
544
+ break;
545
+ }
546
+ }
547
+
548
+ var flag = TT_EXACT;
549
+ if (best <= alphaOrig) flag = TT_UPPER;
550
+ else if (best >= betaOrig) flag = TT_LOWER;
551
+ ttStore(depth, best, flag, bestMove, ply);
552
+
553
+ if (trace && pvOut) {
554
+ pvOut.length = 0;
555
+ for (var q = 0; q < localPv.length; q++) pvOut.push(localPv[q]);
556
+ }
557
+ return best;
558
+ }
559
+
560
+ function orderedRootMoves() {
561
+ if (!prevValues) return rootMoves.slice();
562
+ var map = {};
563
+ for (var i = 0; i < prevValues.length; i++) {
564
+ map[prevValues[i].x + ',' + prevValues[i].y] = prevValues[i].score;
565
+ }
566
+ var arr = rootMoves.slice();
567
+ arr.sort(function (a, b) {
568
+ var sa = map[a.x + ',' + a.y];
569
+ var sb = map[b.x + ',' + b.y];
570
+ if (sa === undefined) sa = -INF;
571
+ if (sb === undefined) sb = -INF;
572
+ return sb - sa;
573
+ });
574
+ return arr;
575
+ }
576
+
577
+ async function searchRoot(depth) {
578
+ var moves = orderedRootMoves();
579
+ var values = [];
580
+ var alpha = -INF;
581
+ var best = null;
582
+ var bestScore = -INF;
583
+ var rootPv = [];
584
+ var nodesBeforeDepth = nodes;
585
+ var cutoffsBeforeDepth = trace ? trace.cutoffCount : 0;
586
+ var cutoffByRoot = trace ? {} : null;
587
+ currentCutoffMap = cutoffByRoot;
588
+
589
+ for (var i = 0; i < moves.length; i++) {
590
+ var m = moves[i];
591
+ currentRootX = m.x;
592
+ currentRootY = m.y;
593
+ var nodesBeforeMove = nodes;
594
+ applyMove(m.x, m.y, side);
595
+ var v;
596
+ var childPv = trace ? [] : null;
597
+ if (G.Board.hasFive(engine.board, m.x, m.y, side)) {
598
+ v = WIN;
599
+ } else {
600
+ v = -negamax(depth - 1, -INF, -alpha, 3 - side, 1, childPv);
601
+ }
602
+ revertMove(m.x, m.y, side);
603
+ if (aborted) {
604
+ currentCutoffMap = null;
605
+ return { aborted: true };
606
+ }
607
+
608
+ var entry = { x: m.x, y: m.y, score: v };
609
+ if (trace) entry.nodes = nodes - nodesBeforeMove;
610
+ values.push(entry);
611
+ if (v > bestScore) {
612
+ bestScore = v;
613
+ best = m;
614
+ if (trace) {
615
+ rootPv = [{ x: m.x, y: m.y }];
616
+ for (var p = 0; p < childPv.length; p++) rootPv.push(childPv[p]);
617
+ }
618
+ }
619
+ if (v > alpha) alpha = v;
620
+
621
+ if ((i & 3) === 3) {
622
+ if (opts.onProgress) {
623
+ opts.onProgress({
624
+ depth: depth,
625
+ maxDepth: searchMaxDepth,
626
+ best: best,
627
+ score: bestScore,
628
+ elapsed: nowMs() - startTime,
629
+ partial: true
630
+ });
631
+ }
632
+ await yieldToUI();
633
+ if (token && token.cancelled) {
634
+ currentCutoffMap = null;
635
+ return { cancelled: true };
636
+ }
637
+ if (abortRequested()) {
638
+ aborted = true;
639
+ currentCutoffMap = null;
640
+ return { aborted: true };
641
+ }
642
+ if ((hasDeadline && nowMs() > deadline) ||
643
+ (nodeLimit > 0 && nodes >= nodeLimit)) {
644
+ aborted = true;
645
+ currentCutoffMap = null;
646
+ return { aborted: true };
647
+ }
648
+ }
649
+ }
650
+ currentCutoffMap = null;
651
+ return {
652
+ values: values,
653
+ best: best,
654
+ score: bestScore,
655
+ depth: depth,
656
+ pv: rootPv,
657
+ nodes: nodes - nodesBeforeDepth,
658
+ cutoffs: trace ? trace.cutoffCount - cutoffsBeforeDepth : 0,
659
+ cutoffByRoot: cutoffByRoot
660
+ };
661
+ }
662
+
663
+ /* ---------- 根局面:强制着法 / 自适应深度 ---------- */
664
+ var rootInfo = threatInfo(rootMoves);
665
+ var forcedResult = null;
666
+ var forcedBlock = false;
667
+ if (forcedOn) {
668
+ if (rootInfo.win) {
669
+ if (trace) trace.forcedRoot.win = true;
670
+ forcedResult = {
671
+ best: rootInfo.win,
672
+ score: WIN,
673
+ values: [{ x: rootInfo.win.x, y: rootInfo.win.y, score: WIN }],
674
+ proven: true
675
+ };
676
+ } else if (rootInfo.blockCount >= 2) {
677
+ if (trace) trace.forcedRoot.loss = true;
678
+ var lossValues = [];
679
+ for (var li = 0; li < rootMoves.length; li++) {
680
+ lossValues.push({ x: rootMoves[li].x, y: rootMoves[li].y, score: -WIN + 1 });
681
+ }
682
+ forcedResult = {
683
+ best: fallbackMove,
684
+ score: -WIN + 1,
685
+ values: lossValues,
686
+ proven: true
687
+ };
688
+ } else if (rootInfo.blockCount === 1) {
689
+ if (trace) trace.forcedRoot.block = true;
690
+ rootMoves = [rootInfo.block];
691
+ fallbackMove = rootMoves[0];
692
+ forcedBlock = true;
693
+ }
694
+ }
695
+
696
+ var searchMaxDepth = maxDepth;
697
+ if (adaptive && !forcedResult) {
698
+ var hot = 0;
699
+ for (var ai = 0; ai < rootMoves.length; ai++) {
700
+ if (rootMoves[ai].score >= 20000) hot++;
701
+ }
702
+ var cap;
703
+ var capReason;
704
+ /* 只有一个必挡点时,落点已经被迫唯一,深搜只影响评估,不做长考。 */
705
+ if (forcedBlock) {
706
+ cap = 4;
707
+ capReason = 'forced-block';
708
+ } else if (engine.cellCount <= 2) {
709
+ cap = 4;
710
+ capReason = 'opening';
711
+ } else if (hot === 0) {
712
+ cap = 6;
713
+ capReason = 'quiet';
714
+ } else if (hot >= 3) {
715
+ cap = 12;
716
+ capReason = 'tactical';
717
+ } else {
718
+ cap = 9;
719
+ capReason = 'general';
720
+ }
721
+ searchMaxDepth = Math.min(maxDepth, cap);
722
+ if (trace) trace.adaptive = { cap: searchMaxDepth, reason: capReason };
723
+ } else if (trace && forcedResult) {
724
+ trace.adaptive = { cap: 0, reason: 'forced' };
725
+ trace.stopReason = 'forced';
726
+ }
727
+ if (trace) trace.searchMaxDepth = forcedResult ? 0 : searchMaxDepth;
728
+
729
+ var prevValues = null;
730
+ var bestResult = null;
731
+ var proven = false;
732
+ var prevBest = null;
733
+ var prevScore = 0;
734
+ var stableLayers = 0;
735
+
736
+ if (!forcedResult) {
737
+ for (var d = 2; d <= searchMaxDepth; d++) {
738
+ if (token && token.cancelled) return null;
739
+ if (timeUp()) {
740
+ aborted = true;
741
+ if (trace) {
742
+ trace.aborted = true;
743
+ trace.stopReason = abortRequested() ? 'abort'
744
+ : (nodeLimit > 0 && nodes >= nodeLimit ? 'nodes' : 'budget');
745
+ }
746
+ break;
747
+ }
748
+
749
+ var r = await searchRoot(d);
750
+ if (r.cancelled) return null;
751
+ if (token && token.cancelled) return null;
752
+ if (r.aborted) {
753
+ if (trace) {
754
+ trace.aborted = true;
755
+ trace.stopReason = abortRequested() ? 'abort'
756
+ : (nodeLimit > 0 && nodes >= nodeLimit ? 'nodes' : 'budget');
757
+ }
758
+ break;
759
+ }
760
+
761
+ bestResult = r;
762
+ prevValues = r.values;
763
+ if (trace) {
764
+ trace.depths.push({
765
+ depth: r.depth,
766
+ best: r.best ? { x: r.best.x, y: r.best.y } : null,
767
+ score: r.score,
768
+ values: r.values.slice(),
769
+ pv: r.pv.slice(),
770
+ nodes: r.nodes,
771
+ elapsed: nowMs() - startTime,
772
+ cutoffs: r.cutoffs,
773
+ cutoffByRoot: r.cutoffByRoot
774
+ });
775
+ }
776
+ if (opts.onProgress) {
777
+ opts.onProgress({
778
+ depth: d,
779
+ maxDepth: searchMaxDepth,
780
+ best: r.best,
781
+ score: r.score,
782
+ elapsed: nowMs() - startTime,
783
+ partial: false
784
+ });
785
+ }
786
+ if (hasDeadline && nowMs() >= deadline) {
787
+ if (trace) {
788
+ trace.aborted = true;
789
+ trace.stopReason = 'budget';
790
+ }
791
+ break;
792
+ }
793
+
794
+ if (r.score >= MATE_BOUND || r.score <= -MATE_BOUND) {
795
+ proven = true;
796
+ if (trace) trace.stopReason = 'mate';
797
+ break;
798
+ }
799
+ if (earlyStop) {
800
+ var sameBest = !!(prevBest && r.best &&
801
+ prevBest.x === r.best.x && prevBest.y === r.best.y);
802
+ if (d >= 6 && sameBest && Math.abs(r.score - prevScore) <= 2000) {
803
+ stableLayers++;
804
+ } else {
805
+ stableLayers = 0;
806
+ }
807
+ prevBest = r.best;
808
+ prevScore = r.score;
809
+ if (stableLayers >= 2) {
810
+ if (trace) {
811
+ trace.earlyStopped = true;
812
+ trace.stopReason = 'stable';
813
+ }
814
+ break;
815
+ }
816
+ }
817
+
818
+ await yieldToUI();
819
+ if (token && token.cancelled) return null;
820
+ }
821
+ }
822
+
823
+ var chosen = fallbackMove;
824
+ var chosenScore = 0;
825
+ var chosenDepth = 0;
826
+ var rootValues = [];
827
+
828
+ if (forcedResult) {
829
+ chosen = forcedResult.best;
830
+ chosenScore = forcedResult.score;
831
+ chosenDepth = 0;
832
+ rootValues = forcedResult.values;
833
+ proven = true;
834
+ } else if (bestResult && bestResult.best) {
835
+ chosenDepth = bestResult.depth;
836
+ rootValues = bestResult.values;
837
+
838
+ var picks = [];
839
+ for (var i2 = 0; i2 < rootValues.length; i2++) {
840
+ picks.push({
841
+ x: rootValues[i2].x,
842
+ y: rootValues[i2].y,
843
+ raw: rootValues[i2].score,
844
+ adj: rootValues[i2].score
845
+ });
846
+ }
847
+ var noise = opts.noise || 0;
848
+ if (noise > 0) {
849
+ for (i2 = 0; i2 < picks.length; i2++) {
850
+ picks[i2].adj = picks[i2].raw * (1 + (Math.random() * 2 - 1) * noise);
851
+ }
852
+ }
853
+ picks.sort(function (a, b) { return b.adj - a.adj; });
854
+
855
+ var pick = picks[0];
856
+ if (opts.randomTopK && Math.random() < (opts.randomChance || 0.5)) {
857
+ var kk2 = Math.min(opts.randomTopK, picks.length);
858
+ pick = picks[Math.floor(Math.random() * kk2)];
859
+ }
860
+ chosen = { x: pick.x, y: pick.y };
861
+ chosenScore = pick.raw;
862
+ if (chosenScore >= MATE_BOUND || chosenScore <= -MATE_BOUND) proven = true;
863
+ }
864
+
865
+ var result = {
866
+ move: chosen,
867
+ score: chosenScore,
868
+ depth: chosenDepth,
869
+ rootValues: rootValues,
870
+ elapsed: nowMs() - startTime,
871
+ nodes: nodes,
872
+ aborted: aborted,
873
+ proven: proven,
874
+ maxDepth: searchMaxDepth
875
+ };
876
+ if (trace) {
877
+ trace.nodes = nodes;
878
+ trace.elapsed = result.elapsed;
879
+ trace.bestDepth = chosenDepth;
880
+ trace.maxDepth = searchMaxDepth;
881
+ trace.searchMaxDepth = forcedResult ? 0 : searchMaxDepth;
882
+ trace.proven = proven;
883
+ if (!forcedResult && trace.stopReason === 'start') trace.stopReason = 'depth';
884
+ result.trace = trace;
885
+ }
886
+ return result;
887
+ }
888
+
889
+ G.AI = {
890
+ WIN: WIN,
891
+ LEVELS: LEVELS,
892
+ ANALYSIS: ANALYSIS,
893
+ HINT: HINT,
894
+ genMoves: genMoves,
895
+ quickScore: quickScore,
896
+ search: search
897
+ };
898
+ })(window.Gomoku);