-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.js
More file actions
executable file
·2209 lines (2031 loc) · 74.8 KB
/
Copy pathengine.js
File metadata and controls
executable file
·2209 lines (2031 loc) · 74.8 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
// engine.js - Texas Hold'em game engine
const { createDeck, shuffle } = require('./deck');
const { evaluateHand, compareHands, HAND_NAMES } = require('./hand-eval');
const { getAvailableNPCs, vanillaMC, rangeWeightedMC } = require('./npc');
const { decideNpcAction } = require('./npc-orchestrator');
const { estimateRange, boardConnectivity } = require('./range');
const { generateNPCChat } = require('./npc-chat');
const random = require('./random');
const { createStructuredLogger } = require('./server/logger');
const { buildSolverContext } = require('./solver-context');
const { warmStrategyTree } = require('./solver-lookup');
// Neural network NPC disabled — awaiting Deep CFR training
// const { neuralNpcDecision } = require('./npc-neural');
const { PlayerStats } = require('./player-stats');
const { NPCPsychology } = require('./npc-psychology');
const { HandHistory, Leaderboard } = require('./hand-history');
const { Tournament } = require('./tournament');
const PHASES = ['waiting', 'preflop', 'flop', 'turn', 'river', 'showdown'];
// ── Configuration Constants ──
const LOG_LEVEL = process.env.LOG_LEVEL || 'info'; // 'debug' | 'info' | 'warn' | 'error'
const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
const GAMEPLAY_TEXT_LOGS = process.env.GAMEPLAY_TEXT_LOGS === '1';
const EQUITY_SIMS = 3000; // Monte Carlo iterations for equity calculation
const NPC_DELAY_MIN = 1500; // NPC decision delay range (ms)
const NPC_DELAY_MAX = 3000;
const PRACTICE_NEXT_DELAY = 2500; // Delay before next round in practice mode (ms)
const CASH_NEXT_DELAY = 5000; // Delay before next round in cash/tournament (ms)
const PRACTICE_ACTION_TIMEOUT_MS = 18000;
const TOURNAMENT_ACTION_TIMEOUT_MS = 25000;
const CASH_IDLE_TIMEOUT_MS = 90000;
const RUNTIME_ROLLOUT_LOG_EVERY = Math.max(
1,
Number.isFinite(Number(process.env.RUNTIME_ROLLOUT_LOG_EVERY))
? Number(process.env.RUNTIME_ROLLOUT_LOG_EVERY)
: 50
);
const AUTO_PLAY_PROFILE = {
name: 'Auto Play',
style: 'balanced',
tightness: 0.56,
bluffFreq: 0.07,
aggression: 0.54,
cbetFreq: 0.58,
checkRaiseFreq: 0.08,
};
const structuredEngineLog = createStructuredLogger('engine');
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function incrementCounter(counterMap, key) {
const normalizedKey = key || 'unknown';
counterMap[normalizedKey] = (counterMap[normalizedKey] || 0) + 1;
}
class PokerGame {
constructor(id, options = {}) {
this.id = id;
this.smallBlind = options.smallBlind || 10;
this.bigBlind = options.bigBlind || 20;
this.startChips = options.startChips || 1000;
this.maxPlayers = options.maxPlayers || 8;
this.players = [];
this.deck = [];
this.communityCards = [];
this.pot = 0;
this.sidePots = [];
this.phase = 'waiting';
this.dealerIndex = 0;
this.currentPlayerIndex = 0;
this.currentBet = 0;
this.minRaise = this.bigBlind;
this.roundBets = {};
this.lastRaiserIndex = -1;
this.isRunning = false;
this.actionTimeout = null;
this.configuredActionTimeoutMs = options.actionTimeoutMs || 0;
this.actionTimeoutMs = this.configuredActionTimeoutMs || 0;
this.onUpdate = null;
this.onMessage = null;
this.npcModelConfig = options.npcModel || null;
this.solverDataDir = options.solverDataDir || null;
this.solverRootCacheDir = options.solverRootCacheDir || null;
// Player behavior tracking
this.playerStats = new PlayerStats();
this.npcPsychology = new NPCPsychology();
this.handActionHistory = {};
this.handActionLog = [];
this.handStartPlayerCount = 0;
this.handStartStacks = {};
this.preflopRaiserId = null;
this.runtimeRolloutStats = {
decisions: 0,
solverHits: 0,
modelHits: 0,
fallbacks: 0,
coveredFallbacks: 0,
lookupSources: {},
fallbackReasons: {},
solverReasons: {},
solverClassifications: {},
solverTakeoverModes: {},
latencyMsTotal: 0,
latencySamples: 0,
};
// Preflop lookup table (injected by server)
this.preflopTable = null;
// Winner tracking (authoritative, sent to client)
this.lastRoundWinnerIds = [];
this.lastRoundRefunds = [];
this.sbIndex = -1;
// Logging helpers
const suitSymbol = { hearts: '♥', diamonds: '♦', clubs: '♣', spades: '♠' };
this._card = (c) => `${c.rank}${suitSymbol[c.suit] || c.suit}`;
this._cards = (arr) => arr.map((c) => this._card(c)).join(' ');
this._logEvent = (event, data = {}, level = 'info', message = '') => {
structuredEngineLog({
level,
event,
roomId: this.id,
message,
data: {
phase: this.phase,
roundCount: this.roundCount,
pot: this.pot,
...data,
},
});
};
this._log = (msg, level = 'info') => {
if (LOG_LEVELS[level] === undefined || LOG_LEVELS[level] < LOG_LEVELS[LOG_LEVEL]) return;
if (!GAMEPLAY_TEXT_LOGS) {
if (level === 'warn' || level === 'error') {
this._logEvent('engine_diag', { detail: msg }, level, 'Engine diagnostic');
}
return;
}
const ts = new Date().toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' });
const humans =
this.players
.filter((p) => !p.isNPC)
.map((p) => p.name)
.join(',') || '-';
console.log(`[${ts}] [room:${this.id}] [players:${humans}] ${msg}`);
};
this.bbIndex = -1;
// Game mode, speed control, pause, equity state
this.gameMode = options.gameMode || 'cash'; // 'cash' | 'tournament' | 'practice'
this.speedMultiplier = 1; // 1=normal, 2=fast, 3=turbo
this.isPaused = false;
this._pausedNpcPending = false; // automated turn pending while paused
this.equityState = {}; // per-player: { freeLeft, priceLevel, unusedStreak }
this.equitySnapshots = {}; // per-player cached oracle result for unchanged board state
// Hand history & leaderboard
this.handHistory = new HandHistory();
this.leaderboard = new Leaderboard();
// Tournament mode
this.tournament = null;
this.roundCount = 0;
this.gameOver = null;
this.turnExpiresAt = null;
this.turnDurationMs = 0;
}
recordRuntimeRolloutDecision(trace, solverTrace = null) {
if (!trace || !['solver_hit', 'model_hit', 'fallback'].includes(trace.status)) return;
const stats = this.runtimeRolloutStats;
stats.decisions += 1;
if (trace.status === 'solver_hit') {
stats.solverHits += 1;
incrementCounter(stats.lookupSources, trace.lookupSource);
incrementCounter(stats.solverReasons, trace.reason);
incrementCounter(stats.solverClassifications, trace.classification);
incrementCounter(stats.solverTakeoverModes, trace.takeoverMode);
} else if (trace.status === 'model_hit') {
stats.modelHits += 1;
} else if (trace.status === 'fallback') {
stats.fallbacks += 1;
incrementCounter(stats.fallbackReasons, trace.fallbackReason || trace.reason);
if (trace.coverageStatus === 'covered_spot' || solverTrace?.classification === 'cold_load') {
stats.coveredFallbacks += 1;
}
if (solverTrace?.reason) incrementCounter(stats.solverReasons, solverTrace.reason);
if (solverTrace?.classification) {
incrementCounter(stats.solverClassifications, solverTrace.classification);
}
if (solverTrace?.lookupSource) incrementCounter(stats.lookupSources, solverTrace.lookupSource);
}
if (typeof trace.latencyMs === 'number' && Number.isFinite(trace.latencyMs)) {
stats.latencyMsTotal += trace.latencyMs;
stats.latencySamples += 1;
}
const shouldLogSummary =
stats.decisions === 1 ||
stats.decisions % RUNTIME_ROLLOUT_LOG_EVERY === 0 ||
(trace.status === 'fallback' &&
(trace.coverageStatus === 'covered_spot' || solverTrace?.classification === 'cold_load'));
if (!shouldLogSummary) return;
const averageLatencyMs =
stats.latencySamples > 0
? Math.round((stats.latencyMsTotal / stats.latencySamples) * 100) / 100
: 0;
this._logEvent(
'runtime_rollout_summary',
{
decisions: stats.decisions,
solverHits: stats.solverHits,
modelHits: stats.modelHits,
fallbacks: stats.fallbacks,
coveredFallbacks: stats.coveredFallbacks,
lookupSources: stats.lookupSources,
fallbackReasons: stats.fallbackReasons,
solverReasons: stats.solverReasons,
solverClassifications: stats.solverClassifications,
solverTakeoverModes: stats.solverTakeoverModes,
averageLatencyMs,
latestStatus: trace.status,
latestReason: trace.reason || null,
},
trace.status === 'fallback' && stats.coveredFallbacks > 0 ? 'warn' : 'info',
'Runtime-first rollout summary'
);
}
addPlayer(playerData) {
if (this.players.length >= this.maxPlayers) return null;
const player = {
id: playerData.id,
name: playerData.name,
chips: this.startChips,
holeCards: [],
bet: 0,
totalBet: 0,
folded: false,
allIn: false,
isNPC: playerData.isNPC || false,
npcProfile: playerData.npcProfile || null,
seatIndex: this.players.length,
isConnected: true,
isReady: false,
autoPlay: false,
wins: 0,
handsPlayed: 0,
};
if (!this.isRunning && this.roundCount === 0 && this.players.length > 0) {
const insertAt = random.randomInt(this.players.length + 1);
this.players.splice(insertAt, 0, player);
this.players.forEach((p, i) => (p.seatIndex = i));
} else {
this.players.push(player);
}
this._log(`📥 seated ${player.name} (${player.isNPC ? 'NPC' : 'human'}) chips:${player.chips}`);
this._logEvent(
'player_joined',
{
playerId: player.id,
playerName: this.getPublicName(player),
isNPC: player.isNPC,
seatIndex: player.seatIndex,
chips: player.chips,
},
'info',
'Player joined room'
);
return player;
}
removePlayer(playerId) {
const idx = this.players.findIndex((p) => p.id === playerId);
if (idx === -1) return;
const removed = this.players[idx];
this._log(
`📤 left ${removed.name} (${removed.isNPC ? 'NPC' : 'human'}) chips:${removed.chips}`
);
this.players.splice(idx, 1);
// Adjust dealerIndex if removed player was before or at dealer position
if (this.players.length > 0) {
if (idx < this.dealerIndex) {
this.dealerIndex--;
} else if (idx === this.dealerIndex) {
// Dealer was removed; dealerIndex now points to next player automatically
// but clamp to valid range
this.dealerIndex = this.dealerIndex % this.players.length;
}
if (this.dealerIndex >= this.players.length) {
this.dealerIndex = 0;
}
} else {
this.dealerIndex = 0;
}
this.players.forEach((p, i) => (p.seatIndex = i));
this._logEvent(
'player_left',
{
playerId: removed.id,
playerName: this.getPublicName(removed),
isNPC: removed.isNPC,
chips: removed.chips,
},
'info',
'Player left room'
);
}
addNPCs(count) {
const npcs = getAvailableNPCs(count);
const added = [];
for (const npc of npcs) {
if (this.players.length >= this.maxPlayers) break;
const player = this.addPlayer({
id: random.randomId('npc_'),
name: npc.name,
isNPC: true,
npcProfile: npc,
});
if (player) added.push(player);
}
return added;
}
getActivePlayers() {
return this.players.filter((p) => !p.folded && p.chips > 0);
}
getPlayersInHand() {
return this.players.filter((p) => !p.folded && (p.chips > 0 || p.allIn));
}
isSpectatorPlayer(player) {
return !!(player && !player.isNPC && player.folded && (!player.holeCards || player.holeCards.length === 0));
}
clearActionTimeout() {
if (this.actionTimeout) {
clearTimeout(this.actionTimeout);
this.actionTimeout = null;
}
this.turnExpiresAt = null;
this.turnDurationMs = 0;
}
getHumanActionTimeoutMs() {
if (this.configuredActionTimeoutMs > 0) return this.configuredActionTimeoutMs;
if (this.gameMode === 'practice') return PRACTICE_ACTION_TIMEOUT_MS;
if (this.gameMode === 'tournament') return TOURNAMENT_ACTION_TIMEOUT_MS;
return CASH_IDLE_TIMEOUT_MS;
}
scheduleActionTimeout() {
this.clearActionTimeout();
if (!this.isRunning || this.isPaused) return;
const current = this.players[this.currentPlayerIndex];
if (
!current ||
current.folded ||
current.allIn ||
this.isAutomatedPlayer(current) ||
current.isNPC
) {
return;
}
const timeoutMs = this.getHumanActionTimeoutMs();
this.actionTimeoutMs = timeoutMs;
this.turnDurationMs = timeoutMs;
this.turnExpiresAt = Date.now() + timeoutMs;
this.actionTimeout = setTimeout(() => {
if (!this.isRunning || this.isPaused) return;
const liveCurrent = this.players[this.currentPlayerIndex];
if (
!liveCurrent ||
liveCurrent.id !== current.id ||
liveCurrent.folded ||
liveCurrent.allIn ||
this.isAutomatedPlayer(liveCurrent)
) {
return;
}
liveCurrent.autoPlay = true;
this.emitMessage(`${this.getPublicName(liveCurrent)} timed out and switched to auto-play`);
this._log(`⏱ ${this.getPublicName(liveCurrent)} timed out -> auto-play`);
this.emitUpdate();
this.processNPCTurn();
}, timeoutMs);
if (this.actionTimeout.unref) this.actionTimeout.unref();
}
beginCurrentTurn() {
const current = this.players[this.currentPlayerIndex];
if (!current || !this.isRunning) {
this.clearActionTimeout();
this.emitUpdate();
return;
}
if (this.isAutomatedPlayer(current)) {
this.clearActionTimeout();
this.emitUpdate();
this.processNPCTurn();
return;
}
this.scheduleActionTimeout();
this.emitUpdate();
}
startRound() {
const startedAt = Number(process.hrtime.bigint()) / 1e6;
if (this.players.length < 2) return false;
this.gameOver = null;
this.clearActionTimeout();
// Remove busted players (keep NPCs by refilling them optionally)
this.players = this.players.filter((p) => p.chips > 0 || !p.isNPC);
if (this.players.filter((p) => p.chips > 0).length < 2) return false;
this.roundCount++;
// Tick equity unused counter (5 consecutive unused = price drop)
this.tickEquityStreak();
for (const p of this.players) {
this.initEquityState(p.id);
}
this.deck = shuffle(createDeck());
this.communityCards = [];
this.pot = 0;
this.sidePots = [];
this.currentBet = 0;
// Tournament: update blinds from current level
if (this.tournament && this.tournament.isActive) {
const blinds = this.tournament.getCurrentBlinds();
this.smallBlind = blinds.sb;
this.bigBlind = blinds.bb;
}
this.minRaise = this.bigBlind;
this.roundBets = {};
this.raiseCount = 0; // Raise cap: max 4 raises per betting round
this.equitySnapshots = {};
// v4: Initialize hand tracking for opponent modeling
this.handActionHistory = {};
this.handActionLog = [];
this.handStartPlayerCount = 0;
this.handStartStacks = {};
this.preflopRaiserId = null;
this.lastRoundWinnerIds = [];
this.lastRoundRefunds = [];
// Reset player states
for (const p of this.players) {
p.holeCards = [];
p.bet = 0;
p.totalBet = 0;
p.folded = p.chips <= 0;
p.allIn = false;
p.lastAction = null;
p.handsPlayed++;
}
// Move dealer
this.dealerIndex = this.dealerIndex % this.players.length;
while (this.players[this.dealerIndex].chips <= 0) {
this.dealerIndex = (this.dealerIndex + 1) % this.players.length;
}
// Post blinds — heads-up special rule: dealer posts SB
const activePlayers = this.players.filter((p) => p.chips > 0);
this.handStartPlayerCount = activePlayers.length;
this.handStartStacks = Object.fromEntries(activePlayers.map((player) => [player.id, player.chips]));
let sbIdx, bbIdx;
if (activePlayers.length === 2) {
// Heads-up: dealer IS the small blind
sbIdx = this.dealerIndex;
bbIdx = this.getNextActiveIndex(this.dealerIndex);
} else {
// 3+ players: standard order
sbIdx = this.getNextActiveIndex(this.dealerIndex);
bbIdx = this.getNextActiveIndex(sbIdx);
}
this.sbIndex = sbIdx;
this.bbIndex = bbIdx;
this.postBlind(sbIdx, this.smallBlind);
this.postBlind(bbIdx, this.bigBlind);
this.currentBet = this.bigBlind;
// Deal hole cards
for (const p of this.players) {
if (!p.folded) {
p.holeCards = [this.deck.pop(), this.deck.pop()];
}
}
this.phase = 'preflop';
// Heads-up preflop: SB (dealer) acts first
if (activePlayers.length === 2) {
this.currentPlayerIndex = sbIdx;
} else {
this.currentPlayerIndex = this.getNextActiveIndex(bbIdx);
}
this.lastRaiserIndex = bbIdx;
this.isRunning = true;
// Start tracking this hand
const activeIds = this.players.filter((p) => !p.folded).map((p) => p.id);
this.playerStats.newHand(activeIds);
for (const id of activeIds) {
this.handActionHistory[id] = [];
}
// Hand history recording
this.handHistory.startHand(
this.roundCount,
this.players.filter((p) => !p.folded),
this.dealerIndex,
sbIdx,
bbIdx,
{ sb: this.smallBlind, bb: this.bigBlind }
);
const dealer = this.players[this.dealerIndex];
const sbPlayer = this.players[sbIdx];
const bbPlayer = this.players[bbIdx];
this.emitMessage(
`🃏 Hand ${this.roundCount} starts! Dealer: ${this.players[this.dealerIndex].name}` +
(this.tournament && this.tournament.isActive
? ` | blinds ${this.smallBlind}/${this.bigBlind}`
: '')
);
this._logEvent(
'round_start',
{
durationMs: Math.round((Number(process.hrtime.bigint()) / 1e6 - startedAt) * 100) / 100,
dealer: this.getPublicName(dealer),
smallBlindPlayer: this.getPublicName(sbPlayer),
bigBlindPlayer: this.getPublicName(bbPlayer),
smallBlind: this.smallBlind,
bigBlind: this.bigBlind,
playerOrder: this.players.map((player) => ({
id: player.id,
name: this.getPublicName(player),
seatIndex: player.seatIndex,
chips: player.chips,
isNPC: player.isNPC,
})),
},
'info',
'Round started'
);
// v10: round start log
const npcNames = this.players
.filter((p) => p.isNPC)
.map((p) => p.name)
.join(', ');
this._log(`Hand ${this.roundCount} start | NPC: ${npcNames}`);
// Log deal: dealer, blinds, hole cards
this._log(
`🎰 D:${dealer.name} SB:${sbPlayer.name}(${this.smallBlind}) BB:${bbPlayer.name}(${this.bigBlind})`
);
for (const p of this.players) {
if (!p.folded && p.holeCards.length === 2) {
if (p.isNPC) {
this._log(`🃏 ${p.name}: ${this._cards(p.holeCards)}`);
} else {
this._log(`🃏 ${p.name}: [hidden]`);
}
}
}
// Reset auto-equity tracker (-1 ensures preflop push)
this._lastAutoEqCCLen = -1;
this.beginCurrentTurn();
return true;
}
postBlind(playerIdx, amount) {
const player = this.players[playerIdx];
const actual = Math.min(amount, player.chips);
player.chips -= actual;
player.bet = actual;
player.totalBet = actual;
this.pot += actual;
if (player.chips === 0) player.allIn = true;
}
getNextActiveIndex(fromIndex) {
let idx = (fromIndex + 1) % this.players.length;
let safety = 0;
while (
(this.players[idx].folded || this.players[idx].allIn || this.players[idx].chips <= 0) &&
safety < this.players.length
) {
idx = (idx + 1) % this.players.length;
safety++;
}
// If safety exhausted (all players folded/allIn), return fromIndex+1 clamped
// This prevents infinite loops and lets advanceAction handle the end-of-round
if (safety >= this.players.length) {
return (fromIndex + 1) % this.players.length;
}
return idx;
}
handleAction(playerId, action, amount = 0) {
const playerIdx = this.players.findIndex((p) => p.id === playerId);
if (playerIdx === -1 || playerIdx !== this.currentPlayerIndex) return false;
const player = this.players[playerIdx];
if (player.folded || player.allIn) return false;
const toCall = this.currentBet - player.bet;
const potBeforeAction = this.pot;
const currentBetBeforeAction = this.currentBet;
const playerBetBeforeAction = player.bet;
const chipsBeforeAction = player.chips;
// ── FIX: Action Validation ──
// If all other non-folded players are all-in, you can only call or fold.
// Raising has no meaning because nobody can respond.
const othersCanAct = this.players.filter(
(p) => p.id !== playerId && !p.folded && !p.allIn && p.chips > 0
);
if (othersCanAct.length === 0 && (action === 'raise' || action === 'allin')) {
// Force to call (or fold if they choose)
action = toCall > 0 ? 'call' : 'check';
}
let recordedAmount = 0;
switch (action) {
case 'fold':
player.folded = true;
this.emitMessage(`${this.getPublicName(player)} folds`);
recordedAmount = 0;
break;
case 'check':
if (toCall > 0) return false;
this.emitMessage(`${this.getPublicName(player)} checks`);
recordedAmount = 0;
break;
case 'call':
if (toCall <= 0) {
this.emitMessage(`${this.getPublicName(player)} checks`);
recordedAmount = 0;
action = 'check';
break;
}
const callAmount = Math.min(toCall, player.chips);
player.chips -= callAmount;
player.bet += callAmount;
player.totalBet += callAmount;
this.pot += callAmount;
if (player.chips === 0) player.allIn = true;
this.emitMessage(`${this.getPublicName(player)} calls ${callAmount}`);
recordedAmount = callAmount;
break;
case 'raise':
// Enforce raise cap (max 4 raises per betting round)
if (this.raiseCount >= 4) {
// Cap reached, convert to call
const capCall = Math.min(this.currentBet - player.bet, player.chips);
if (capCall > 0) {
player.chips -= capCall;
player.bet += capCall;
player.totalBet += capCall;
this.pot += capCall;
if (player.chips === 0) player.allIn = true;
}
this.emitMessage(`${this.getPublicName(player)} calls ${capCall} (raise cap)`);
recordedAmount = capCall;
action = 'call';
break;
}
const minRaiseTotal = this.currentBet + this.minRaise;
const maxReachableTotal = player.bet + player.chips;
if (maxReachableTotal <= this.currentBet) {
const forcedCall = Math.min(toCall, player.chips);
player.chips -= forcedCall;
player.bet += forcedCall;
player.totalBet += forcedCall;
this.pot += forcedCall;
if (player.chips === 0) player.allIn = true;
this.emitMessage(`${this.getPublicName(player)} calls ${forcedCall}`);
recordedAmount = forcedCall;
action = forcedCall > 0 ? 'call' : 'check';
break;
}
if (maxReachableTotal < minRaiseTotal) {
const shortAllInAmount = player.chips;
player.bet += shortAllInAmount;
player.totalBet += shortAllInAmount;
this.pot += shortAllInAmount;
player.chips = 0;
player.allIn = true;
if (player.bet > this.currentBet) {
const raiseIncrement = player.bet - this.currentBet;
const isFullRaise = raiseIncrement >= this.minRaise;
this.currentBet = player.bet;
if (isFullRaise) {
this.lastRaiserIndex = playerIdx;
this.minRaise = Math.max(this.bigBlind, raiseIncrement);
}
}
this.emitMessage(`${this.getPublicName(player)} all-in ${shortAllInAmount}!`);
recordedAmount = player.bet;
action = 'allin';
break;
}
this.raiseCount++;
const raiseTotal = Math.max(amount, minRaiseTotal);
const raiseAmount = Math.min(raiseTotal - player.bet, player.chips);
player.chips -= raiseAmount;
player.bet += raiseAmount;
player.totalBet += raiseAmount;
this.pot += raiseAmount;
const prevBet = this.currentBet;
this.currentBet = player.bet;
this.minRaise = Math.max(this.bigBlind, player.bet - prevBet);
this.lastRaiserIndex = playerIdx;
if (player.chips === 0) {
player.allIn = true;
this.emitMessage(`${this.getPublicName(player)} all-in ${raiseAmount}!`);
recordedAmount = player.bet;
} else {
this.emitMessage(`${this.getPublicName(player)} raises to ${player.bet}`);
recordedAmount = player.bet;
}
break;
case 'allin':
const allInAmount = player.chips;
player.bet += allInAmount;
player.totalBet += allInAmount;
this.pot += allInAmount;
player.chips = 0;
player.allIn = true;
if (player.bet > this.currentBet) {
const raiseIncrement = player.bet - this.currentBet;
const isFullRaise = raiseIncrement >= this.minRaise;
this.currentBet = player.bet;
if (isFullRaise) {
// Full raise: reopen action, all players get to act again
this.lastRaiserIndex = playerIdx;
this.minRaise = Math.max(this.bigBlind, raiseIncrement);
}
// If NOT a full raise: currentBet updates (so others know the call price)
// but lastRaiserIndex stays unchanged (doesn't reopen action for
// players who already acted — they only need to match or fold)
}
this.emitMessage(`${this.getPublicName(player)} all-in ${allInAmount}!`);
recordedAmount = player.bet;
break;
default:
return false;
}
this.clearActionTimeout();
// v4: Record action for opponent modeling
const facingRaise = toCall > 0;
const isBlind = false; // blinds are posted separately via postBlind()
this.playerStats.recordAction(playerId, this.phase, action, recordedAmount, {
facingRaise,
isBlind,
firstToAct: this.currentBet === 0,
checkedTo: this.currentBet === 0,
});
if (this.handActionHistory[playerId]) {
this.handActionHistory[playerId].push({ phase: this.phase, action, amount: recordedAmount });
}
this.handActionLog.push({
phase: this.phase,
playerId,
action,
amount: recordedAmount,
contribution: Math.max(0, player.bet - playerBetBeforeAction),
potBeforeAction,
potAfterAction: this.pot,
currentBetBeforeAction,
currentBetAfterAction: this.currentBet,
playerBetBeforeAction,
playerBetAfterAction: player.bet,
toCallBeforeAction: toCall,
chipsBeforeAction,
chipsAfterAction: player.chips,
});
// v9.5: log human player actions to server
if (!player.isNPC) {
const actStr =
action === 'raise'
? `raise ${player.bet}`
: action === 'allin'
? `all_in ${player.bet}`
: action === 'call'
? `call ${recordedAmount}`
: action;
this._log(
`👤 ${player.name}: ${actStr} (chips:${player.chips} invested:${player.totalBet} pot:${this.pot})`
);
}
// Track preflop raiser for c-bet detection
if (this.phase === 'preflop' && (action === 'raise' || action === 'allin')) {
this.preflopRaiserId = playerId;
}
// Hand history recording
const p = this.players.find((pp) => pp.id === playerId);
if (p) p.lastAction = { action, amount: recordedAmount, time: Date.now() };
this.handHistory.recordAction(
playerId,
p ? this.getPublicName(p) : '?',
this.phase,
action,
recordedAmount,
this.pot
);
this._logEvent(
'player_action',
{
playerId,
playerName: p ? this.getPublicName(p) : playerId,
action,
amount: recordedAmount,
currentBet: this.currentBet,
playerBet: p ? p.bet : 0,
playerChips: p ? p.chips : 0,
toCallAfterAction: p ? Math.max(0, this.currentBet - p.bet) : 0,
},
'info',
'Player action applied'
);
// v7: Track recent actions for self-image awareness (keep last 30)
if (p) {
if (!p._recentActions) p._recentActions = [];
p._recentActions.push({ action, phase: this.phase });
if (p._recentActions.length > 30) p._recentActions.shift();
}
// NPC chat: react to own actions
if (p && p.isNPC) {
let chatEvent = null;
if (action === 'fold') chatEvent = 'fold';
else if (action === 'allin') chatEvent = 'allin';
if (chatEvent) {
const msg = generateNPCChat(p.name, chatEvent, 0.35);
if (msg) {
const avatar = p.npcProfile?.avatar || '';
this.emitMessage(`💬 ${avatar} ${this.getPublicName(p)}: ${msg}`);
}
}
}
this.advanceAction();
return true;
}
advanceAction() {
// Check if only one player left
const activePlayers = this.getPlayersInHand();
if (activePlayers.filter((p) => !p.folded).length === 1) {
this.awardPot(activePlayers.filter((p) => !p.folded));
this.endRound();
return;
}
// Find next player who can act
let nextIdx = (this.currentPlayerIndex + 1) % this.players.length;
let safety = 0;
while (safety < this.players.length) {
const p = this.players[nextIdx];
if (!p.folded && !p.allIn && p.chips > 0) {
// Check if betting round is complete
if (nextIdx === this.lastRaiserIndex) {
// Edge case: a short all-in after us raised currentBet
// but didn't reopen action. We still need to match or fold.
if (p.bet < this.currentBet) {
break; // Let this player act (fold/call to match)
}
this.nextPhase();
return;
}
break;
}
nextIdx = (nextIdx + 1) % this.players.length;
safety++;
if (nextIdx === this.lastRaiserIndex) {
// Check if this player still needs to act
const lp = this.players[nextIdx];
if (lp.folded || lp.allIn) {
this.nextPhase();
return;
}
// If their bet < currentBet (short all-in raised the price), they must act
if (lp.bet >= this.currentBet) {
this.nextPhase();
return;
}
break;
}
}
// If all remaining players are all-in or folded
const canAct = this.players.filter((p) => !p.folded && !p.allIn && p.chips > 0);
if (canAct.length === 0) {
// Deal remaining community cards
this.dealRemainingCards();
return;
}
if (canAct.length === 1 && canAct[0].bet >= this.currentBet) {
// Preflop live blind: BB gets option to raise even if everyone limped/folded
const isBBLiveBlind =
this.phase === 'preflop' && canAct[0].seatIndex === this.bbIndex && !canAct[0].lastAction; // BB hasn't acted yet this hand
if (isBBLiveBlind) {
this.currentPlayerIndex = canAct[0].seatIndex;
this.emitUpdate();
this.processNPCTurn();
return;
}
this.nextPhase();
return;
}
this.currentPlayerIndex = nextIdx;
this.beginCurrentTurn();
}
dealRemainingCards() {
while (this.communityCards.length < 5) {
this.deck.pop(); // burn
this.communityCards.push(this.deck.pop());
}
this.phase = 'showdown';
this.showdown();
}
nextPhase() {
const phaseIdx = PHASES.indexOf(this.phase);
if (phaseIdx >= 4) {
this.phase = 'showdown';
this.showdown();
return;
}
// Reset bets for new betting round
for (const p of this.players) {
p.bet = 0;
}
this.currentBet = 0;
this.minRaise = this.bigBlind;
this.raiseCount = 0;
switch (PHASES[phaseIdx + 1]) {
case 'flop':
this.deck.pop(); // burn
this.communityCards.push(this.deck.pop(), this.deck.pop(), this.deck.pop());
this.phase = 'flop';
this.emitMessage(`── Flop ──`);
this._log(`🂠 flop: ${this._cards(this.communityCards)} (pot:${this.pot})`);
this._logEvent(
'street_advance',
{ street: 'flop', communityCards: this.communityCards.map((card) => this._card(card)) },
'info',
'Street advanced to flop'
);
break;
case 'turn':
this.deck.pop();
this.communityCards.push(this.deck.pop());
this.phase = 'turn';
this.emitMessage(`── Turn ──`);
this._log(
`🂠 turn: ${this._card(this.communityCards[3])} → ${this._cards(this.communityCards)} (pot:${this.pot})`
);
this._logEvent(
'street_advance',
{ street: 'turn', communityCards: this.communityCards.map((card) => this._card(card)) },