-
Notifications
You must be signed in to change notification settings - Fork 0
/
blackjack.py
901 lines (823 loc) · 37.5 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
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
from random import randint #used for dealer to pick random bet, also used in Deck object to grab a random card from the deck
from dealer_logic import Logic #import separate .py file with decision making code for dealer to pick move
from os import name, system #used for clear lambda function
from time import sleep #used in play method in class Game when player has stood & dealer is still making moves
from blackjack_exceptions import * #import all custom exceptions for project
suitSymbols = {'SPADE':'♠', 'CLUB':'♣', 'DIAMOND':'♦', 'HEART':'♥'}
cardTemplate = []
betAmounts = {'1':1.00, '2':2.50, '3':5.00, '4':25.00, '5':50.00, '6':100.00, '7':500.00}
with open('card_template.txt', 'r', encoding='utf-8') as ct: #reads input file with template for ASCII art card
for line in ct:
cardTemplate.append(line.replace('\n', ''))
clear = lambda: system('cls' if name == 'nt' else 'clear') #used to clear output from console
def takeInput(valids, text): #input validation function
while True:
choice = input(f'{text}')
if choice not in valids:
print('\nInvalid option. Please try again.')
else:
return choice
class Card:
def __init__(self, suit, face, isFlipped): #constructor
self.suit = suit
self.face = face
self.isFlipped = isFlipped
if self.face in ('J', 'Q', 'K'):
self.points = 10
elif self.face == 'A':
self.points = 11
else:
self.points = int(self.face)
def __str__(self): #returns visual representation of card
if self.isFlipped:
return self.flippedCard()
fullCard = ''
for count, line in enumerate(cardTemplate):
if 'F' in line:
if len(self.face) > 1:
line = line.replace('F ', self.face)
line = line.replace(' F', self.face)
else:
line = line.replace('F', self.face)
elif 'S' in line:
line = line.replace('S', suitSymbols[self.suit])
if count == 0:
fullCard += line
else:
fullCard += '\n' + line
return fullCard
def flippedCard(self): #returns visual representation of a face down card
fullCard = ''
for count, line in enumerate(cardTemplate):
line = line.replace('F', '▒')
line = line.replace('S', '▒')
line = line.replace(' ', '▒')
if count == 0:
fullCard += line
else:
fullCard += '\n' + line
return fullCard
class Deck(list):
def __init__(self): #constructor, in this case used to read the input file and populate the default, full deck
self.defaultDeck = []
with open('cards.txt', 'r') as d:
for c in d:
c = c.replace('\n', '')
c = c.split('|')
self.defaultDeck.append(Card(c[1], c[2], False))
def shuffle(self): #clears all remaining cards from self and loads in default deck
self.clear()
for i in self.defaultDeck:
self.append(i)
def getRandom(self): #removes a card from self and then returns said card
try:
return self.pop(randint(0, (len(self)-1)))
except:
raise improperDeck
def forceDraw(self, forcedFace): #used by debug mode, used to draw a card with a specified face
for c, card in enumerate(self):
if card.face == forcedFace:
return self.pop(c)
raise forcedCardNotFound
def getSplit(self): #pulls random pairs of cards until it pulls 2 cards with the same face, then returns pair
while True:
split = []
for i in range(2):
randIndex = randint(0, len(self)-1)
split.append([randIndex, self[randIndex]])
if split[0][1].face == split[1][1].face:
return [i[1] for i in split]
def getDouble(self): #pulls random pairs of cards until it pulls 2 cards that meet the criteria to double down, then returns pair
while True:
double = []
for i in range(2):
randIndex = randint(0, len(self)-1)
double.append([randIndex, self[randIndex]])
if double[0][1].points + double[1][1].points in range(9, 12):
return [i[1] for i in double]
deck = Deck() #initializes deck object
class Hand(list):
def __init__(self, isDealer, splitCard, bet, isCopy, debugHand): #constructor
self.points = 0
self.isDealer = isDealer
self.bet = bet
self.hasDoubled = False
self.splitCard = splitCard
if not isCopy and not debugHand:
self.debugMode = False
if not splitCard:
self.newHand()
else:
self.append(splitCard)
self.points += splitCard.points
elif debugHand and not isCopy:
self.debugMode = True
for i in debugHand:
if type(i) == str:
tempCard = deck.forceDraw(i)
self.points += tempCard.points
self.append(tempCard)
else:
self.append(deck.forceDraw(i.face))
self.points += i.points
elif self.isDealer == 'd':
self.isDealer = True
self.debugMode = True
else:
self.debugMode = False
def newHand(self): #called to deal 2 cards when new hand created (unless this is a debug hand or a copy)
for i in range(2):
self.append(deck.getRandom())
if self.isDealer: #if this is the dealer's hand, show only one card face up
self[1].isFlipped = True
for card in self:
self.points += card.points
def makeCopy(self): #generates and returns a copy of the hand object, used by chkBreak method so it won't need to actually change hand points
handCopy = Hand(self.isDealer, None, self.bet, True, None)
for c in self:
handCopy.append(c)
handCopy.points += c.points
return handCopy
def endRound(self, won): #resolves payout at end of game
if self.isDealer:
if won == 'W':
Dealer.cash += self.bet * 2
elif won == 'B':
Dealer.cash += self.bet + self.bet * 1.5
elif won == 'D':
Dealer.cash += self.bet
else:
raise endRoundError('dealer', won)
else:
if won == 'W':
Player.cash += self.bet * 2
elif won == 'B':
Player.cash += self.bet + self.bet * 1.5
elif won == 'D':
Player.cash += self.bet
else:
raise endRoundError('player', won)
def doubleDown(self): #doubles the bet on the hand, also subtracts additional bet from balance
if not self.hasDoubled:
self.hasDoubled = True
if self.isDealer:
Dealer.cash -= self.bet
else:
Player.cash -= self.bet
self.bet *= 2
def hasAce(self): #returns true if hand contains 1 or more aces, otherwise returns false
aceList = [i for i in self if i.face == 'A']
if aceList:
return True
return False
def chkBreak(self): #returns a boolean representing if hand is bust, takes soft values from aces into account
testList = self.makeCopy()
aceList = [i for i in self if i.face == 'A']
if self.hasAce():
for a in aceList:
if testList.points > 21:
testList.points -= 10
else:
break
if self.debugMode:
if not self.isDealer:
print(f'Ace adjusted points for player (from chkBreak method): {testList.points}')
else:
print(f'Ace adjusted points for dealer (from chkBreak method {testList.points}')
if testList.points > 21:
return True
return False
def changeAce(self): #if there is a bust, reduces ace(s) point values in hand from 11 to 1 until bust resolved or out of aces
aceList = [i for i in self if i.face == 'A']
changed = False
for a in aceList:
if self.points > 21:
self.points -= 10
changed = True
return changed
def chkDouble(self): #checks if hand can be doubled down, returns boolean
if ( self.points in range(9, 12) ) and len(self) == 2 and not self.hasDoubled:
if self.isDealer and (Dealer.cash - self.bet) > 0:
return True
if (Player.cash - self.bet) > 0 and not self.isDealer:
return True
return False
def chkSplit(self): #checks if hand can be split, returns boolean
if len(self) == 2:
faces = [i.face for i in self]
if faces[0] == faces[1]:
return True
return False
def chkBlackjack(self, isSplit): #checks if hand has blackjack, returns boolean
if self.points == 21 and len(self) == 2 and not isSplit:
return True
return False
def hit(self): #main method used to hit. pops a card from deck and adds it to hand
newCard = deck.getRandom()
if self.isDealer:
newCard.isFlipped = True
self.points += newCard.points
self.append(newCard)
def __str__(self): #str method, returns visual representation of hand
tempAdd = []
fullHand = ''
for count, card in enumerate(self):
for lineCount, line in enumerate(card.__str__().split('\n')):
if count == 0:
tempAdd.append(line + '\n')
else:
editLine = tempAdd[lineCount]
editLine = editLine.replace('\n', ' ' + line + '\n')
tempAdd[lineCount] = editLine
for i in tempAdd:
fullHand += ''.join(i)
return fullHand
class Dealer:
cash = 500
def __init__(self, pCard, debug): #constructor
self.originalBet = betAmounts[str(randint(1, 6))]
if debug:
self.hand = Hand('d', None, self.originalBet, False, None)
else:
self.hand = Hand(True, None, self.originalBet, False, None)
self.pCard = pCard
self.isSplit = False
self.splitAce = False
Dealer.cash -= self.originalBet
def __str__(self): #__str__ method for printing dealer's hand(s)
if not self.isSplit:
return self.hand.__str__()
else:
tempAdd = []
fullHand = ''
hands = [self.hand, self.spHand]
for handCount, h in enumerate(hands):
for count, card in enumerate(h):
cardLines = card.__str__().split('\n')
for lineCount, line in enumerate(cardLines):
if handCount == 0:
if count == 0 and len(h) == 1:
tempAdd.append(line + '\t\t\n')
elif count == 0 and len(h) != 1:
tempAdd.append(line + ' \n')
else:
editLine = tempAdd[lineCount]
if count == len(h) - 1:
editLine = editLine.replace('\n', ' ' + line + '\t\t\n')
else:
editLine = editLine.replace('\n', ' ' + line + '\n')
tempAdd[lineCount] = editLine
else:
editLine = tempAdd[lineCount]
editLine = editLine.replace('\n', ' ' + line + '\n')
tempAdd[lineCount] = editLine
for i in tempAdd:
fullHand += ''.join(i)
return fullHand
def split(self): #splits dealer's hand if allowed, raises exception if split is attempted when not allowed
if self.hand.chkSplit() and not self.isSplit:
if self.hand[0].face == 'A' and self.hand[1].face == 'A':
self.hand.points = 11
self.splitAce = True
else:
self.hand.points /= 2
self.spHand = Hand(True, self.hand.pop(), self.originalBet, False, None)
self.isSplit = True
Dealer.cash -= self.originalBet
elif not self.hand.chkSplit() and not self.isSplit:
raise illegalSplit('c')
elif self.hand.chkSplit() and self.isSplit:
raise illegalSplit('a')
else:
raise illegalSplit('b')
def parseMove(self, move, currentHand): #used by play method, takes move from dealer_logic and performs it
if move == 'S':
pass
elif move == 'H':
currentHand.hit()
elif move == 'D' and currentHand.chkDouble():
currentHand.doubleDown()
elif move == 'D' and not currentHand.chkDouble():
currentHand.hit()
elif move == 'SP':
self.split()
else:
raise parseMoveError(move)
def totalBust(self): #returns true if all dealer's hands have busted, else false
if self.isSplit and self.spHand.chkBreak() and self.hand.chkBreak():
return True
if self.hand.chkBreak() and not self.isSplit:
return True
return False
def showCards(self): #flips all dealer's cards face up to display at end of round
if self.isSplit:
for c in self.spHand:
c.isFlipped = False
for c in self.hand:
c.isFlipped = False
def anyDouble(self): #returns boolean representing if dealer has doubled down on any hand
if self.isSplit:
return self.hand.hasDoubled or self.spHand.hasDoubled
return self.hand.hasDoubled
def play(self): #main method dealer uses to play turn, calls class from dealer_logic.py to decide move if needed
aceChanged = False
returnStr = []
if self.hand.points == 21 or self.isSplit and self.spHand.points == 21:
if self.hand.points == 21:
returnStr.append('S')
if self.isSplit and self.spHand.points == 21:
returnStr.append('S')
elif not self.anyDouble() and not self.splitAce: #if dealer has not doubled down, and has not split aces
if self.hand.chkBreak():
returnStr.append('S')
else:
if self.hand.hasAce:
aceChanged = self.hand.changeAce()
mainLogic = Logic(self.pCard, self.hand, self.isSplit, aceChanged)
move = mainLogic.decideMove()
returnStr.append(move)
self.parseMove(move, self.hand)
if self.isSplit:
if self.spHand.chkBreak():
returnStr.append('S')
else:
if self.spHand.hasAce():
aceChanged = self.spHand.changeAce()
logicTwo = Logic(self.pCard, self.spHand, self.isSplit, aceChanged)
moveTwo = logicTwo.decideMove()
self.parseMove(moveTwo, self.spHand)
returnStr.append(moveTwo)
else:
if ( len(self.hand) == 1 and not self.hand.chkBreak() ) or ( len(self.hand) == 2 and self.hand.hasDoubled ):
self.hand.hit()
returnStr.append('H')
else:
returnStr.append('S')
if self.isSplit:
if ( len(self.spHand) == 1 and not self.spHand.chkBreak() ) or ( len(self.spHand) == 2 and self.spHand.hasDoubled ):
self.spHand.hit()
returnStr.append('H')
else:
returnStr.append('S')
return ''.join(returnStr)
class Player:
cash = 500
def __init__(self, debug): #constructor
if debug:
self.debugMode = True
else:
self.debugMode = False
self.makeBet()
self.hand = Hand(False, None, self.originalBet, False, debug)
self.isSplit = False
self.splitAce = False
def __str__(self): #str method to show player's hand(s)
if not self.isSplit:
return self.hand.__str__()
else:
tempAdd = []
fullHand = ''
hands = [self.hand, self.spHand]
for handCount, h in enumerate(hands):
if h.chkBreak():
for i in range(9):
if handCount > 0:
if i == 3:
normalLine = tempAdd[i]
tempAdd[i] = normalLine.replace('\n', '\t** BUST **\n')
else:
if i == 3:
tempAdd.append(' ** BUST **\t\t\t\n')
else:
tempAdd.append('\t\t\t\t\n')
else:
for count, card in enumerate(h):
cardLines = card.__str__().split('\n')
for lineCount, line in enumerate(cardLines):
if handCount == 0:
if count == 0 and len(h) == 1:
tempAdd.append(line + '\t\t\n')
elif count == 0 and len(h) != 1:
tempAdd.append(line + ' \n')
else:
editLine = tempAdd[lineCount]
if count == len(h) - 1:
editLine = editLine.replace('\n', ' ' + line + '\t\t\n')
else:
editLine = editLine.replace('\n', ' ' + line + '\n')
tempAdd[lineCount] = editLine
else:
editLine = tempAdd[lineCount]
editLine = editLine.replace('\n', ' ' + line + '\n')
tempAdd[lineCount] = editLine
for i in tempAdd:
fullHand += ''.join(i)
return fullHand
def totalBust(self): #checks if all player's hand(s) have busted, returns boolean
if self.isSplit and self.spHand.chkBreak() and self.hand.chkBreak():
return True
if self.hand.chkBreak() and not self.isSplit:
return True
return False
def split(self): #splits player's hand if allowed
if self.hand.chkSplit() and not self.isSplit:
if self.hand[0].face == 'A' and self.hand[1].face == 'A':
self.splitAce = True
self.hand.points = 11
else:
self.hand.points /= 2
self.spHand = Hand(False, self.hand.pop(), self.originalBet, False, None)
self.isSplit = True
Player.cash -= self.originalBet
else:
raise illegalSplit('p') #raise exception if obj attempts an illegal split
def anyDouble(self): #returns boolean representing if player has doubled down on any hand
if self.isSplit:
return self.hand.hasDoubled or self.spHand.hasDoubled
return self.hand.hasDoubled
def makeBet(self): #takes player input for bet on hand
if not self.debugMode:
clear()
if Player.cash <= 0:
raise makeBetError
print(f'Your current cash is ${Player.cash:.2f}')
betAmt = takeInput(('1', '2', '3', '4', '5', '6', '7'), '\n1. $1.00\n2. $2.50\n3. $5.00\n4. $25.00\n5. $50.00\n6. $100.00\n7. $500.00\n\nEnter bet choice: ')
while betAmounts[betAmt] > Player.cash:
betAmt = takeInput(('1', '2', '3', '4', '5', '6', '7'), "\n1. $1.00\n2. $2.50\n3. $5.00\n4. $25.00\n5. $50.00\n6. $100.00\n7. $500.00\n\nCan't afford bet! Enter lower amount: ")
for k, v in betAmounts.items():
if betAmt == k:
self.originalBet = v
break
Player.cash -= self.originalBet
def play(self, spLogic): #main method for player to take turn
if not self.anyDouble() and not self.splitAce:
if not spLogic:
if self.hand.chkSplit() and self.hand.chkDouble() and not self.isSplit:
option = takeInput(('1', '2', '3', '4'), '\n1. Hit\n2. Stand\n3. Split\n4. Double Down\n\nEnter choice: ')
if option == '1':
self.hand.hit()
returnStr ='H'
elif option == '2':
returnStr = 'S'
elif option == '3':
self.split()
returnStr = 'SP'
else:
self.hand.doubleDown()
returnStr = 'D'
elif self.hand.chkSplit() and not self.isSplit:
option = takeInput(('1', '2', '3'), '\n1. Hit\n2. Stand\n3. Split\n\nEnter choice: ')
if option == '1':
self.hand.hit()
returnStr = 'H'
elif option == '2':
returnStr = 'S'
else:
self.split()
returnStr = 'SP'
elif self.hand.chkDouble():
if self.isSplit:
option = takeInput(('1', '2', '3'), '\n1. Hit\n2. Stand\n3. Double Down\n\nEnter choice for hand #1: ')
else:
option = takeInput(('1', '2', '3'), '\n1. Hit\n2. Stand\n3. Double Down\n\nEnter choice: ')
if option == '1':
self.hand.hit()
returnStr = 'H'
elif option == '2':
returnStr = 'S'
else:
self.hand.doubleDown()
returnStr = 'D'
else:
if self.isSplit:
option = takeInput(('1', '2'), '\n1. Hit\n2. Stand\n\nEnter choice for hand #1: ')
else:
option = takeInput(('1', '2'), '\n1. Hit\n2. Stand\n\nEnter choice: ')
if option == '1':
self.hand.hit()
returnStr = 'H'
else:
returnStr = 'S'
else:
if spLogic == 1 and not self.hand.chkBreak():
if self.hand.chkDouble():
option = takeInput(('1', '2', '3'), '\n1. Hit\n2. Stand\n3. Double Down\n\nEnter choice for hand #1: ')
if option == '1':
self.hand.hit()
returnStr = 'H'
elif option == '2':
returnStr = 'S'
else:
self.hand.doubleDown()
returnStr = 'D'
else:
option = takeInput(('1', '2'), '\n1. Hit\n2. Stand\n\nEnter choice for hand #1: ')
if option == '1':
self.hand.hit()
returnStr = 'H'
else:
returnStr = 'S'
else:
if self.spHand.chkDouble():
option = takeInput(('1', '2', '3'), '\n1. Hit\n2. Stand\n3. Double Down\n\nEnter choice for hand #2: ')
if option == '1':
self.spHand.hit()
returnStr = 'H'
elif option == '2':
returnStr = 'S'
else:
self.spHand.doubleDown()
returnStr = 'D'
else:
option = takeInput(('1', '2'), '\n1. Hit\n2. Stand\n\nEnter choice for hand #2: ')
if option == '1':
self.spHand.hit()
returnStr = 'H'
else:
returnStr = 'S'
else:
if ( self.isSplit and len(self.hand) == 1 ) or ( len(self.hand) == 2 and self.hand.hasDoubled ):
self.hand.hit()
returnStr = 'H'
elif ( self.isSplit and len(self.spHand) == 1 ) or ( self.isSplit and len(self.spHand) == 2 and self.spHand.hasDoubled ):
self.spHand.hit()
returnStr = 'H'
else:
returnStr = 'S'
return returnStr
class Game:
def __init__(self, debug): #constructor
deck.shuffle()
if debug:
self.player = Player(debug)
self.debugMode = True
self.dealer = Dealer(self.player.hand[0], True)
else:
self.player = Player(None)
self.debugMode = False
self.dealer = Dealer(self.player.hand[0], False)
self.winStatus = {}
def __str__(self):
if not self.dealer.isSplit and not self.player.isSplit:
return " *** Dealer's Hand ***\n" + self.dealer.__str__() + '\n\n *** Your Hand ***\n' + self.player.__str__()
if self.player.isSplit and not self.dealer.isSplit:
return " *** Dealer's Hand ***\n" + self.dealer.__str__() + '\n\n *** Your Hands ***\n'+ self.player.__str__()
if self.dealer.isSplit and not self.player.isSplit:
return " *** Dealer's Hands ***\n" + self.dealer.__str__() + '\n\n *** Your Hand ***\n' + self.player.__str__()
if self.player.isSplit and self.dealer.isSplit:
return " *** Dealer's Hands ***\n" + self.dealer.__str__() + '\n\n *** Your Hands ***\n' + self.player.__str__()
def eitherBlackjack(self): #made individual method for blackjack case so it can be checked at game start
if self.player.hand.chkBlackjack(self.player.isSplit):
self.dealer.showCards()
return self.__str__() + '\n\n*** YOU HAVE BLACKJACK! YOU WIN! ***'
elif self.dealer.hand.chkBlackjack(self.dealer.isSplit):
self.dealer.showCards()
return self.__str__() + '\n\n*** DEALER HAS BLACKJACK! DEALER WINS! ***'
else:
return ''
def play(self): #main method to play turns, loops until one or both bust, or until both stand
lastPlayerSPcard = 'X'
while True: #loops until break condition (if either bust or both stand) at end is met
if not self.debugMode:
clear()
print(self)
if not self.player.isSplit:
lastPlayerMove = self.player.play(None)
else:
if 'S' not in {lastPlayerMove, lastPlayerSPcard} and not ( self.player.hand.chkBreak() or self.player.spHand.chkBreak() ):
for i in range(1, 3):
if not self.debugMode:
clear()
print(self)
tempMove = self.player.play(i)
if i == 1:
lastPlayerMove = tempMove
else:
lastPlayerSPcard = tempMove
else:
if self.player.hand.chkBreak() or lastPlayerMove == 'S':
lastPlayerSPcard = self.player.play(2)
else:
lastPlayerMove = self.player.play(1)
lastDealerMove = self.dealer.play()
joinedPlayerMoves = lastPlayerMove + lastPlayerSPcard
if lastDealerMove not in {'S', 'SS'} and joinedPlayerMoves in {'SX', 'SS'} and not self.player.totalBust():
while lastDealerMove not in {'S', 'SS'} and not self.dealer.totalBust():
sleep(0.4)
lastDealerMove = self.dealer.play()
clear()
print(self)
if ( joinedPlayerMoves in {'SX', 'SS'} and lastDealerMove in {'S', 'SS'} ) or (self.player.totalBust() or self.dealer.totalBust()) or\
( 'S' in joinedPlayerMoves and ( self.player.hand.chkBreak() or self.player.spHand.chkBreak() ) ):
return
def finishGame(self): #used to resolve payouts for bets as well as determine winner
self.dealer.showCards()
playerResults = []
dealerResults = []
if self.player.isSplit and not self.player.spHand.chkBreak():
self.player.spHand.changeAce()
playerResults.append(self.player.spHand)
if not self.player.hand.chkBreak():
self.player.hand.changeAce()
playerResults.append(self.player.hand)
if self.dealer.isSplit and not self.dealer.spHand.chkBreak():
self.dealer.spHand.changeAce()
dealerResults.append(self.dealer.spHand)
if not self.dealer.hand.chkBreak():
self.dealer.hand.changeAce()
dealerResults.append(self.dealer.hand)
pScores = {c : i.points for c, i in enumerate(playerResults)}
dScores = {c : i.points for c, i in enumerate(dealerResults)}
if pScores:
bestP = max(pScores.values())
if dScores:
bestD = max(dScores.values())
if self.debugMode:
print(f'Player scores are {pScores.values()}\nDealer scores are {dScores.values()}')
def addResult(result): #used to add wins, losses, and draws to player and dealer
if result == 'pw':
self.winStatus['player'] = 'w'
self.winStatus['dealer'] = 'l'
elif result == 'dw':
self.winStatus['player'] = 'l'
self.winStatus['dealer'] = 'w'
elif result == 'draw':
self.winStatus['player'] = 'draw'
self.winStatus['dealer'] = 'draw'
elif result == 'n':
self.winStatus['player'] = 'l'
self.winStatus['dealer'] = 'l'
else:
raise finishGameError(2, result)
if 'YOU' in self.eitherBlackjack():
self.player.hand.endRound('B')
elif 'DEALER' in self.eitherBlackjack():
self.dealer.hand.endRound('B')
elif not self.player.totalBust() and not self.dealer.totalBust():
wins = []
if len(playerResults) > len(dealerResults):
for k, v in pScores.items():
if v > bestD:
playerResults[k].endRound('W')
wins.append(v)
elif v == bestD:
playerResults[k].endRound('D')
dealerResults[0].endRound('D')
wins.append(v)
else:
dealerResults[0].endRound('W')
wins.append(v)
if max(wins) > bestD:
addResult('pw')
elif max(wins) == bestD:
addResult('draw')
else:
addResult('dw')
elif len(playerResults) < len(dealerResults):
for k, v in dScores.items():
if v > bestP:
dealerResults[k].endRound('W')
wins.append(v)
elif v == bestP:
playerResults[0].endRound('D')
dealerResults[k].endRound('D')
wins.append(v)
else:
playerResults[0].endRound('W')
wins.append(v)
if max(wins) > bestP:
addResult('dw')
elif max(wins) == bestP:
addResult('draw')
else:
addResult('pw')
elif len(playerResults) == 2 and len(dealerResults) == 2:
for (pk, pv), (dk, dv) in zip(pScores.items(), dScores.items()):
if pv > dv:
playerResults[pk].endRound('W')
elif pv == dv:
playerResults[pk].endRound('D')
dealerResults[dk].endRound('D')
else:
dealerResults[dk].endRound('W')
if bestP > bestD:
addResult('pw')
elif bestP == bestD:
addResult('draw')
else:
addResult('dw')
else:
if bestP > bestD:
playerResults[0].endRound('W')
addResult('pw')
elif bestP == bestD:
playerResults[0].endRound('D')
dealerResults[0].endRound('D')
addResult('draw')
elif bestD > bestP:
dealerResults[0].endRound('W')
addResult('dw')
elif self.player.totalBust() and not self.dealer.totalBust():
addResult('dw')
for i in dealerResults:
if not i.chkBreak():
i.endRound('W')
elif self.dealer.totalBust() and not self.player.totalBust():
addResult('pw')
for i in playerResults:
if not i.chkBreak():
i.endRound('W')
elif self.player.totalBust() and self.dealer.totalBust():
addResult('n')
else:
raise finishGameError(1, None) #if all possible win conditions are exhausted, raises exception
def endgameStr(self): #returns string declaring winner
winValues = {'w' : 2, 'draw' : 1, 'l' : 0}
playerVal = winValues[self.winStatus['player']]
dealerVal = winValues[self.winStatus['dealer']]
baseReturn = self.__str__()
if playerVal > dealerVal:
baseReturn += '\n\n*** PLAYER WINS ***'
if self.debugMode:
baseReturn += f'\n\nPlayer win value: {self.winStatus["player"]}\nDealer win value: {self.winStatus["dealer"]}'
return baseReturn
if dealerVal > playerVal:
baseReturn += '\n\n*** DEALER WINS ***'
if self.debugMode:
baseReturn += f'\n\nPlayer win value: {self.winStatus["player"]}\nDealer win value: {self.winStatus["dealer"]}'
return baseReturn
if all(v == 1 for v in {playerVal, dealerVal}):
baseReturn += '\n\n*** DRAW ***'
if self.debugMode:
baseReturn += f'\n\nPlayer win value: {self.winStatus["player"]}\nDealer win value: {self.winStatus["dealer"]}'
return baseReturn
if all(v == 0 for v in {playerVal, dealerVal}):
baseReturn += '\n\n*** ALL BUSTED ***'
if self.debugMode:
baseReturn += f'\n\nPlayer win value: {self.winStatus["player"]}\nDealer win value: {self.winStatus["dealer"]}'
return baseReturn
raise winStatusError(self.winStatus['player'], self.winStatus['dealer'])
def debug(): #debug tools used to diagnose issues with specific game conditions, such as splits returning wrong winner
while True:
if Player.cash <= 0:
print('Player cash too low, setting to default at 500...')
sleep(3)
deck.shuffle()
choice = input('\n\nDebug Menu\n\n1. Specify dealt hand\n2. Deal condition permitting split\n3. Deal condition permitting double down\n4. Play standard round with diagnostic info\n5. Exit and play normal game\n')
if choice == '1':
hand = input('Enter hand: ')
hand = hand.split(',')
elif choice == '2':
hand = deck.getSplit()
elif choice == '3':
hand = deck.getDouble()
elif choice == '4':
hand = []
try:
for i in range(2):
hand.append(deck[randint(0, len(deck)-1)])
except:
raise improperDeck
else:
return
currentGame = Game(hand)
if currentGame.eitherBlackjack():
print(currentGame.eitherBlackjack())
currentGame.finishGame()
else:
currentGame.play()
currentGame.finishGame()
print(currentGame.endgameStr())
input('\n\nPress enter to continue.')
enterDebug = input('Welcome! Press Enter to start.\n')
if enterDebug == 'debug':
debug()
while True: #used for playing normal games. asks user if they want to play again, loops until user answers no
if Player.cash == 0:
clear()
option = takeInput({'1', '2'}, "You're out of money! Options:\n1. Start over with default cash\n2. Exit\n")
if option == '1':
Player.cash, Dealer.cash = 500, 500
else:
break
elif Dealer.cash == 0:
clear()
print('Dealer is out of cash! Player wins!')
option = takeInput({'1', '2'}, "Options:\n1. Start over with default cash\n2. Exit\n")
if option == '1':
Player.cash, Dealer.cash = 500, 500
else:
break
currentGame = Game(None)
if currentGame.eitherBlackjack():
clear()
print(currentGame.eitherBlackjack())
currentGame.finishGame()
else:
currentGame.play()
currentGame.finishGame()
clear()
print(currentGame.endgameStr())
cont = takeInput(('y', 'n'), '\nPlay again? (y/n)\n')
if cont == 'n':
break