forked from seblau/BlackJack-Simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlackJack.py
497 lines (414 loc) · 13.9 KB
/
BlackJack.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
import sys
from random import shuffle
import numpy as np
import scipy.stats as stats
import pylab as pl
import matplotlib.pyplot as plt
from importer.StrategyImporter import StrategyImporter
GAMES = 20000
SHOE_SIZE = 6
SHOE_PENETRATION = 0.25
BET_SPREAD = 20.0
DECK_SIZE = 52.0
CARDS = {"Ace": 11, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 10, "Queen": 10, "King": 10}
BASIC_OMEGA_II = {"Ace": 0, "Two": 1, "Three": 1, "Four": 2, "Five": 2, "Six": 2, "Seven": 1, "Eight": 0, "Nine": -1, "Ten": -2, "Jack": -2, "Queen": -2, "King": -2}
BLACKJACK_RULES = {
'triple7': False, # Count 3x7 as a blackjack
}
HARD_STRATEGY = {}
SOFT_STRATEGY = {}
PAIR_STRATEGY = {}
class Card(object):
"""
Represents a playing card with name and value.
"""
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return "%s" % self.name
class Shoe(object):
"""
Represents the shoe, which consists of a number of card decks.
"""
reshuffle = False
def __init__(self, decks):
self.count = 0
self.count_history = []
self.ideal_count = {}
self.decks = decks
self.cards = self.init_cards()
self.init_count()
def __str__(self):
s = ""
for c in self.cards:
s += "%s\n" % c
return s
def init_cards(self):
"""
Initialize the shoe with shuffled playing cards and set count to zero.
"""
self.count = 0
self.count_history.append(self.count)
cards = []
for d in range(self.decks):
for c in CARDS:
for i in range(0, 4):
cards.append(Card(c, CARDS[c]))
shuffle(cards)
return cards
def init_count(self):
"""
Keep track of the number of occurrences for each card in the shoe in the course over the game. ideal_count
is a dictionary containing (card name - number of occurrences in shoe) pairs
"""
for card in CARDS:
self.ideal_count[card] = 4 * SHOE_SIZE
def deal(self):
"""
Returns: The next card off the shoe. If the shoe penetration is reached,
the shoe gets reshuffled.
"""
if self.shoe_penetration() < SHOE_PENETRATION:
self.reshuffle = True
card = self.cards.pop()
assert self.ideal_count[card.name] > 0, "Either a cheater or a bug!"
self.ideal_count[card.name] -= 1
self.do_count(card)
return card
def do_count(self, card):
"""
Add the dealt card to current count.
"""
self.count += BASIC_OMEGA_II[card.name]
self.count_history.append(self.truecount())
def truecount(self):
"""
Returns: The current true count.
"""
return self.count / (self.decks * self.shoe_penetration())
def shoe_penetration(self):
"""
Returns: Ratio of cards that are still in the shoe to all initial cards.
"""
return len(self.cards) / (DECK_SIZE * self.decks)
class Hand(object):
"""
Represents a hand, either from the dealer or from the player
"""
_value = 0
_aces = []
_aces_soft = 0
splithand = False
surrender = False
doubled = False
def __init__(self, cards):
self.cards = cards
def __str__(self):
h = ""
for c in self.cards:
h += "%s " % c
return h
@property
def value(self):
"""
Returns: The current value of the hand (aces are either counted as 1 or 11).
"""
self._value = 0
for c in self.cards:
self._value += c.value
if self._value > 21 and self.aces_soft > 0:
for ace in self.aces:
if ace.value == 11:
self._value -= 10
ace.value = 1
if self._value <= 21:
break
return self._value
@property
def aces(self):
"""
Returns: The all aces in the current hand.
"""
self._aces = []
for c in self.cards:
if c.name == "Ace":
self._aces.append(c)
return self._aces
@property
def aces_soft(self):
"""
Returns: The number of aces valued as 11
"""
self._aces_soft = 0
for ace in self.aces:
if ace.value == 11:
self._aces_soft += 1
return self._aces_soft
def soft(self):
"""
Determines whether the current hand is soft (soft means that it consists of aces valued at 11).
"""
if self.aces_soft > 0:
return True
else:
return False
def splitable(self):
"""
Determines if the current hand can be splitted.
"""
if self.length() == 2 and self.cards[0].name == self.cards[1].name:
return True
else:
return False
def blackjack(self):
"""
Check a hand for a blackjack, taking the defined BLACKJACK_RULES into account.
"""
if not self.splithand and self.value == 21:
if all(c.value == 7 for c in self.cards) and BLACKJACK_RULES['triple7']:
return True
elif self.length() == 2:
return True
else:
return False
else:
return False
def busted(self):
"""
Checks if the hand is busted.
"""
if self.value > 21:
return True
else:
return False
def add_card(self, card):
"""
Add a card to the current hand.
"""
self.cards.append(card)
def split(self):
"""
Split the current hand.
Returns: The new hand created from the split.
"""
self.splithand = True
c = self.cards.pop()
new_hand = Hand([c])
new_hand.splithand = True
return new_hand
def length(self):
"""
Returns: The number of cards in the current hand.
"""
return len(self.cards)
class Player(object):
"""
Represent a player
"""
def __init__(self, hand=None, dealer_hand=None):
self.hands = [hand]
self.dealer_hand = dealer_hand
def set_hands(self, new_hand, new_dealer_hand):
self.hands = [new_hand]
self.dealer_hand = new_dealer_hand
def play(self, shoe):
for hand in self.hands:
# print "Playing Hand: %s" % hand
self.play_hand(hand, shoe)
def play_hand(self, hand, shoe):
if hand.length() < 2:
if hand.cards[0].name == "Ace":
hand.cards[0].value = 11
self.hit(hand, shoe)
while not hand.busted() and not hand.blackjack():
if hand.soft():
flag = SOFT_STRATEGY[hand.value][self.dealer_hand.cards[0].name]
elif hand.splitable():
flag = PAIR_STRATEGY[hand.value][self.dealer_hand.cards[0].name]
else:
flag = HARD_STRATEGY[hand.value][self.dealer_hand.cards[0].name]
if flag == 'D':
if hand.length() == 2:
# print "Double Down"
hand.doubled = True
self.hit(hand, shoe)
break
else:
flag = 'H'
if flag == 'Sr':
if hand.length() == 2:
# print "Surrender"
hand.surrender = True
break
else:
flag = 'H'
if flag == 'H':
self.hit(hand, shoe)
if flag == 'P':
self.split(hand, shoe)
if flag == 'S':
break
def hit(self, hand, shoe):
c = shoe.deal()
hand.add_card(c)
# print "Hitted: %s" % c
def split(self, hand, shoe):
self.hands.append(hand.split())
# print "Splitted %s" % hand
self.play_hand(hand, shoe)
class Dealer(object):
"""
Represent the dealer
"""
def __init__(self, hand=None):
self.hand = hand
def set_hand(self, new_hand):
self.hand = new_hand
def play(self, shoe):
while self.hand.value < 17:
self.hit(shoe)
def hit(self, shoe):
c = shoe.deal()
self.hand.add_card(c)
# print "Dealer hitted: %s" %c
# Returns an array of 6 numbers representing the probability that the final score of the dealer is
# [17, 18, 19, 20, 21, Busted] '''
# TODO Differentiate 21 and BJ
# TODO make an actual tree, this is false AF
def get_probabilities(self) :
start_value = self.hand.value
# We'll draw 5 cards no matter what an count how often we got 17, 18, 19, 20, 21, Busted
class Tree(object):
"""
A tree that opens with a statistical card and changes as a new
statistical card is added. In this context, a statistical card is a list of possible values, each with a probability.
e.g : [2 : 0.05, 3 : 0.1, ..., 22 : 0.1]
Any value above 21 will be truncated to 22, which means 'Busted'.
"""
#TODO to test
def __init__(self, start=[]):
self.tree = []
self.tree.append(start)
def add_a_statistical_card(self, stat_card):
# New set of leaves in the tree
leaves = []
for p in self.tree[-1] :
for v in stat_card :
new_value = v + p
proba = self.tree[-1][p]*stat_card[v]
if (new_value > 21) :
# All busted values are 22
new_value = 22
if (new_value in leaves) :
leaves[new_value] = leaves[new_value] + proba
else :
leaves[new_value] = proba
class Game(object):
"""
A sequence of Blackjack Rounds that keeps track of total money won or lost
"""
def __init__(self):
self.shoe = Shoe(SHOE_SIZE)
self.money = 0.0
self.bet = 0.0
self.stake = 1.0
self.player = Player()
self.dealer = Dealer()
def get_hand_winnings(self, hand):
win = 0.0
bet = self.stake
if not hand.surrender:
if hand.busted():
status = "LOST"
else:
if hand.blackjack():
if self.dealer.hand.blackjack():
status = "PUSH"
else:
status = "WON 3:2"
elif self.dealer.hand.busted():
status = "WON"
elif self.dealer.hand.value < hand.value:
status = "WON"
elif self.dealer.hand.value > hand.value:
status = "LOST"
elif self.dealer.hand.value == hand.value:
if self.dealer.hand.blackjack():
status = "LOST" # player's 21 vs dealers blackjack
else:
status = "PUSH"
else:
status = "SURRENDER"
if status == "LOST":
win += -1
elif status == "WON":
win += 1
elif status == "WON 3:2":
win += 1.5
elif status == "SURRENDER":
win += -0.5
if hand.doubled:
win *= 2
bet *= 2
win *= self.stake
return win, bet
def play_round(self):
if self.shoe.truecount() > 6:
self.stake = BET_SPREAD
else:
self.stake = 1.0
player_hand = Hand([self.shoe.deal(), self.shoe.deal()])
dealer_hand = Hand([self.shoe.deal()])
self.player.set_hands(player_hand, dealer_hand)
self.dealer.set_hand(dealer_hand)
# print "Dealer Hand: %s" % self.dealer.hand
# print "Player Hand: %s\n" % self.player.hands[0]
self.player.play(self.shoe)
self.dealer.play(self.shoe)
# print ""
for hand in self.player.hands:
win, bet = self.get_hand_winnings(hand)
self.money += win
self.bet += bet
# print "Player Hand: %s %s (Value: %d, Busted: %r, BlackJack: %r, Splithand: %r, Soft: %r, Surrender: %r, Doubled: %r)" % (hand, status, hand.value, hand.busted(), hand.blackjack(), hand.splithand, hand.soft(), hand.surrender, hand.doubled)
# print "Dealer Hand: %s (%d)" % (self.dealer.hand, self.dealer.hand.value)
def get_money(self):
return self.money
def get_bet(self):
return self.bet
if __name__ == "__main__":
importer = StrategyImporter(sys.argv[1])
HARD_STRATEGY, SOFT_STRATEGY, PAIR_STRATEGY = importer.import_player_strategy()
moneys = []
bets = []
countings = []
nb_hands = 0
for g in range(GAMES):
game = Game()
while not game.shoe.reshuffle:
# print '%s GAME no. %d %s' % (20 * '#', i + 1, 20 * '#')
game.play_round()
nb_hands += 1
moneys.append(game.get_money())
bets.append(game.get_bet())
countings += game.shoe.count_history
print("WIN for Game no. %d: %s (%s bet)" % (g + 1, "{0:.2f}".format(game.get_money()), "{0:.2f}".format(game.get_bet())))
sume = 0.0
total_bet = 0.0
for value in moneys:
sume += value
for value in bets:
total_bet += value
print "\n%d hands overall, %0.2f hands per game on average" % (nb_hands, float(nb_hands) / GAMES)
print "%0.2f total bet" % total_bet
print("Overall winnings: {} (edge = {} %)".format("{0:.2f}".format(sume), "{0:.3f}".format(100.0*sume/total_bet)))
moneys = sorted(moneys)
fit = stats.norm.pdf(moneys, np.mean(moneys), np.std(moneys)) # this is a fitting indeed
pl.plot(moneys, fit, '-o')
pl.hist(moneys, normed=True)
pl.show()
plt.ylabel('count')
plt.plot(countings, label='x')
plt.legend()
plt.show()