-
Notifications
You must be signed in to change notification settings - Fork 4
/
basic_strategy_generator.py
748 lines (645 loc) · 40.1 KB
/
basic_strategy_generator.py
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
"""Generate basic strategy and plot it in graphs."""
from best_move import perfect_mover_cache
from shoe_generators import hilo_generator
from utils import DECK
from utils import list_range_str
from typing import Iterable, cast
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import itertools
import csv
import re
import argparse
import multiprocessing
class Hand:
"""Hold information about the hand of the player and the dealer."""
def __init__(self, cards: Iterable[int]) -> None:
"""
Save the initial cards.
:param cards: The cards the hand started with.
"""
self.cards = list(cards)
def add_card(self, card: int) -> None:
"""
Add a new card to the hand.
:param card: The new card to add for the hand (an ace is symbolised as 11).
"""
self.cards.append(card)
def value(self) -> int:
"""
Return the value of a hand.
:return: The hand's value.
"""
aces = 0
score = 0
for card in self.cards:
if card == 11:
aces += 1
score += card
while score > 21 and aces > 0:
aces -= 1
score -= 10
return score
def value_aces(self) -> tuple[int, int]:
"""
Return the value of a hand and how many aces that count as 11 it has.
:return: The hand's value and how many aces are counted as 11 (0 or 1).
"""
aces = 0
score = 0
for card in self.cards:
if card == 11:
aces += 1
score += card
while score > 21 and aces > 0:
aces -= 1
score -= 10
return score, aces
def argmax(*profits: float) -> tuple[float, str]:
"""
Return the maximum profit and the action that gets you that profit.
:param profits: The profits generated by each action.
:return: The best profit, and the best action.
"""
max_profit = max(profits)
index_to_action = {0: "s", 1: "h", 2: "d", 3: "p", 4: "u", 5: "i"}
for index, profit in enumerate(profits):
if profit == max_profit:
return max_profit, index_to_action[index]
return 0, ""
def no_ace_table_generator(cores: int = 1, card_numbers: tuple[int, ...] = (2, 3, 4), number_of_decks: int = 6,
true_count: int | None = None, shoes_to_test: int | None = None,
deck_penetration: float = .25, dealer_peeks_for_blackjack: bool = True, das: bool = True,
dealer_stands_soft_17: bool = True, can_surrender: bool = True) -> dict[int, dict[int, str]]:
"""
Generate basic strategy when we don't have an ace.
:param cores: How many cores to use in the generation of basic strategy.
:param card_numbers: Test all hand with card_numbers number of hands. (e.g. if card_numbers is (2, 3), then all hands
with 2 or 3 cards will be tested)
:param number_of_decks: The number of decks in the initial shoe.
:param true_count: The true count that we should generate basic strategy for.
Default is None which generates general basic strategy. An integer, generated deviations from basic strategy.
:param shoes_to_test: How many shoes to test when generating deviations.
:param deck_penetration: When to reshuffle the shoe. Reshuffles when cards remaining < starting cards * deck penetration.
So the shoe can't have fewer than starting cards * deck penetration cards.
:param dealer_peeks_for_blackjack: Whether the dealer peeks for blackjack.
:param das: Whether we can double after splitting.
:param dealer_stands_soft_17: Whether the dealer stands on soft 17.
:param can_surrender: Whether the game rules allow surrendering.
:return: The basic strategy table, to be saved and/or plotted.
"""
shoe = DECK * number_of_decks
shoe.sort()
arguments = []
all_combinations = []
possible_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for card_number in card_numbers:
all_combinations_card_number = list(itertools.combinations_with_replacement(possible_cards, card_number))
all_combinations_card_number = list(map(lambda comb: tuple(sorted(comb)), all_combinations_card_number))
all_combinations += all_combinations_card_number
set_combinations = dict.fromkeys(all_combinations_card_number)
for cards in set_combinations:
hand_value = Hand(cards).value()
if hand_value > 21 or hand_value < 4:
continue
for dealer_up_card in range(2, 12):
if true_count is None:
default_shoe = shoe.copy()
for card in cards + (dealer_up_card,):
default_shoe.remove(card)
decks = [default_shoe]
else:
decks = []
for _ in range(shoes_to_test if shoes_to_test else 1):
decks.append(hilo_generator(true_count, number_of_decks, deck_penetration,
list(cards) + [dealer_up_card]))
for example_shoe in decks:
shoe_copy = example_shoe.copy()
arguments.append((cards, dealer_up_card, tuple(shoe_copy), card_number <= 2,
card_number == 2, can_surrender and card_number == 2, 0,
dealer_peeks_for_blackjack, das, dealer_stands_soft_17, True))
data_table = {player_total: {dealer_up_card: {
key: [0., 0., 0., 0., 0., 0., 0.] for key in ["all", "double", "surrender", "insurance"]}
for dealer_up_card in range(2, 12)} for player_total in range(4, 22)}
with multiprocessing.Pool(processes=cores) as pool:
for argument, profits_not_cast in zip(arguments, pool.starmap(perfect_mover_cache, arguments)):
profits = cast(tuple[float, ...], profits_not_cast)
cards = argument[0]
dealer_up_card = argument[1]
hand = Hand(cards)
hand_value, hand_aces = hand.value_aces()
card_number = len(cards)
print(f"Player cards: {cards}, Dealer up card: {dealer_up_card}, No ace profits: {profits}")
data_table[hand_value][dealer_up_card]["all"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][2] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][3] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][4] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][5] -= 1000 * all_combinations.count(cards)
if card_number == 2:
data_table[hand_value][dealer_up_card]["double"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][3] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][4] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][5] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][3] += profits[3] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][4] += profits[4] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][5] -= 1000 * all_combinations.count(cards)
if dealer_up_card == 11 and card_number == 2:
data_table[hand_value][dealer_up_card]["insurance"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][3] += profits[3] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][4] += profits[4] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][5] += profits[5] * all_combinations.count(cards)
print(f"No ace data table:\n{data_table}")
clean_table = {player_total: {dealer_up_card: "" for dealer_up_card in range(2, 12)} for player_total in range(4, 22)}
for player_total in range(4, 22):
for dealer_up_card in range(2, 12):
print(f"Player total: {player_total}, Dealer up card: {dealer_up_card}, "
f"No ace data row: {data_table[player_total][dealer_up_card]}")
clean_text = ""
if data_table[player_total][dealer_up_card]["insurance"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["insurance"][6] for profit in
data_table[player_total][dealer_up_card]["insurance"][:6]]
if profit_line[5] > 0:
clean_text += f"i ({round(profit_line[5], 2)}) "
if data_table[player_total][dealer_up_card]["surrender"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["surrender"][6] for profit in
data_table[player_total][dealer_up_card]["surrender"][:6]]
max_profit, max_action = argmax(*profit_line[:5])
if max_action == "u":
clean_text += f"u ({round(max_profit, 2)}) "
if data_table[player_total][dealer_up_card]["double"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["double"][6] for profit in
data_table[player_total][dealer_up_card]["double"][:6]]
max_profit, max_action = argmax(*profit_line[:4])
if max_action == "d":
clean_text += f"d ({round(max_profit, 2)}) "
profit_line = [profit / max(data_table[player_total][dealer_up_card]["all"][6], 1) for profit in
data_table[player_total][dealer_up_card]["all"][:6]]
max_profit, max_action = argmax(*profit_line[:2])
clean_text += f"{max_action} ({round(max_profit, 2)}) "
clean_table[player_total][dealer_up_card] = clean_text.strip()
return clean_table
def ace_table_generator(cores: int = 1, card_numbers: tuple[int, ...] = (2, 3, 4), number_of_decks: int = 6,
true_count: int | None = None, shoes_to_test: int | None = None,
deck_penetration: float = .25, dealer_peeks_for_blackjack: bool = True, das: bool = True,
dealer_stands_soft_17: bool = True, can_surrender: bool = True) -> dict[int, dict[int, str]]:
"""
Generate basic strategy when we have an ace.
:param cores: How many cores to use in the generation of basic strategy.
:param card_numbers: Test all hand with card_numbers number of hands. (e.g. if card_numbers is (2, 3), then all hands
with 2 or 3 cards will be tested)
:param number_of_decks: The number of decks in the initial shoe.
:param true_count: The true count that we should generate basic strategy for.
Default is None which generates general basic strategy. An integer, generated deviations from basic strategy.
:param shoes_to_test: How many shoes to test when generating deviations.
:param deck_penetration: When to reshuffle the shoe. Reshuffles when cards remaining < starting cards * deck penetration.
So the shoe can't have fewer than starting cards * deck penetration cards.
:param dealer_peeks_for_blackjack: Whether the dealer peeks for blackjack.
:param das: Whether we can double after splitting.
:param dealer_stands_soft_17: Whether the dealer stands on soft 17.
:param can_surrender: Whether the game rules allow surrendering.
:return: The basic strategy table, to be saved and/or plotted.
"""
shoe = DECK * number_of_decks
shoe.sort()
arguments = []
all_combinations = []
possible_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
for card_number in card_numbers:
all_combinations_card_number = list(itertools.combinations_with_replacement(possible_cards, card_number - 1))
all_combinations_card_number = list(map(lambda comb: comb + (11,), all_combinations_card_number))
all_combinations_card_number = list(map(lambda comb: tuple(sorted(comb)), all_combinations_card_number))
all_combinations += all_combinations_card_number
set_combinations = dict.fromkeys(all_combinations_card_number)
for cards in set_combinations:
hand = Hand(cards)
hand_value, hand_aces = hand.value_aces()
if hand_value > 21 or hand_value < 12 or hand_aces == 0:
continue
for dealer_up_card in range(2, 12):
if true_count is None:
default_shoe = shoe.copy()
for card in cards + (dealer_up_card,):
default_shoe.remove(card)
decks = [default_shoe]
else:
decks = []
for _ in range(shoes_to_test if shoes_to_test else 1):
decks.append(hilo_generator(true_count, number_of_decks, deck_penetration,
list(cards) + [dealer_up_card]))
for example_shoe in decks:
shoe_copy = example_shoe.copy()
arguments.append((cards, dealer_up_card, tuple(shoe_copy), card_number <= 2,
card_number == 2, can_surrender and card_number == 2, 0,
dealer_peeks_for_blackjack, das, dealer_stands_soft_17, True))
data_table = {player_total: {dealer_up_card: {
key: [0., 0., 0., 0., 0., 0., 0.] for key in ["all", "double", "surrender", "insurance"]}
for dealer_up_card in range(2, 12)} for player_total in range(12, 22)}
with multiprocessing.Pool(processes=cores) as pool:
for argument, profits_not_cast in zip(arguments, pool.starmap(perfect_mover_cache, arguments)):
profits = cast(tuple[float, ...], profits_not_cast)
cards = argument[0]
dealer_up_card = argument[1]
hand = Hand(cards)
hand_value, hand_aces = hand.value_aces()
card_number = len(cards)
print(f"Player cards: {cards}, Dealer up card: {dealer_up_card}, Ace profits: {profits}")
data_table[hand_value][dealer_up_card]["all"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][2] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][3] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][4] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["all"][5] -= 1000 * all_combinations.count(cards)
if card_number == 2:
data_table[hand_value][dealer_up_card]["double"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][3] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][4] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["double"][5] -= 1000 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][3] += profits[3] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][4] += profits[4] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["surrender"][5] -= 1000 * all_combinations.count(cards)
if dealer_up_card == 11 and card_number == 2:
data_table[hand_value][dealer_up_card]["insurance"][6] += 1 * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][0] += profits[0] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][1] += profits[1] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][2] += profits[2] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][3] += profits[3] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][4] += profits[4] * all_combinations.count(cards)
data_table[hand_value][dealer_up_card]["insurance"][5] += profits[5] * all_combinations.count(cards)
print(f"Ace data table:\n{data_table}")
clean_table = {player_total: {dealer_up_card: "" for dealer_up_card in range(2, 12)} for player_total in range(12, 22)}
for player_total in range(12, 22):
for dealer_up_card in range(2, 12):
clean_text = ""
print(f"Player total: {player_total}, Dealer up card: {dealer_up_card}, "
f"Ace data row: {data_table[player_total][dealer_up_card]}")
if data_table[player_total][dealer_up_card]["insurance"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["insurance"][6] for profit in
data_table[player_total][dealer_up_card]["insurance"][:6]]
if profit_line[5] > 0:
clean_text += f"i ({round(profit_line[5], 2)}) "
if data_table[player_total][dealer_up_card]["surrender"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["surrender"][6] for profit in
data_table[player_total][dealer_up_card]["surrender"][:6]]
max_profit, max_action = argmax(*profit_line[:5])
if max_action == "u":
clean_text += f"u ({round(max_profit, 2)}) "
if data_table[player_total][dealer_up_card]["double"][6]:
profit_line = [profit / data_table[player_total][dealer_up_card]["double"][6] for profit in
data_table[player_total][dealer_up_card]["double"][:6]]
max_profit, max_action = argmax(*profit_line[:4])
if max_action == "d":
clean_text += f"d ({round(max_profit, 2)}) "
profit_line = [profit / max(data_table[player_total][dealer_up_card]["all"][6], 1) for profit in
data_table[player_total][dealer_up_card]["all"][:6]]
max_profit, max_action = argmax(*profit_line[:2])
clean_text += f"{max_action} ({round(max_profit, 2)}) "
clean_table[player_total][dealer_up_card] = clean_text.strip()
return clean_table
def split_table_generator(cores: int = 1, max_splits: int = 1, number_of_decks: int = 6, true_count: int | None = None,
shoes_to_test: int | None = None, deck_penetration: float = .25,
dealer_peeks_for_blackjack: bool = True, das: bool = True,
dealer_stands_soft_17: bool = True, can_surrender: bool = True) -> dict[int, dict[int, str]]:
"""
Generate basic strategy when we can split.
:param cores: How many cores to use in the generation of basic strategy.
:param max_splits: The maximum number of times a hand can be split. (1=fastest, fairly accurate; 3=slowest, super accurate)
:param number_of_decks: The number of decks in the initial shoe.
:param true_count: The true count that we should generate basic strategy for.
Default is None which generates general basic strategy. An integer, generated deviations from basic strategy.
:param shoes_to_test: How many shoes to test when generating deviations.
:param deck_penetration: When to reshuffle the shoe. Reshuffles when cards remaining < starting cards * deck penetration.
So the shoe can't have fewer than starting cards * deck penetration cards.
:param dealer_peeks_for_blackjack: Whether the dealer peeks for blackjack.
:param das: Whether we can double after splitting.
:param dealer_stands_soft_17: Whether the dealer stands on soft 17.
:param can_surrender: Whether the game rules allow surrendering.
:return: The basic strategy table, to be saved and/or plotted.
"""
shoe = DECK * number_of_decks
shoe.sort()
arguments = []
for split_card in range(2, 12):
cards = (split_card, split_card)
for dealer_up_card in range(2, 12):
if true_count is None:
default_shoe = shoe.copy()
for card in cards + (dealer_up_card,):
default_shoe.remove(card)
decks = [default_shoe]
else:
decks = []
for _ in range(shoes_to_test if shoes_to_test else 1):
decks.append(hilo_generator(true_count, number_of_decks, deck_penetration, list(cards) + [dealer_up_card]))
for example_shoe in decks:
shoe_copy = example_shoe.copy()
arguments.append((cards, dealer_up_card, tuple(shoe_copy), True, True, can_surrender, max_splits,
dealer_peeks_for_blackjack, das, dealer_stands_soft_17, True))
data_table = {player_total: {dealer_up_card: [0., 0., 0., 0., 0., 0., 0.] for dealer_up_card in range(2, 12)}
for player_total in range(2, 12)}
with multiprocessing.Pool(processes=cores) as pool:
for argument, profits_not_cast in zip(arguments, pool.starmap(perfect_mover_cache, arguments)):
profits = cast(tuple[float, ...], profits_not_cast)
split_card = argument[0][0]
dealer_up_card = argument[1]
print(f"Player cards: {argument[0]}, Dealer up card: {dealer_up_card}, Split profits: {profits},"
f" Split shoe: {argument[2]}")
data_table[split_card][dealer_up_card][6] += 1
data_table[split_card][dealer_up_card][0] += profits[0]
data_table[split_card][dealer_up_card][1] += profits[1]
data_table[split_card][dealer_up_card][2] += profits[2]
data_table[split_card][dealer_up_card][3] += profits[3]
data_table[split_card][dealer_up_card][4] += profits[4]
data_table[split_card][dealer_up_card][5] += profits[5]
print(f"Split data table:\n{data_table}")
clean_table = {player_total: {dealer_up_card: "" for dealer_up_card in range(2, 12)} for player_total in range(2, 12)}
for split_card in range(2, 12):
for dealer_up_card in range(2, 12):
print(f"Player split card: {split_card}, Dealer up card: {dealer_up_card}, "
f"Split data row: {data_table[split_card][dealer_up_card]}")
clean_text = ""
profit_line = [profit / data_table[split_card][dealer_up_card][6] for profit in
data_table[split_card][dealer_up_card][:6]]
if profit_line[5] > 0:
clean_text += f"i ({round(profit_line[5], 2)}) "
max_profit, max_action = argmax(*profit_line[:5])
if max_action == "u":
clean_text += f"u ({round(max_profit, 2)}) "
max_profit, max_action = argmax(*profit_line[:4])
if max_action == "d":
clean_text += f"d ({round(max_profit, 2)}) "
profit_line[2] = -1000
max_profit, max_action = argmax(*profit_line[:4])
clean_text += f"{max_action} ({round(max_profit, 2)}) "
clean_table[split_card][dealer_up_card] = clean_text.strip()
return clean_table
def draw_and_export_tables(effort: int = 0, cores: int = 1, filename: str | None = None, true_count: int | None = None,
number_of_decks: int = 6, deck_penetration: float = .25,
dealer_peeks_for_blackjack: bool = True, das: bool = True,
dealer_stands_soft_17: bool = True, can_surrender: bool = True,
plot_results: bool = True) -> tuple[list[list[str]], ...]:
"""
Create the graphs with the basic strategy (and maybe save it to a file).
:param effort: How many different hand combinations to test. (min: 0=fastest, very accurate;
max: 5=very slow, super accurate)
:param cores: How many cores to use in the generation of basic strategy.
:param filename: Where to store the basic strategy. If it is None, then it isn't saved.
:param true_count: The true count that we should generate basic strategy for.
Default is None which generates general basic strategy. An integer, generated deviations from basic strategy.
:param number_of_decks: The number of decks in the initial shoe.
:param deck_penetration: When to reshuffle the shoe. Reshuffles when cards remaining < starting cards * deck penetration.
So the shoe can't have fewer than starting cards * deck penetration cards.
:param dealer_peeks_for_blackjack: Whether the dealer peeks for blackjack.
:param das: Whether we can double after splitting.
:param dealer_stands_soft_17: Whether the dealer stands on soft 17.
:param can_surrender: Whether the game rules allow surrendering.
:param plot_results: Whether we should plot the basic strategy at the end.
:return: The three basic strategy tables. (for hard totals, soft totals, and pair splitting)
"""
card_numbers: tuple[int, ...] = (2,)
max_splits = 1
shoes_to_test = 30
shoes_for_split = 10
if effort == 0:
card_numbers = (2,)
max_splits = 1
shoes_to_test = 30
shoes_for_split = 10
elif effort == 1:
card_numbers = (2, 3)
max_splits = 1
shoes_to_test = 50
shoes_for_split = 20
elif effort == 2:
card_numbers = (2, 3, 4)
max_splits = 2
shoes_to_test = 100
shoes_for_split = 40
elif effort == 3:
card_numbers = (2, 3, 4, 5)
max_splits = 3
shoes_to_test = 200
shoes_for_split = 80
elif effort == 4:
card_numbers = (2, 3, 4, 5, 6)
max_splits = 3
shoes_to_test = 500
shoes_for_split = 200
fig, ax = plt.subplots(dpi=200)
fig.patch.set_visible(False)
fig.set_size_inches(7, 4.8)
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.yaxis.set_label_coords(-0.12, 0)
no_ace_table_dict = no_ace_table_generator(cores, card_numbers, number_of_decks=number_of_decks, true_count=true_count,
shoes_to_test=shoes_to_test, deck_penetration=deck_penetration,
dealer_peeks_for_blackjack=dealer_peeks_for_blackjack, das=das,
dealer_stands_soft_17=dealer_stands_soft_17, can_surrender=can_surrender)
print("Save the line below (no ace table) if you want to stop and continue later by commenting the above line and "
"replacing it with the precalculated table.")
print(no_ace_table_dict)
no_ace_table = [[
no_ace_table_dict[hand_total][dealer_card] for dealer_card in range(2, 12)] for hand_total in range(4, 22)]
no_ace_colors: list[list[str]] = [[] for _ in range(18)]
for row in range(18):
for col in range(10):
if no_ace_table[row][col].startswith("s"):
no_ace_colors[row].append("y")
elif no_ace_table[row][col].startswith("h"):
no_ace_colors[row].append("w")
elif no_ace_table[row][col].startswith("d"):
no_ace_colors[row].append("g")
elif no_ace_table[row][col].startswith("p"):
no_ace_colors[row].append("c")
elif no_ace_table[row][col].startswith("u"):
no_ace_colors[row].append("r")
elif no_ace_table[row][col].startswith("i"):
no_ace_colors[row].append("maroon")
table = ax.table(cellText=no_ace_table, cellColours=no_ace_colors, colLabels=list_range_str(2, 12),
rowLabels=list_range_str(4, 22), loc='center', cellLoc='center')
table.scale(1.13, 1.1)
table.auto_set_font_size(False)
table.set_fontsize(3.5)
ax.set_title("Hard totals")
ax.set_xlabel("Dealer Up Card")
ax.set_ylabel("Player Cards")
ax.xaxis.tick_top()
handles = [patches.Rectangle((0, 0), .1, .1, facecolor=color, edgecolor='k', lw=.6)
for color in ["y", "w", "g", "c", "r", "maroon"]]
ax.legend(handles, ["Stand", "Hit", "Double", "Split", "Surrender", "Insurance"], fontsize="xx-small",
bbox_to_anchor=(0.5, -0.14), ncol=6, loc=8)
plt.tight_layout()
fig2, ax2 = plt.subplots(dpi=200)
fig2.patch.set_visible(False)
fig2.set_size_inches(7, 3.2)
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.set_xticks([])
ax2.set_yticks([])
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.yaxis.set_label_coords(-0.12, 0)
ace_table_dict = ace_table_generator(cores, card_numbers, number_of_decks=number_of_decks, true_count=true_count,
shoes_to_test=shoes_to_test, deck_penetration=deck_penetration,
dealer_peeks_for_blackjack=dealer_peeks_for_blackjack, das=das,
dealer_stands_soft_17=dealer_stands_soft_17, can_surrender=can_surrender)
print("Save the line below (ace table) if you want to stop and continue later by commenting the above line and "
"replacing it with the precalculated table.")
print(ace_table_dict)
ace_table = [[ace_table_dict[hand_total][dealer_card] for dealer_card in range(2, 12)] for hand_total in range(12, 22)]
ace_colors: list[list[str]] = [[] for _ in range(10)]
for row in range(10):
for col in range(10):
if ace_table[row][col].startswith("s"):
ace_colors[row].append("y")
elif ace_table[row][col].startswith("h"):
ace_colors[row].append("w")
elif ace_table[row][col].startswith("d"):
ace_colors[row].append("g")
elif ace_table[row][col].startswith("p"):
ace_colors[row].append("c")
elif ace_table[row][col].startswith("u"):
ace_colors[row].append("r")
elif ace_table[row][col].startswith("i"):
ace_colors[row].append("maroon")
row_labels = ["A,A"] + [f"A,{card}" for card in range(2, 11)]
table = ax2.table(cellText=ace_table, cellColours=ace_colors, colLabels=list_range_str(2, 12),
rowLabels=row_labels, loc='center', cellLoc='center')
table.scale(1.13, 1.25)
table.auto_set_font_size(False)
table.set_fontsize(3.5)
ax2.set_title("Soft totals")
ax2.set_xlabel("Dealer Up Card")
ax2.set_ylabel("Player Cards")
ax2.xaxis.tick_top()
handles = [patches.Rectangle((0, 0), .1, .1, facecolor=color, edgecolor='k', lw=.6)
for color in ["y", "w", "g", "c", "r", "maroon"]]
ax2.legend(handles, ["Stand", "Hit", "Double", "Split", "Surrender", "Insurance"], fontsize="xx-small",
bbox_to_anchor=(0.5, -0.23), ncol=6, loc=8)
plt.tight_layout()
fig3, ax3 = plt.subplots(dpi=200)
fig3.patch.set_visible(False)
fig3.set_size_inches(7, 3.2)
ax3.set_yticklabels([])
ax3.set_xticklabels([])
ax3.set_xticks([])
ax3.set_yticks([])
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)
ax3.yaxis.set_label_coords(-0.12, 0)
split_table_dict = split_table_generator(cores, max_splits, number_of_decks=number_of_decks, true_count=true_count,
shoes_to_test=shoes_for_split, deck_penetration=deck_penetration,
dealer_peeks_for_blackjack=dealer_peeks_for_blackjack, das=das,
dealer_stands_soft_17=dealer_stands_soft_17, can_surrender=can_surrender)
print("Save the line below (split table) if you want to stop and continue later by commenting the above line and "
"replacing it with the precalculated table.")
print(split_table_dict)
split_table = [[split_table_dict[card][dealer_card] for dealer_card in range(2, 12)] for card in range(2, 12)]
split_colors: list[list[str]] = [[] for _ in range(10)]
for row in range(10):
for col in range(10):
if split_table[row][col].startswith("s"):
split_colors[row].append("y")
elif split_table[row][col].startswith("h"):
split_colors[row].append("w")
elif split_table[row][col].startswith("d"):
split_colors[row].append("g")
elif split_table[row][col].startswith("p"):
split_colors[row].append("c")
elif split_table[row][col].startswith("u"):
split_colors[row].append("r")
elif split_table[row][col].startswith("i"):
split_colors[row].append("maroon")
row_labels = [f"{card},{card}" for card in range(2, 11)] + ["A,A"]
table = ax3.table(cellText=split_table, cellColours=split_colors, colLabels=list_range_str(2, 12),
rowLabels=row_labels, loc='center', cellLoc='center')
table.scale(1.13, 1.25)
table.auto_set_font_size(False)
table.set_fontsize(3.5)
ax3.set_title("Pair Splitting")
ax3.set_xlabel("Dealer Up Card")
ax3.set_ylabel("Player Cards")
ax3.xaxis.tick_top()
handles = [patches.Rectangle((0, 0), .1, .1, facecolor=color, edgecolor='k', lw=.6)
for color in ["y", "w", "g", "c", "r", "maroon"]]
ax3.legend(handles, ["Stand", "Hit", "Double", "Split", "Surrender", "Insurance"], fontsize="xx-small",
bbox_to_anchor=(0.5, -0.23), ncol=6, loc=8)
plt.tight_layout()
if filename:
with open(filename, "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for row_index, hand_total in enumerate(range(4, 22)):
new_row = list(map(lambda item: re.sub(r'\([^)]*\)', '', item).replace(" ", ""), no_ace_table[row_index]))
writer.writerow([f"n{hand_total}"] + new_row)
for row_index, hand_total in enumerate(range(12, 22)):
new_row = list(map(lambda item: re.sub(r'\([^)]*\)', '', item).replace(" ", ""), ace_table[row_index]))
writer.writerow([f"a{hand_total}"] + new_row)
for row_index, card in enumerate(range(2, 12)):
new_row = list(map(lambda item: re.sub(r'\([^)]*\)', '', item).replace(" ", ""), split_table[row_index]))
writer.writerow([f"s{card}"] + new_row)
if plot_results:
plt.show()
return no_ace_table, ace_table, split_table
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog='Basic Strategy Generation',
description='Create highly customized basic strategy tables based on specific '
'blackjack rule variations.')
parser.add_argument("-e", "--effort", default=0, type=int, help='How many different hand combinations '
'to test. (min: 0=fastest, very accurate; '
'max: 5=very slow, super accurate; default: 0)')
parser.add_argument("--cores", default=1, type=int,
help='How many cores to use in the calculation. (default: 1, use -1 for all cores)')
parser.add_argument("-f", "--filename", help='Where to save the basic strategy generated. Leave empty '
'to not save. (default: don\'t save)')
parser.add_argument("-tc", "--true-count", help='Generate deviations from basic strategy for a specific'
' true count. Leave empty to generate basic strategy. '
'(default: generate basic strategy)')
parser.add_argument("--decks", default=6, type=int, help='How many decks the shoe starts with. (default: 6)')
parser.add_argument("--deck-penetration", default=.25, type=float, help='When to reshuffle the shoe. '
'Reshuffles when cards remaining < starting cards'
' * deck penetration. (default: 0.25)')
parser.add_argument("--stand17", action='store_true', help='Dealer should stand on soft 17. (default: true)')
parser.add_argument("--hit17", action='store_true', help='Dealer should hit on soft 17. (default: false)')
parser.add_argument("--das", action='store_true', help='Allow double after split. (default: true)')
parser.add_argument("--no-das", action='store_true', help='Don\'t allow double after split. (default: false)')
parser.add_argument("--peek", action='store_true', help='Dealer peeks for blackjack. (default: true)')
parser.add_argument("--no-peek", action='store_true', help="Dealer doesn't peek for blackjack. (default: false)")
parser.add_argument("--surrender", action='store_true', help='Allow surrendering. (default: true)')
parser.add_argument("--no-surrender", action='store_true', help='Don\'t allow surrendering. (default: false)')
args = parser.parse_args()
stand_soft_17 = args.stand17 or (not args.hit17)
das_allowed = args.das or (not args.no_das)
peek_for_bj = args.peek or (not args.no_peek)
surrender_allowed = args.surrender or (not args.no_surrender)
cores_used = args.cores if args.cores != -1 else multiprocessing.cpu_count()
draw_and_export_tables(args.effort, cores_used, args.filename, args.true_count, args.decks, args.deck_penetration,
peek_for_bj, das_allowed, stand_soft_17, surrender_allowed, True)