2
\$\begingroup\$

I had to make this blackjack game for school, but this is only the first part. We only had to use a random value between 2 and 11 to generate the cards, as we will have a library of cards later, and the dealer will keep pulling cards until their total value is at or equal to 17. The player needs to decide whether they want to hit or stay, and will always bet $25. I want to clean up the code to make it clearer, as it seems a bit messy.

import random

def main():

  restart = True

  bank_balance = 1000
  player_name = input("Please enter your name: ")
  while (bank_balance >= 25 and restart == True):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      restart=True
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      restart=False


def play_hand(name):

  player= []
  dealer= []

  play_again = True

  dealer.append(random.randint(1, 11))

  player.extend([random.randint(1, 11), random.randint(1, 11)])

  print ('The dealer received card of value', *dealer)
  print(name, 'received cards of value', player[0], 'and', player[-1])
  print(f'Dealer total is {sum(dealer)}')
  print(f"{name}'s total is {sum(player)}", '\n')

  stay = False
  bust = False

  while (sum(player) <= 21 and stay == False and play_again == True):
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')

      print(f'Dealer total is {sum(dealer)}')
      print(f"{name}'s cards are", *player)
      print(f"{name}'s total is {sum(player)}", '\n') 

    elif (hors == 's'):
      stay=True
      print('stay')


  if (sum(player) > 21 ):
    bust = True
    print('You busted!')

  while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
    dealer.append(random.randint(1, 11))

    print('The dealers total is', sum(dealer), '\n')



  if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
    print("The dealer wins!")
  elif (sum(player) <= 21 and sum(player) > sum(dealer)):
    print("You win!")
  if (sum(dealer) > 21):
    print ('You win! The dealer busted!')
  if (sum(dealer) == sum(player)):
    print('Its a Tie! ')

main()
\$\endgroup\$
2
\$\begingroup\$

My main tip is to use break and continue to control the flow of your while loops rather than having a bunch of extra bools in the loop condition. For example, instead of:

  restart = True
  while (bank_balance >= 25 and restart == True):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      restart=True
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      restart=False

get rid of the restart flag and do:

  while bank_balance >= 25:

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      break

(Also, for a true/false value instead of saying flag == True or flag == False just say flag or not flag.)

You can apply this same principle to the loops in play_hand where you're checking several bools in each while loop:

  player_bust = False
  dealer_bust = False

  while True:
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')
    elif (hors == 's'):
      print('stay')
      break
    print(f'Dealer total is {sum(dealer)}')
    print(f"{name}'s cards are", *player)
    print(f"{name}'s total is {sum(player)}", '\n')
    if sum(player) > 21:
      player_bust = True
      break

  if not player_bust:
    while sum(dealer) > 17:
      dealer.append(random.randint(1, 11))
      print('The dealers total is', sum(dealer), '\n')
  if sum(dealer) > 21:
    dealer_bust = True

  if player_bust:
    print("You busted!")
  elif dealer_bust:
    print("You win!  The dealer busted!"
  elif sum(dealer) > sum(player):
    print("The dealer wins!")
  elif sum(player) < sum(dealer):
    print("You win!")
  else:
    print('Its a Tie! ')

The idea is to minimize the number of conditions that each check depends on; it gives you less to keep track of as you read your code and try to figure out what it's going to do in any given situation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.