I'm in the progress of building a basic blackjack game and I've made a while loop that should terminate once either player hand or house hand is greater than 21 but it just keeps looping?
the crazy thing is that I actually did make it work once but I accidentally broke it again while testing another function that I tried to get working (turning the 11 into a 1 if greater than 21) and I can't seem to get it working again?
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_hand = []
house_hand = []
def player_opening_hand():
for hand in range (0,2):
player_hand.append(random.choice(cards))
def house_opening_hand():
for hand in range(0,2):
house_hand.append(random.choice(cards))
def total_score(hand):
return sum(hand)
def new_draw(draw):
draw.append(random.choice(cards))
# if total_score(draw) > 21 and 11 in draw:
# draw[11] = 1
def current_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's first card: {house_hand[0]}")
def final_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's cards: {house_hand}, house total score: {total_score(house_hand)}")
#Intro to the player
begin = input('welcome to pyjack, would you like to start a new game? enter "y" or "n": ')
if begin == 'y':
# first two cards for both players are dealt,
player_opening_hand()
house_opening_hand()
current_score()
if total_score(player_hand) == 21:
print('you won!')
else:
while total_score(player_hand) and total_score(house_hand) < 21:
player_choice = input('Type "y" to get another draw or type "n" to pass: ')
if player_choice == 'y':
new_draw(player_hand)
current_score()
if total_score(player_hand) > 21:
final_score()
print('you went over 21, you lose!')
elif total_score(player_hand) > total_score(house_hand):
final_score()
print('your hand is bigger than the house! you win!')
elif total_score(player_hand) == 21 and total_score(house_hand) < 21:
final_score()
print('Blackjack! you win!')
else:
final_score()
print('you lose!')
CodePudding user response:
while total_score(player_hand) and total_score(house_hand) < 21:
does not do what you think it does. The correct code is
while total_score(player_hand) < 21 and total_score(house_hand) < 21:
CodePudding user response:
You always have to mention the both conditions using AND
or OR
operators.
Here condition is to be:
while total_score(player_hand) < 21 and total_score(house_hand) < 21:
I hope this will work for you.