i made a blackjack game and i’m having problems counting my cards with the aces. Can someone help me clean my code
JavaScript
x
59
59
1
class Player():
2
def __init__(self, name):
3
self.bust = False
4
5
self.hand = []
6
self.hand2 = []
7
self.name = str(name)
8
self.handlist = []
9
10
def hit(self):
11
for i in self.handlist:
12
response = ''
13
while response != 'h' or response != 's':
14
print(self.name)
15
print(i)
16
print("Do you want to hit or stand? (h/s)")
17
print(self.gettotal(i))
18
response = str(input())
19
if response == 'h':
20
phand = i
21
card = pickacard(deck)
22
phand.append(card)
23
i = phand
24
phand = []
25
grade = self.gettotal(i)
26
if grade > 21:
27
self.bust = True
28
print(i)
29
print(self.gettotal(i))
30
print("Player busts!")
31
break
32
else:
33
break
34
35
def gettotal(self, hand):
36
total = 0
37
if hand == []:
38
total = 0
39
return total
40
for i in range(len(hand)):
41
42
t = int(hand[i][0])
43
if t == 11 or t == 12 or t == 13:
44
total += 10
45
elif t != 1:
46
total += t
47
elif t == 1 and total < 22:
48
total += 11
49
if total > 21:
50
i = len(hand)-1
51
while i >= 0:
52
t = int(hand[i][0])
53
if t == 1:
54
total -= 10
55
break
56
i -= 1
57
t = 0
58
return total
59
i have those exemple:
player1
[[‘1’, ‘D’], [’11’, ‘C’], [’11’, ‘D’], [‘1’, ‘H’]]
Do you want to hit or stand? (h/s)
total = 21
player1
[[‘1’, ‘D’], [’10’, ‘D’], [’11’, ‘H’], [‘1’, ‘H’]]
Do you want to hit or stand? (h/s)
total = 21
Advertisement
Answer
Something like this:
JavaScript
1
16
16
1
def gettotal(self, hand):
2
total = 0
3
aces = False
4
for card in hand:
5
t = int(card[0])
6
if t > 11:
7
total += 10
8
elif t == 1:
9
aces = True
10
total += 1
11
else:
12
total += t
13
if aces and total <= 11:
14
total += 10
15
return total
16
And, by the way, any card game that shows 1, 11, 12 and 13 instead of A, J, Q, K is not worth playing. Since you’re storing the cards as strings anyway, why not just store the familiar letters? It would take very minor changes to your code, and the user experience would be much better:
JavaScript
1
16
16
1
def gettotal(self, hand):
2
total = 0
3
aces = False
4
for card in hand:
5
t = card[0]
6
if t in "JQK":
7
total += 10
8
elif t == 'A':
9
aces = True
10
total += 1
11
else:
12
total += int(t)
13
if aces and total <= 11:
14
total += 10
15
return total
16