-
Notifications
You must be signed in to change notification settings - Fork 0
/
AI_Blackjack.py
62 lines (51 loc) · 1.86 KB
/
AI_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
import random
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards)
def calculate_score(hand):
if sum(hand) == 21 and len(hand) == 2:
return 0
if 11 in hand and sum(hand) > 21:
hand.remove(11)
hand.append(1)
return sum(hand)
def blackjack():
user_cards = []
computer_cards = []
game_over = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not game_over:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print("Your cards: ", user_cards, ", current score: ", user_score)
print("Computer's first card: ", computer_cards[0])
if user_score == 0 or computer_score == 0 or user_score > 21:
game_over = True
else:
should_continue = input("Type 'y' to get another card, 'n' to pass: ")
if should_continue == 'y':
user_cards.append(deal_card())
else:
game_over = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print("Your final hand: ", user_cards, ", final score: ", user_score)
print("Computer's final hand: ", computer_cards, ", final score: ", computer_score)
if user_score > 21:
return "You went over. You lose!"
elif computer_score > 21:
return "Computer went over. You win!"
elif user_score == computer_score:
return "It's a draw!"
elif user_score == 0:
return "Blackjack! You win!"
elif computer_score == 0:
return "Computer got a Blackjack. You lose!"
elif user_score > computer_score:
return "You win!"
else:
return "You lose!"
print(blackjack())