oqiw2
oqiw2

Reputation: 13

My boolean flag isn't triggering when it's supposed to

At the play_again input, whenever I input "n" to end the loop, python seems to ignore it and prints :

Your cards: [x, x], current score: xx Computers first card: x. Would you like to draw another card? Press 'y' to draw or 'n' to stand.

Even though I have set end_game back to True. What gives?

import random
from art import logo
from replit import clear
def deal_card():
  cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  card = random.choice(cards)
  return card

def calculate_score(card_list):
  if len(card_list) == 2 and sum(card_list) == 21:
    return 0
  if 11 in card_list and sum(card_list) > 21:
    card_list.remove(11)
    card_list.append(1)

  return sum(card_list)  

def compare(user, computer):
  if user == computer:
    return "I'ts a draw!"
  elif user == 0:
    return "You win with a BlackJack!"
  elif computer == 0:
    return "Computer wins with a BlackJack!"
  elif computer > 21:
    return "You win! Computer busts."
  elif user > 21:
    return "Computer wins, you bust!"
  elif user > computer:
    return "You win!"
  else:
    return "You lose!"
def main_loop():
  print(logo)
  user_cards = []
  computer_cards = []
  game_end = False

  for _ in range(2):
    user_cards.append(deal_card())
    computer_cards.append(deal_card())

  while not game_end:
    user_score = calculate_score(user_cards)
    computer_score = calculate_score(computer_cards)
    print(f"Your cards: {user_cards}, current score: {user_score}")
    print(f"Computers first card: {computer_cards[0]}.")

    if user_score == 0 or computer_score == 0 or user_score > 21:
      game_end = True
    else:
      play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")

      if play_again == "y":
        user_cards.append(deal_card())
      else:
        end_game = True

  while computer_score != 0 and computer_score < 17:
    computer_cards.append(deal_card())
    computer_score = calculate_score(computer_cards)
        
  print(f"Your final hand: {user_cards}, Your final score{user_score}.")
  print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
  print(compare(user_score, computer_score))

while input("Would you like to play a game of BlackJack?: ") == 'y':
  clear()
  main_loop()
else:
  print('Goodbye!')
  quit()

Upvotes: 1

Views: 79

Answers (1)

ROHIT SURESH SAWANT
ROHIT SURESH SAWANT

Reputation: 46

Please check your variable name game_end in "while not game_end:" loop,

if user_score == 0 or computer_score == 0 or user_score > 21:
  game_end = True
else:
  play_again = input("Would you like to draw another card? Press 'y' to draw 
                     or 'n' to stand.")

  if play_again == "y":
    user_cards.append(deal_card())
  else:
    end_game = True

I think it's "game_end" in else: , you put end_game , please change it, other function working fine.

Upvotes: 1

Related Questions