I am creating a simplified blackjack game, and when game over is called in one of my functions, it is not being registered in the 'while' loop, and it just starts over. I've tried debugging, and I can see when game_over is called, however the while loop continues. I know there is definitely an easier way to write this, but in the spirit of learning I am just writing it in the way that immediately makes sense and will clean it later. Thank you.
start_game = (input("Do you want to play a game of BlackJack? Type 'y' or 'n': ")).lower()
if start_game == 'y':
def deal_card(hand):
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
hand.append(random.choice(cards))
def calculate_score(hand):
score = sum(hand)
if score == 21:
return 0
game_over = True
elif score > 21:
new_hand = []
for cards in hand:
if cards == 11:
cards = 1
new_hand.append(cards)
if sum(new_hand) == 2:
new_hand = [11, 1]
else:
new_hand.append(cards)
score = sum(new_hand)
return score
game_over = True
else:
return score
def compare(user, pc):
if sum(user) == 0:
print("You got BlackJack! You win.")
elif sum(pc) == 0:
print("Computer got BlackJack! You lose.")
elif sum(user) > 21:
print("You busted your load. You lose.")
elif sum(pc) > 21:
print("The computer busted his load. You win.")
elif sum(user) > sum(pc):
print("You win.")
else:
print("You lose")
game_over = True
user_hand = []
deal_card(user_hand)
deal_card(user_hand)
pc_hand = []
deal_card(pc_hand)
deal_card(pc_hand)
game_over = False
while not game_over:
print(f"Your cards: {user_hand}, current score: {sum(user_hand)}")
print(f"Computer's first card: {pc_hand[0]}")
hit_me = (input("Type 'y' to get another card, type 'n' to hold: ")).lower()
if hit_me == 'n':
print(f"Your final hand: {user_hand}, final score: {calculate_score(user_hand)}")
pc_done = False
while not pc_done:
if calculate_score(pc_hand) < 17 and calculate_score(pc_hand) > 0:
deal_card(pc_hand)
else:
compare(user_hand, pc_hand)
if hit_me == 'y':
deal_card(user_hand)
calculate_score(user_hand)
print(f"Your final hand: {user_hand}, final score: {calculate_score(user_hand)}\nComputer's final hand: {pc_hand}, final score: {calculate_score(pc_hand)}")