forked from Ryukaki/ThressGame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbotManager.js
More file actions
431 lines (366 loc) · 14.4 KB
/
botManager.js
File metadata and controls
431 lines (366 loc) · 14.4 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
/**
* Bot Manager -- Manages a single bot opponent for 1v1 games.
*/
const crypto = require('crypto');
const { createPlayer } = require('./gameController');
const { getBestMove, evaluateBoard } = require('./bots/botAI');
const { getHooks, getCustomMoves, getWrapMoves } = require('./mutators/ruleHooks');
const { isRuleActive } = require('./mutators/mutatorEngine');
const { COLUMNS, ROWS, getIntermediateSquares } = require('./mutators/boardUtils');
const { checkMutatorDeadlock } = require('./utils/gameLifecycle');
let botCounter = 0;
/**
* Check if a move passes through or lands on a trap square (mine, pit, death square).
* Returns true if the move is dangerous.
*/
function isTrapMove(room, move) {
if (!room.mutatorState) return false;
const mods = room.mutatorState.boardModifiers || {};
// Collect all dangerous squares
const trapSquares = new Set();
if (mods.mines) mods.mines.forEach(m => trapSquares.add(m.square));
if (mods.bottomlessPits) mods.bottomlessPits.forEach(p => trapSquares.add(p.square));
if (mods.deathSquares) {
const mc = room.mutatorState.moveCount || 0;
mods.deathSquares.forEach(d => {
if (!d.expiresAtMove || mc < d.expiresAtMove) trapSquares.add(d.square);
});
}
if (trapSquares.size === 0) return false;
// Check destination
if (trapSquares.has(move.to)) return true;
// Check intermediate squares for sliding pieces
const path = getIntermediateSquares(move.from, move.to);
for (const sq of path) {
if (trapSquares.has(sq)) return true;
}
return false;
}
/**
* Pick the best move from a pre-filtered pool using board evaluation.
* Unlike getBestMove (which queries chess.js for unfiltered moves),
* this only considers moves already validated against mutator restrictions.
*
* @param {Object} chess - Chess.js instance
* @param {Array} moves - Pre-filtered legal moves for a single source square
* @param {string} color - The bot's color ('w' or 'b')
* @returns {Object|null} Best move from the pool
*/
function getBestMoveFromPool(chess, moves, color) {
if (moves.length === 0) return { move: null, score: -Infinity };
if (moves.length === 1) return { move: moves[0], score: 0 };
let bestMove = null;
let bestScore = -Infinity;
for (const move of moves) {
let score;
// Custom moves (flags 'n') can't be evaluated by chess.js — use heuristic
if (move.flags === 'n') {
const target = chess.get(move.to);
// Simple capture value for custom moves; random baseline otherwise
const customPieceValues = { p: 100, n: 320, b: 330, r: 500, q: 900, k: 20000 };
score = target ? (customPieceValues[target.type] || 0) : Math.random() * 10;
} else {
chess.move(move);
score = evaluateBoard(chess, color) + Math.random() * 10;
chess.undo();
}
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
return { move: bestMove, score: bestScore };
}
/**
* Add a bot player to a room.
*
* @param {Object} room - GameRoom instance
* @param {string} color - The color for the bot ('w' or 'b')
*/
function addBotToRoom(room, color) {
botCounter++;
const botSocketId = `bot:${crypto.randomUUID()}`;
const botName = `Bot ${botCounter}`;
const botPlayerHash = crypto
.createHash('sha256')
.update(botSocketId)
.digest('hex')
.substring(0, 16);
const bot = createPlayer(botSocketId, botName, botPlayerHash, color, true);
room.addPlayer(bot);
console.log(`[botManager] Added ${botName} as ${color === 'w' ? 'white' : 'black'} to room ${room.roomCode}`);
return bot;
}
/**
* Schedule a bot move after a random delay.
*
* @param {Object} room - GameRoom instance
* @param {Object} io - Socket.IO server
* @param {Object} gameManager - GameManager instance
* @param {Function} handleMoveFn - The handleMove function: (io, fakeSocket, gameManager, moveData)
* @param {Function} [afterMoveFn] - Optional callback after move (e.g. botAutoMutatorResponse)
*/
function scheduleBotMove(room, io, gameManager, handleMoveFn, afterMoveFn) {
if (!room || room.status !== 'active') return;
// Determine whose turn it is
const currentTurn = room.chess.turn();
const currentPlayer = room.getPlayer(currentTurn);
// Only schedule if it's a bot's turn
if (!currentPlayer || !currentPlayer.isBot) return;
// Random delay between 2000ms and 4000ms
const delay = 2000 + Math.random() * 2000;
const timer = setTimeout(() => {
room.disconnectTimers.delete('bot_move');
performBotMove(room, io, gameManager, handleMoveFn, afterMoveFn);
}, delay);
// Store the timeout so it can be cleared if the room ends
room.disconnectTimers.set('bot_move', timer);
}
/**
* Apply active mutator restriction filters to narrow the legal move pool.
* Mirrors the restriction check in moveHandler.js so bots only pick valid moves.
*
* @param {Object} room - GameRoom instance
* @param {string} playerColor - The bot's color ('w' or 'b')
* @returns {Array} Filtered array of legal move objects
*/
function getMutatorFilteredMoves(room, playerColor) {
let legalMoves = room.chess.moves({ verbose: true });
if (!room.mutatorState || room.mutatorState.activeRules.length === 0) {
return legalMoves;
}
const restrictionRules = room.mutatorState.activeRules.filter(ar => {
const ruleHooks = getHooks(ar.rule.id);
return ruleHooks.getLegalMoveModifiers;
});
// Include custom moves before filtering so distance filters can evaluate them
const custom = getCustomMoves(room, playerColor);
for (const cm of custom) {
if (!legalMoves.some(m => m.from === cm.from && m.to === cm.to)) {
legalMoves.push({ from: cm.from, to: cm.to, flags: 'n', san: cm.to });
}
}
// Include wrap moves from Pacman Style
if (isRuleActive(room.mutatorState, 'pacman_style')) {
const wraps = getWrapMoves(room, playerColor);
for (const wm of wraps) {
if (!legalMoves.some(m => m.from === wm.from && m.to === wm.to)) {
legalMoves.push({ from: wm.from, to: wm.to, flags: 'n', san: wm.to });
}
}
}
// Sort so forced-move rules (tornado, bloodthirsty) run last and override distance filters
const FORCED_MOVE_RULES = new Set(['tornado', 'bloodthirsty']);
restrictionRules.sort((a, b) => {
const aForced = FORCED_MOVE_RULES.has(a.rule.id) ? 1 : 0;
const bForced = FORCED_MOVE_RULES.has(b.rule.id) ? 1 : 0;
return aForced - bForced;
});
for (const ar of restrictionRules) {
const ruleHooks = getHooks(ar.rule.id);
const filterFn = ruleHooks.getLegalMoveModifiers(room, playerColor);
if (filterFn) {
legalMoves = filterFn(legalMoves);
}
}
return legalMoves;
}
/**
* Execute a bot move.
*
* @param {Object} room - GameRoom instance
* @param {Object} io - Socket.IO server
* @param {Object} gameManager - GameManager instance
* @param {Function} handleMoveFn - The handleMove function: (io, fakeSocket, gameManager, moveData)
* @param {Function} [afterMoveFn] - Optional callback after move (e.g. botAutoMutatorResponse)
*/
async function performBotMove(room, io, gameManager, handleMoveFn, afterMoveFn) {
if (!room || room.status !== 'active') return;
const currentTurn = room.chess.turn();
const bot = room.getPlayer(currentTurn);
if (!bot || !bot.isBot) return;
// If there's a pending mutator state, reschedule instead of moving now
if (room.mutatorState && (room.mutatorState.pendingRPS || room.mutatorState.pendingChoice || room.mutatorState.pendingAction || room.mutatorState.pendingSecondAction)) {
scheduleBotMove(room, io, gameManager, handleMoveFn, afterMoveFn);
return;
}
// Get mutator-filtered legal moves (respects active restrictions)
let allMoves = getMutatorFilteredMoves(room, currentTurn);
if (allMoves.length === 0) {
checkMutatorDeadlock(room, io, gameManager);
return;
}
// Trap awareness: 50/50 chance to avoid trap moves (mines, pits, death squares)
if (room.mutatorState && Math.random() < 0.5) {
const safeMoves = allMoves.filter(m => !isTrapMove(room, m));
if (safeMoves.length > 0) {
allMoves = safeMoves;
}
// If all moves are traps, keep the full pool (no choice but to walk into one)
}
let selectedMove = null;
// Collect active treasure squares for bonus targeting
const treasureSquares = new Set();
if (room.mutatorState?.boardModifiers?.treasureSquares) {
for (const ts of room.mutatorState.boardModifiers.treasureSquares) {
if (ts.active) treasureSquares.add(ts.square);
}
}
// Try AI move: evaluate each legal move with board evaluation
// Only consider moves from the mutator-filtered pool
try {
const squareSet = new Set(allMoves.map(m => m.from));
let bestOverallMove = null;
let bestOverallScore = -Infinity;
for (const square of squareSet) {
const piece = room.chess.get(square);
if (!piece) continue;
const squareMoves = allMoves.filter(m => m.from === square);
const { move, score } = getBestMoveFromPool(room.chess, squareMoves, currentTurn);
if (move && score > bestOverallScore) {
bestOverallScore = score;
bestOverallMove = move;
}
}
if (bestOverallMove) {
selectedMove = bestOverallMove;
}
// Treasure chest awareness: prioritize landing on a treasure square
// unless the current best move is a capture or resolves check
if (treasureSquares.size > 0 && selectedMove) {
const isBestCapture = selectedMove.captured || (selectedMove.flags && selectedMove.flags.includes('c'));
const inCheck = room.chess.inCheck();
if (!isBestCapture && !inCheck) {
const treasureMove = allMoves.find(m => treasureSquares.has(m.to));
if (treasureMove) {
selectedMove = treasureMove;
}
}
}
} catch (err) {
console.warn('[botManager] AI move calculation failed:', err.message);
}
// Fallback to random legal move from filtered pool
if (!selectedMove) {
selectedMove = allMoves[Math.floor(Math.random() * allMoves.length)];
console.log(`[botManager] Using random fallback move: ${selectedMove.from}->${selectedMove.to}`);
}
// Create fake socket for the bot
const fakeSocket = {
id: bot.socketId,
emit: () => {},
};
try {
await handleMoveFn(io, fakeSocket, gameManager, {
from: selectedMove.from,
to: selectedMove.to,
promotion: selectedMove.promotion || undefined,
});
console.log(`[botManager] Bot ${bot.name} moved: ${selectedMove.from}->${selectedMove.to}`);
// Handle any mutator auto-responses (RPS, target selection, etc.)
if (afterMoveFn && room.mutatorState) {
setTimeout(() => afterMoveFn(room, io, gameManager), 200);
}
// Schedule next bot move if it's still a bot's turn (after the move is processed)
scheduleBotMove(room, io, gameManager, handleMoveFn, afterMoveFn);
} catch (err) {
console.error(`[botManager] Bot move execution failed:`, err.message);
}
}
/**
* Generate a random valid target for a mutator action.
* @param {Object} room - GameRoom instance
* @param {string} botColor - The bot's color ('w' or 'b')
* @param {string} choiceType - The type of choice needed
* @returns {*} The target data (square, column, row, array, etc.)
*/
function generateBotTarget(room, botColor, choiceType) {
const chess = room.chess;
const board = chess.board(); // 8x8 array
// Helper: get all squares with pieces matching criteria
function findSquares(filterFn) {
const results = [];
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
const piece = board[r][c];
const sq = COLUMNS[c] + ROWS[7 - r];
if (filterFn(piece, sq)) results.push(sq);
}
}
return results;
}
const opponentColor = botColor === 'w' ? 'b' : 'w';
switch (choiceType) {
case 'column':
return COLUMNS[Math.floor(Math.random() * 8)];
case 'row':
return ROWS[Math.floor(Math.random() * 8)];
case 'empty_square': {
const empty = findSquares((p) => !p);
return empty.length > 0 ? empty[Math.floor(Math.random() * empty.length)] : null;
}
case 'square': {
const sq = COLUMNS[Math.floor(Math.random() * 8)] + ROWS[Math.floor(Math.random() * 8)];
return sq;
}
case 'piece': {
const pieces = findSquares((p) => p && p.type !== 'k');
return pieces.length > 0 ? pieces[Math.floor(Math.random() * pieces.length)] : null;
}
case 'friendly_piece': {
const friendly = findSquares((p) => p && p.color === botColor && p.type !== 'k');
return friendly.length > 0 ? friendly[Math.floor(Math.random() * friendly.length)] : null;
}
case 'enemy_piece': {
const enemies = findSquares((p) => p && p.color === opponentColor && p.type !== 'k');
return enemies.length > 0 ? enemies[Math.floor(Math.random() * enemies.length)] : null;
}
case 'two_squares': {
const allSq = [];
for (const c of COLUMNS) for (const r of ROWS) allSq.push(c + r);
const idx1 = Math.floor(Math.random() * allSq.length);
const sq1 = allSq.splice(idx1, 1)[0];
const sq2 = allSq[Math.floor(Math.random() * allSq.length)];
return [sq1, sq2];
}
case 'two_friendly_pawns': {
const pawns = findSquares((p) => p && p.color === botColor && p.type === 'p');
if (pawns.length >= 2) {
const idx1 = Math.floor(Math.random() * pawns.length);
const sq1 = pawns.splice(idx1, 1)[0];
const sq2 = pawns[Math.floor(Math.random() * pawns.length)];
return { pawns: [sq1, sq2], bishopSquare: sq1 };
}
return null;
}
case 'two_pieces_same_column': {
// Find columns with 2+ pieces
for (const col of COLUMNS) {
const inCol = findSquares((p, sq) => p && sq[0] === col);
if (inCol.length >= 2) {
const idx1 = Math.floor(Math.random() * inCol.length);
const sq1 = inCol.splice(idx1, 1)[0];
const sq2 = inCol[Math.floor(Math.random() * inCol.length)];
return { square1: sq1, square2: sq2 };
}
}
return null;
}
case 'friendly_bishop_or_knight': {
const pieces = findSquares((p) => p && p.color === botColor && (p.type === 'b' || p.type === 'n'));
return pieces.length > 0 ? pieces[Math.floor(Math.random() * pieces.length)] : null;
}
case 'sophie': {
const friendly = findSquares((p) => p && p.color === botColor && p.type !== 'k');
return friendly.length > 0 ? friendly[Math.floor(Math.random() * friendly.length)] : null;
}
default:
return null;
}
}
module.exports = {
addBotToRoom,
scheduleBotMove,
performBotMove,
generateBotTarget,
};