-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblackjack-solver.js
More file actions
664 lines (567 loc) · 25.8 KB
/
blackjack-solver.js
File metadata and controls
664 lines (567 loc) · 25.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
// blackjack-solver.js — Exact blackjack solver using backward induction
//
// Computes mathematically optimal play by solving the full decision tree
// via dynamic programming. Every possible future card sequence and its
// optimal continuation is evaluated — no heuristics, no approximations.
const CARD_TYPES = ['2', '3', '4', '5', '6', '7', '8', '9', '0', '1'];
// '0' = 10/J/Q/K (16 per deck), '1' = Ace (4 per deck), '2'-'9' = pip (4 per deck)
const CARD_VAL = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 };
// Conditional import for Node.js worker_threads (not available in browser)
// Creates a pre-warmed pool of workers that stay alive across calls
// Only on the main thread — workers skip pool creation to avoid fork bomb
let workerPool = null;
let poolJobId = 0;
try {
const wt = await import('node:worker_threads');
if (wt.isMainThread) {
const os = await import('node:os');
const numWorkers = Math.max(2, Math.ceil(os.availableParallelism() / 2));
const workerUrl = new URL('./upcard-worker.js', import.meta.url);
const pending = new Map();
workerPool = Array.from({ length: numWorkers }, () => {
const w = new wt.Worker(workerUrl);
w.on('message', (msg) => {
const job = pending.get(msg.id);
if (!job) return;
job.results.push(msg);
if (job.results.length === job.expected) {
pending.delete(msg.id);
job.resolve(job.results);
}
});
w.on('error', (err) => {
for (const [id, job] of pending) {
pending.delete(id);
job.reject(err);
}
});
return w;
});
workerPool.dispatch = (batches, solveOpts) => {
const id = ++poolJobId;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject, results: [], expected: batches.length });
for (let i = 0; i < batches.length; i++) {
workerPool[i % workerPool.length].postMessage({ id, batch: batches[i], solveOpts });
}
});
};
}
} catch {
// Browser environment — falls back to sequential
}
// ── Utilities ──────────────────────────────────────────────────────────
export function normalizeCard(card) {
card = String(card).toLowerCase();
if (['10', 'j', 'q', 'k'].includes(card)) return '0';
if (card === 'a') return '1';
return card;
}
export function normalizeCards(cards) {
return cards.map(normalizeCard);
}
function createShoe(deckCount, deadCards = {}) {
const shoe = {};
for (const c of CARD_TYPES) {
const perDeck = c === '0' ? 16 : 4;
shoe[c] = Math.max(0, deckCount * perDeck - (deadCards[c] || 0));
}
return shoe;
}
function shoeKey(shoe) {
return String.fromCharCode(
(shoe['2']|0)+1, (shoe['3']|0)+1, (shoe['4']|0)+1, (shoe['5']|0)+1, (shoe['6']|0)+1,
(shoe['7']|0)+1, (shoe['8']|0)+1, (shoe['9']|0)+1, (shoe['0']|0)+1, (shoe['1']|0)+1
);
}
function shoeTotal(shoe) {
let t = 0;
for (const c of CARD_TYPES) t += (shoe[c] || 0);
return t;
}
function drawCard(shoe, card) {
return { ...shoe, [card]: Math.max(0, (shoe[card] || 0) - 1) };
}
// Add a card to a hand, handling ace soft/hard conversion
function hit(total, softAces, card) {
let t = total, s = softAces;
if (card === '1') { t += 11; s++; }
else if (card === '0') { t += 10; }
else { t += CARD_VAL[card]; }
while (t > 21 && s > 0) { t -= 10; s--; }
return { total: t, softAces: s };
}
function handInfo(cards) {
let total = 0, softAces = 0;
for (const c of cards) {
if (c === '1') { total += 11; softAces++; }
else if (c === '0') { total += 10; }
else { total += CARD_VAL[c]; }
}
while (total > 21 && softAces > 0) { total -= 10; softAces--; }
return { total, softAces, isBlackjack: total === 21 && cards.length === 2 };
}
export function calculateBlackjackOdds(deckCount, deadCards = {}) {
const shoe = createShoe(deckCount, deadCards);
const t = shoeTotal(shoe);
const odds = {};
for (const c of CARD_TYPES) odds[c] = t > 0 ? shoe[c] / t : 0;
return odds;
}
// ── Dealer Solver ──────────────────────────────────────────────────────
// Recursively computes all possible dealer final totals.
// Returns Map<outcome, probability> where outcome in {17..26+, 'BJ', 'bust'}
function solveDealerHand(total, softAces, numCards, shoe, remaining, hitOnSoft17, memo) {
const key = String.fromCharCode(total + 256, softAces + 512, numCards + 768,
(shoe['2']|0)+1, (shoe['3']|0)+1, (shoe['4']|0)+1, (shoe['5']|0)+1, (shoe['6']|0)+1,
(shoe['7']|0)+1, (shoe['8']|0)+1, (shoe['9']|0)+1, (shoe['0']|0)+1, (shoe['1']|0)+1);
if (memo.has(key)) return memo.get(key);
const result = new Map();
if (total > 21) {
result.set('bust', 1);
} else if (total === 21 && numCards === 2) {
result.set('BJ', 1);
} else {
const isSoft = softAces > 0;
const mustHit = total < 17 || (total === 17 && isSoft && hitOnSoft17);
if (!mustHit) {
result.set(total, 1);
} else {
if (remaining <= 0) {
result.set(total, 1);
} else {
for (const c of CARD_TYPES) {
const count = shoe[c] || 0;
if (count <= 0) continue;
const prob = count / remaining;
const { total: nt, softAces: nsa } = hit(total, softAces, c);
shoe[c]--;
const sub = solveDealerHand(nt, nsa, numCards + 1, shoe, remaining - 1, hitOnSoft17, memo);
shoe[c]++;
for (const [outcome, sp] of sub) {
result.set(outcome, (result.get(outcome) || 0) + prob * sp);
}
}
}
}
}
memo.set(key, result);
return result;
}
// ── Stand EV ───────────────────────────────────────────────────────────
// Compare player's final total against dealer outcome distribution
function computeStandEV(playerTotal, isPlayerBJ, dealerOutcomes, bjPayout) {
let ev = 0;
for (const [d, prob] of dealerOutcomes) {
if (isPlayerBJ) {
// Player BJ pushes dealer BJ, beats everything else at 3:2
ev += (d === 'BJ') ? 0 : prob * bjPayout;
} else if (d === 'BJ') {
ev -= prob; // Dealer BJ beats non-BJ player
} else if (d === 'bust') {
ev += prob;
} else if (playerTotal > d) {
ev += prob;
} else if (playerTotal < d) {
ev -= prob;
}
// equal totals = push (ev += 0)
}
return ev;
}
// ── Player Solver (backward induction) ─────────────────────────────────
//
// For any hand state, recursively computes:
// EV(stand) = compare total vs dealer
// EV(hit) = sum over all cards: P(card) * optimal_EV(new state)
// EV(double) = 2 * sum over all cards: P(card) * EV(stand after 1 card)
//
// This is the key difference from blackjack-odds.js which only did
// one-step lookahead. Here, EV(hit) accounts for ALL future optimal plays.
//
// Dealer outcomes are precomputed once from the initial shoe and reused
// for all player states. For 6+ deck shoes the error is negligible (<0.01%).
// Player draw probabilities still use the exact current shoe state.
function solvePlayer(total, softAces, numCards, shoe, remaining, ctx) {
if (total > 21) return { ev: -1, action: 'bust' };
const key = String.fromCharCode(total + 256, softAces + 512, numCards + 768,
(shoe['2']|0)+1, (shoe['3']|0)+1, (shoe['4']|0)+1, (shoe['5']|0)+1, (shoe['6']|0)+1,
(shoe['7']|0)+1, (shoe['8']|0)+1, (shoe['9']|0)+1, (shoe['0']|0)+1, (shoe['1']|0)+1);
if (ctx.playerMemo.has(key)) return ctx.playerMemo.get(key);
// Use precomputed dealer outcomes (computed once from initial shoe)
const dOutcomes = ctx.dealerOutcomes;
const isBJ = total === 21 && numCards === 2 && !ctx.isSplitHand;
const sEV = computeStandEV(total, isBJ, dOutcomes, ctx.bjPayout);
// Must stand on 21, or on split aces after receiving one card
if (total === 21 || (ctx.isSplitAces && numCards >= 2)) {
const r = { ev: sEV, action: 'stand', standEV: sEV, hitEV: null, doubleEV: null };
ctx.playerMemo.set(key, r);
return r;
}
// ── Hit EV (recursive: draw card, then play optimally from new state)
let hEV = 0;
if (remaining > 0) {
for (const c of CARD_TYPES) {
const count = shoe[c] || 0;
if (count <= 0) continue;
const prob = count / remaining;
const { total: nt, softAces: nsa } = hit(total, softAces, c);
shoe[c]--;
const sub = solvePlayer(nt, nsa, numCards + 1, shoe, remaining - 1, ctx);
shoe[c]++;
hEV += prob * sub.ev;
}
}
// ── Double EV (draw exactly 1 card, forced stand, 2x bet)
let dEV = null;
if (numCards === 2 && !ctx.isSplitAces && ctx.allowDouble && remaining > 0) {
let raw = 0;
for (const c of CARD_TYPES) {
const count = shoe[c] || 0;
if (count <= 0) continue;
const prob = count / remaining;
const { total: nt } = hit(total, softAces, c);
if (nt > 21) {
raw += prob * (-1);
} else {
raw += prob * computeStandEV(nt, false, dOutcomes, ctx.bjPayout);
}
}
dEV = 2 * raw;
}
// Best action
let bestEV = sEV, bestAction = 'stand';
if (hEV > bestEV) { bestEV = hEV; bestAction = 'hit'; }
if (dEV !== null && dEV > bestEV) { bestEV = dEV; bestAction = 'double'; }
const r = { ev: bestEV, action: bestAction, standEV: sEV, hitEV: hEV, doubleEV: dEV };
ctx.playerMemo.set(key, r);
return r;
}
// ── Split Solver ───────────────────────────────────────────────────────
// Computes EV of splitting a pair. Each split hand draws one card from the
// shoe and is then played optimally. Uses independence approximation
// (both hands see the same shoe — exact for large shoes).
function solveSplitEV(splitCard, shoe, remaining, ctx) {
if (remaining <= 0) return null;
let singleEV = 0;
for (const c of CARD_TYPES) {
const count = shoe[c] || 0;
if (count <= 0) continue;
const prob = count / remaining;
const { total: ht, softAces: hs } = handInfo([splitCard, c]);
// Fresh memo for split hand (different game state)
const splitCtx = {
...ctx,
playerMemo: new Map(),
isSplitHand: true,
isSplitAces: splitCard === '1',
allowDouble: ctx.doubleAfterSplit,
};
shoe[c]--;
const result = solvePlayer(ht, hs, 2, shoe, remaining - 1, splitCtx);
shoe[c]++;
singleEV += prob * result.ev;
}
return 2 * singleEV; // Two hands, each with 1 unit bet
}
// ── Public API ─────────────────────────────────────────────────────────
export function solve(dealerUpcard, playerCards, options = {}) {
const {
deckCount = 8,
deadCards = {},
hitOnSoft17 = true,
bjPayout = 1.5,
doubleAfterSplit = true,
dealerPeeks = true, // American rules: dealer checks for BJ on Ace/10
} = options;
const dc = normalizeCard(dealerUpcard);
const pc = normalizeCards(playerCards);
// Build shoe minus visible cards (upcard + player cards)
const shoe = createShoe(deckCount, deadCards);
shoe[dc] = Math.max(0, shoe[dc] - 1);
for (const c of pc) shoe[c] = Math.max(0, shoe[c] - 1);
const dealerVal = dc === '1' ? 11 : (dc === '0' ? 10 : CARD_VAL[dc]);
const dealerSoft = dc === '1' ? 1 : 0;
const { total, softAces, isBlackjack } = handInfo(pc);
const canSplit = pc.length === 2 && pc[0] === pc[1];
// Can dealer have BJ? Only with Ace or 10-value upcard
const canBJ = dealerVal === 11 || dealerVal === 10;
const bjCard = dealerSoft > 0 ? '0' : '1'; // card that would complete BJ
// ── PEEK + CAN_BJ: dealer peeks for blackjack ──────────────────────
// When dealer shows Ace/10 and peeks (American rules), we know the hole card
// is NOT the BJ-completing type. We compute averaged dealer outcomes across
// all non-BJ hole cards, solve the player ONCE against those averaged outcomes,
// then apply a uniform -1 BJ penalty. This correctly captures the peek benefit:
// double/split bets are protected (lose only 1 unit, not 2, to dealer BJ).
//
// Note: the player doesn't know WHICH hole card was dealt, so we don't
// condition the player's shoe per hole card (that would inflate EV via
// Jensen's inequality). The player draws from the original shoe.
if (dealerPeeks && canBJ) {
const remaining = shoeTotal(shoe);
if (remaining <= 0) {
return { action: 'stand', ev: 0, handValue: total, dealerBJProb: 0,
details: { standEV: 0, hitEV: null, doubleEV: null, splitEV: null },
dealerOutcomes: {} };
}
const bjCount = shoe[bjCard] || 0;
const dealerBJProb = bjCount / remaining;
const pNoBJ = 1 - dealerBJProb;
const noBJRemaining = remaining - bjCount;
if (noBJRemaining <= 0) {
return { action: 'stand', ev: -1, handValue: total, dealerBJProb: 1,
details: { standEV: -1, hitEV: -1, doubleEV: null, splitEV: null },
dealerOutcomes: {} };
}
// Compute dealer outcome distribution averaged over all non-BJ hole cards
const avgDO = new Map();
const dealerMemo = new Map();
for (const c of CARD_TYPES) {
if (c === bjCard) continue;
const cnt = shoe[c] || 0;
if (cnt <= 0) continue;
const prob = cnt / noBJRemaining;
const { total: dt, softAces: dsa } = hit(dealerVal, dealerSoft, c);
shoe[c]--;
const dOutcomes = solveDealerHand(dt, dsa, 2, shoe, remaining - 1, hitOnSoft17, dealerMemo);
shoe[c]++;
for (const [o, sp] of dOutcomes) {
avgDO.set(o, (avgDO.get(o) || 0) + prob * sp);
}
}
// Player BJ: push vs dealer BJ, win bjPayout otherwise
if (isBlackjack) {
const ev = pNoBJ * bjPayout;
return { action: 'blackjack', ev, handValue: 'BJ', dealerBJProb,
details: { standEV: ev, hitEV: null, doubleEV: null, splitEV: null },
dealerOutcomes: Object.fromEntries(avgDO) };
}
// Solve player ONCE with original shoe against averaged dealer outcomes
const ctx = {
dealerTotal: dealerVal, dealerSoftAces: dealerSoft, hitOnSoft17, bjPayout,
dealerOutcomes: avgDO,
isSplitHand: false, isSplitAces: false,
allowDouble: true, doubleAfterSplit,
playerMemo: new Map(), dealerMemo,
};
const result = solvePlayer(total, softAces, pc.length, shoe, remaining, ctx);
let splitEVCond = null;
if (canSplit) splitEVCond = solveSplitEV(pc[0], shoe, remaining, ctx);
// Apply BJ penalty: peek protects — lose only 1 unit regardless of action
const applyBJ = (condEV) => condEV === null ? null : dealerBJProb * (-1) + pNoBJ * condEV;
const standEV = applyBJ(result.standEV);
const hitEV = applyBJ(result.hitEV);
const doubleEV = applyBJ(result.doubleEV);
const splitEV = applyBJ(splitEVCond);
// Best action (BJ penalty is uniform, so ordering matches conditioned EVs)
const bestCondAction = (splitEVCond !== null && splitEVCond > result.ev) ? 'split' : result.action;
const bestEV = bestCondAction === 'split' ? splitEV : applyBJ(result.ev);
return {
action: bestCondAction, ev: bestEV, handValue: total, dealerBJProb,
details: { standEV, hitEV, doubleEV, splitEV },
dealerOutcomes: Object.fromEntries(avgDO),
};
}
// ── STANDARD PATH (2-9 upcard, or no peek) ──────────────────────
// No BJ possible. Dealer draws hole card as part of normal play.
// Player shoe uses the "precomputed dealer outcomes" approximation
// (negligible error for 4+ deck shoes).
const remaining = shoeTotal(shoe);
const dealerMemo = new Map();
const dealerOutcomes = solveDealerHand(dealerVal, dealerSoft, 1, shoe, remaining, hitOnSoft17, dealerMemo);
if (isBlackjack) {
const ev = computeStandEV(21, true, dealerOutcomes, bjPayout);
return { action: 'blackjack', ev, handValue: 'BJ', dealerBJProb: 0,
details: { standEV: ev, hitEV: null, doubleEV: null, splitEV: null },
dealerOutcomes: Object.fromEntries(dealerOutcomes) };
}
const ctx = {
dealerTotal: dealerVal, dealerSoftAces: dealerSoft, hitOnSoft17, bjPayout,
dealerOutcomes,
isSplitHand: false, isSplitAces: false,
allowDouble: true, doubleAfterSplit,
playerMemo: new Map(), dealerMemo,
};
const result = solvePlayer(total, softAces, pc.length, shoe, remaining, ctx);
let splitEV = null;
if (canSplit) splitEV = solveSplitEV(pc[0], shoe, remaining, ctx);
let bestAction = result.action, bestEV = result.ev;
if (splitEV !== null && splitEV > bestEV) { bestAction = 'split'; bestEV = splitEV; }
return {
action: bestAction, ev: bestEV, handValue: total, dealerBJProb: 0,
details: { standEV: result.standEV, hitEV: result.hitEV, doubleEV: result.doubleEV, splitEV },
dealerOutcomes: Object.fromEntries(dealerOutcomes),
};
}
// Compute exact overall expected value by enumerating all possible initial deals
// Uses worker_threads in Node.js for parallelism; falls back to sequential in browser
export async function solveOverallEV(options = {}) {
const {
deckCount = 8,
deadCards = {},
hitOnSoft17 = true,
bjPayout = 1.5,
dealerPeeks = true,
} = options;
const baseShoe = createShoe(deckCount, deadCards);
const totalCards = shoeTotal(baseShoe);
const solveOpts = { deckCount, deadCards, hitOnSoft17, bjPayout, dealerPeeks };
// Build all combos with precomputed probabilities
const allCombos = [];
let combos = 0;
for (const dc of CARD_TYPES) {
if ((baseShoe[dc] || 0) <= 0) continue;
const p1 = baseShoe[dc] / totalCards;
const s1 = drawCard(baseShoe, dc);
const t1 = totalCards - 1;
for (let i = 0; i < CARD_TYPES.length; i++) {
const pc1 = CARD_TYPES[i];
if ((s1[pc1] || 0) <= 0) continue;
const p2 = s1[pc1] / t1;
const s2 = drawCard(s1, pc1);
const t2 = t1 - 1;
for (let j = i; j < CARD_TYPES.length; j++) {
const pc2 = CARD_TYPES[j];
if ((s2[pc2] || 0) <= 0) continue;
const p3 = s2[pc2] / t2;
let prob, n;
if (i === j) {
prob = p1 * p2 * p3;
n = 1;
} else {
// Combine both orderings: (pc1,pc2) and (pc2,pc1)
const p2r = s1[pc2] / t1;
const s2r = drawCard(s1, pc2);
const p3r = (s2r[pc1] || 0) / t2;
prob = p1 * p2 * p3 + p1 * p2r * p3r;
n = 2;
}
if (prob <= 0) continue;
allCombos.push([dc, pc1, pc2, prob, n]);
combos += n;
}
}
}
let totalEV = 0, totalProb = 0;
if (workerPool && allCombos.length > 1) {
// Parallel path: distribute combos across pre-warmed worker pool
const batches = Array.from({ length: workerPool.length }, () => []);
for (let i = 0; i < allCombos.length; i++) {
batches[i % workerPool.length].push(allCombos[i]);
}
const results = await workerPool.dispatch(batches, solveOpts);
for (const r of results) {
totalEV += r.partialEV;
totalProb += r.partialProb;
}
} else {
// Sequential fallback (browser or single combo)
for (const [dc, pc1, pc2, prob] of allCombos) {
const result = solve(dc, [pc1, pc2], solveOpts);
totalEV += prob * result.ev;
totalProb += prob;
}
}
const ev = totalProb > 0 ? totalEV / totalProb : 0;
return {
ev,
advantage: `${ev >= 0 ? '+' : ''}${(ev * 100).toFixed(4)}%`,
recommendation: ev > 0 ? 'FAVORABLE' : 'UNFAVORABLE',
details: { combinations: combos, totalProbability: totalProb },
};
}
// Generate a complete basic strategy chart
export function generateStrategyChart(options = {}) {
const dealerCards = ['2', '3', '4', '5', '6', '7', '8', '9', '0', '1'];
const chart = { hard: {}, soft: {}, pairs: {} };
// Hard totals 5-19
const hardHands = [
[5, ['2','3']], [6, ['2','4']], [7, ['2','5']], [8, ['2','6']],
[9, ['2','7']], [10, ['3','7']], [11, ['2','9']], [12, ['2','0']],
[13, ['3','0']], [14, ['4','0']], [15, ['5','0']], [16, ['6','0']],
[17, ['7','0']], [18, ['8','0']], [19, ['9','0']],
];
for (const [total, cards] of hardHands) {
chart.hard[total] = {};
for (const dc of dealerCards) {
chart.hard[total][dc] = solve(dc, cards, options).action;
}
}
// Soft totals (A+2 through A+9)
for (let pip = 2; pip <= 9; pip++) {
const label = `A${pip}`;
const cards = ['1', String(pip)];
chart.soft[label] = {};
for (const dc of dealerCards) {
chart.soft[label][dc] = solve(dc, cards, options).action;
}
}
// Pairs (2,2 through A,A)
const pairCards = ['2','3','4','5','6','7','8','9','0','1'];
const pairLabels = { '0': '10,10', '1': 'A,A' };
for (const pc of pairCards) {
const label = pairLabels[pc] || `${pc},${pc}`;
chart.pairs[label] = {};
for (const dc of dealerCards) {
chart.pairs[label][dc] = solve(dc, [pc, pc], options).action;
}
}
return chart;
}
// ── CLI ────────────────────────────────────────────────────────────────
const ACTION_SHORT = { stand: 'S', hit: 'H', double: 'D', split: 'P', blackjack: 'BJ' };
const DEALER_LABELS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A'];
export function printStrategyChart(options = {}) {
const chart = generateStrategyChart(options);
const fmtRow = (label, row) => {
const cells = ['2','3','4','5','6','7','8','9','0','1']
.map(dc => ACTION_SHORT[row[dc]] || '?');
return `${label.padStart(6)} ${cells.join(' ')}`;
};
const header = `${''.padStart(6)} ${DEALER_LABELS.map(l => l.padStart(2)).join(' ')}`;
console.log('\n=== HARD TOTALS ===');
console.log(header);
for (const total of [5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]) {
if (chart.hard[total]) console.log(fmtRow(String(total), chart.hard[total]));
}
console.log('\n=== SOFT TOTALS ===');
console.log(header);
for (let pip = 2; pip <= 9; pip++) {
const label = `A${pip}`;
if (chart.soft[label]) console.log(fmtRow(label, chart.soft[label]));
}
console.log('\n=== PAIRS ===');
console.log(header);
const pairOrder = ['2,2','3,3','4,4','5,5','6,6','7,7','8,8','9,9','10,10','A,A'];
for (const label of pairOrder) {
if (chart.pairs[label]) console.log(fmtRow(label, chart.pairs[label]));
}
}
// Run if executed directly
const isMain = typeof process !== 'undefined' && process.argv[1] &&
(process.argv[1].endsWith('blackjack-solver.js') || process.argv[1].endsWith('blackjack-solver'));
if (isMain) {
console.log('Blackjack Solver — Exact backward induction\n');
// Quick test: solve a specific hand
const testHand = solve('6', ['0', '6'], { deckCount: 8, hitOnSoft17: true });
console.log('Test: 10+6 vs dealer 6');
console.log(` Action: ${testHand.action.toUpperCase()}`);
console.log(` EV: ${(testHand.ev * 100).toFixed(4)}%`);
console.log(` Stand EV: ${(testHand.details.standEV * 100).toFixed(4)}%`);
console.log(` Hit EV: ${(testHand.details.hitEV * 100).toFixed(4)}%`);
if (testHand.details.doubleEV !== null)
console.log(` Double EV: ${(testHand.details.doubleEV * 100).toFixed(4)}%`);
console.log();
// Overall EV
console.log('Computing overall house edge (8 deck, H17)...');
const t0 = Date.now();
const overall = await solveOverallEV({ deckCount: 8, hitOnSoft17: true });
const elapsed = ((Date.now() - t0) / 1000).toFixed(1);
console.log(` Overall EV: ${overall.advantage}`);
console.log(` ${overall.recommendation}`);
console.log(` Combinations: ${overall.details.combinations}`);
console.log(` Computed in ${elapsed}s\n`);
// Strategy chart
console.log('Generating strategy chart...');
printStrategyChart({ deckCount: 8, hitOnSoft17: true });
}