My python blackjack game is not working as intended - python

The problems are:
Upon typing n to stand and winning, it doesnt ask the user again if they want to play a game of blackjack.
And upon winning it also does not ask the user if it wants to play, straight up just starts the game once again.
Please help me solve this, I lost all hope while debugging...
p.s. #clear and #art are placeholders
import random
active_game = True # - Active flag
def restart_game():
# clear()
# print(logo)
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
cards_player = [random.choice(cards), random.choice(cards)]
cards_dealer = [random.choice(cards), random.choice(cards)]
def total(cards_entity): # count someone's cards
return sum(cards_entity)
print(f" Your cards: {cards_player}, current score: {total(cards_player)}")
print(f" Dealer's first card: {cards_dealer[0]}")
def final_score():
print(f" Your final hand: {cards_player}, final score: {total(cards_player)}")
print(f" Dealer's final hand: {cards_dealer}, final score: {total(cards_dealer)}")
def winner(): #-checks result of move
if total(cards_player) == 21: # player got 21
if total(cards_dealer) == 21:
print("You both scored a blackjack. It's a draw! 🤷‍♂️")
final_score()
restart_game()
else:
print("You scored a blackjack. You won! 🤑")
final_score()
restart_game()
if total(cards_player) > 21: # player went over 21
if 11 in cards_player:
i = cards_player.index(11)
cards_player[i] = 1
else:
print("You went over. You lost! 😤")
final_score()
restart_game()
if total(cards_player) < 21: # player got less than 21
if total(cards_dealer) > 21:
print("The opponent went over. You won! 🤑")
final_score()
restart_game()
if total(cards_dealer) == 21:
print("The opponent got 21! You lost! 😤")
final_score()
restart_game()
def move():
if input("Type 'y' to get another card, type 'n' to pass: ") == "y":
cards_player.append(random.choice(cards))
cards_dealer.append(random.choice(cards))
print(f"Your cards: {cards_player}, current score: {total(cards_player)}")
print(f"Dealer's first card: {cards_dealer[0]}")
winner()
else:
cards_dealer.append(random.choice(cards))
winner()
move()
while input("Would you like to play a game of Black Jack? Type 'y' or 'n': ") == "y":
restart_game()
print("I'm out!")

Just replace the restart_game() statement from each branch of winner function with return.
In this way, after each game you would return to the while loop, where you called the restart_game() function.
Final Code:
import random
def restart_game():
# clear()
# print(logo)
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
cards_player = [random.choice(cards), random.choice(cards)]
cards_dealer = [random.choice(cards), random.choice(cards)]
def total(cards_entity): # count someone's cards
return sum(cards_entity)
print(f" Your cards: {cards_player}, current score: {total(cards_player)}")
print(f" Dealer's first card: {cards_dealer[0]}")
def final_score():
print(f" Your final hand: {cards_player}, final score: {total(cards_player)}")
print(f" Dealer's final hand: {cards_dealer}, final score: {total(cards_dealer)}")
def winner(): #-checks result of move
if total(cards_player) == 21: # player got 21
if total(cards_dealer) == 21:
print("You both scored a blackjack. It's a draw! 🤷‍♂️")
final_score()
# restart_game()
return
else:
print("You scored a blackjack. You won! 🤑")
final_score()
# restart_game()
return
if total(cards_player) > 21: # player went over 21
if 11 in cards_player:
i = cards_player.index(11)
cards_player[i] = 1
else:
print("You went over. You lost! 😤")
final_score()
# restart_game()
return
if total(cards_player) < 21: # player got less than 21
if total(cards_dealer) > 21:
print("The opponent went over. You won! 🤑")
final_score()
# restart_game()
return
if total(cards_dealer) == 21:
print("The opponent got 21! You lost! 😤")
final_score()
# restart_game()
return
def move():
if input("Type 'y' to get another card, type 'n' to pass: ") == "y":
cards_player.append(random.choice(cards))
cards_dealer.append(random.choice(cards))
print(f"Your cards: {cards_player}, current score: {total(cards_player)}")
print(f"Dealer's first card: {cards_dealer[0]}")
winner()
else:
cards_dealer.append(random.choice(cards))
winner()
move()
while input("Would you like to play a game of Black Jack? Type 'y' or 'n': ") == "y":
restart_game()
print("I'm out!")

Upon typing n to stand and winning, it doesnt ask the user again if they want to play a game of blackjack.
This line makes sure that the user will not be asked to play a game of blackjack if the user input is not y. Since n is not y, it will not ask the user again upon typing n:
while input("Would you like to play a game of Black Jack? Type 'y' or 'n': ") == "y":
restart_game()
And upon winning it also does not ask the user if it wants to play, straight up just starts the game once again.
Instead of returning from the restart_game() function, this calls it again, so the code doesn't return to the while loop:
if total(cards_dealer) > 21:
print("The opponent went over. You won! 🤑")
final_score()
restart_game()

Related

Blackjack Capstone Project from 100 Days of Code with Dr. Angela Yu

This question is in relation to Dr Angela Yu's 11th day of Python tutorials. I am not able to execute the code I typed in. The code is typed in replit. Where am I making mistakes? This code is supposed to play the game of Blackjack.
import random
from replit import clear
from art import logo
def draw_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards)
def calculate_score(cards):
if sum(cards) == 21 and len(cards) == 2:
return 0
if sum(cards) > 21 and 11 in cards:
cards.remove(11)
cards.append(1)
return sum(cards)
def compare(user_score, computer_score):
if user_score > 21 and computer_score > 21:
print("You went over 21. You lost")
elif computer_score == 0:
print("You lost. Computer has blackjack")
elif user_score == 0:
print("You won with a blackjack.")
elif user_score == computer_score:
print("Draw")
elif user_score > 21:
print("You lost")
elif computer_score > 21:
print("you won")
elif user_score > computer_score:
print("You won.")
else:
print("Computer won")
def play_game():
print (logo)
user_cards = []
computer_cards = []
for number in range(2):
user_cards.append(draw_card())
computer_cards.append(draw_card())
game_end = False
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f" Your cards: {user_cards}, your score: {user_score}.")
print(f" Computer's first card: {computer_cards[0]}")
get_card = input("Type 'y' to get another card, type 'n' to pass: ")
if get_card == "y".lower():
user_cards.append(draw_card())
else:
game_end = True
while computer_score < 17:
computer_cards.append(draw_card)
print(f" Your final hand: {user_cards}, final score: {user_score}")
print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
print(compare(user_score, computer_score))
play = input("Do you want to play a game of blackjack. Type y or n: ").lower()
while play == "y":
clear()
play_game()
I am not able to debug this code in thonny due to some functions I can only find in replit.
You never recompute computer_score, so computer_score < 17 will stay True forever.
There are bugs in your code.Here are the solutions.
Do this:
#The main bug is that the program gets stuck at while loop in around lineNO 62 where it says "while computer_score < 17:"
#I could solve it for you but i don't know the game, so do something there.
#My suggestion: use if statement instead of while loop.

problem in logic over python code creating blackjack project

this is my code below
it is work right but the problem is in my logic if i asked the user if he wants another card the game reload from the start you can try it there https://replit.com/#KamalSalm/blackjack-start-1#main.py if you want
the code works right but the problem is in asked the user for another card
import random
import art
from replit import clear
############### Blackjack Project #####################
#Difficulty Normal 😎: Use all Hints below to complete the project.
#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
#Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.
#Difficulty Expert 🤯: Only use Hint 1 to complete the project.
############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in the list have equal probability of being drawn.
## Cards are not removed from the deck as they are drawn.
## The computer is the dealer.
##################### Hints #####################
#Hint 1: Go to this website and try out the Blackjack game:
# https://games.washingtonpost.com/games/blackjack/
#Then try out the completed Blackjack project here:
# http://blackjack-final.appbrewery.repl.run
#deck
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
#logo blackjack
def logo():
"""show logo"""
print(art.logo)
#user cards
def add_card():
return random.choice(cards)
#the final cards
the_cards ={}
game_on = True
while game_on:
user_response = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower()
if user_response == "y":
clear()
the_cards["user_cards"] = [add_card() , add_card()]
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"] = [add_card()]
total_com = sum(the_cards['com_cards'])
print(art.logo)
print(f" your cards: {the_cards['user_cards']}, current score is :{total_user} ")
print(f" computer is first card is {the_cards['com_cards']}")
#ask user if he want another card or pass
if total_user == 21:
print("game over you win it's blackjack")
game_on = False
elif total_user < 21 and total_com < 21:
ask_user = input("would you choose another card ").lower()
if ask_user == "y":
total_user += add_card()
if total_com > 13:
total_com += add_card()
if total_com == 21:
print("game over it's blackjack com win")
elif total_user > total_com:
print("you have won upper hand")
elif total_user < total_com:
print("you have lost not good hand")
elif ask_user =="n":
if total_user > total_com:
print("you have won your cards beat com")
elif total_user < total_com:
print("you have lose com has bigger hands")
else:
if total_user > 21:
print("game over you lose it is over 21")
elif total_com > 21:
print("you win computer cards over 21 ")
elif user_response == "n":
print("game over you can try again if you like")
game_on = False
else:
print("you type it wrong try again")
without to give the complete solution, i just sugget to refactor your code with 2 while loops, to separate the game play from the another card:
# the final cards
the_cards = {}
launch_game = 'y'
while launch_game == 'y':
user_response = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower()
game_on = True
total_user = 0
total_com = 0
while user_response == 'y' and game_on:
if total_user == 0:
the_cards["user_cards"] = [add_card(), add_card()]
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"] = [add_card(), add_card()]
total_com = sum(the_cards['com_cards'])
else:
the_cards["user_cards"].append(add_card())
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"].append(add_card())
total_com = sum(the_cards['com_cards'])
print(f" your cards: {the_cards['user_cards']}, current score is :{total_user} ")
print(f" computer's card: {the_cards['com_cards']}, current score is :{total_com} ")
game_on = False
if total_user == 21:
print("game over you win it's blackjack")
continue
if total_com == 21:
print("game over you lose it's blackjack for computer")
continue
if total_user > 21:
print("game over you lose it is over 21")
continue
if total_com > 21:
print("you win computer cards over 21 ")
continue
ask_user = input("would you choose another card ").lower()
if ask_user == "y":
game_on = True
continue
else: #and if total_user == total_com?
if total_user > total_com:
print("you have won your cards beat com")
elif total_user < total_com:
print("you have lose com has bigger hands")
it will easier for you to trap problem in your code!

Need assistance on blackjack python project implementing hit/stand feature

im just working on a blackjack project and im new to coding so its a little tough trying to add new functions such as the hit/stand function. I have tried making a hit/stand function but im not sure how to actually add a new card to the total of the players cards and the dealer also. im just staring by adding the players to try and get some result but a am just stuck at this rate and have no idea how i can properly implement this. I have a sep file that stores the list of the deck and shuffle but is imported
import playing_cards
import random
player_hand = []
dealers_hand = []
hands = [[]]
#STAGE 1 - testing purpose only
# Testing code for step 1
##card = playing_cards.deal_one_card()
##print(card)
#Stage 2 - testing purpose only (PLAYERS HAND)
# Deal first card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
# Deal second card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
#ADDING UP BOTH CARDS
# Display the player's hand to the screen using a simple print statement
#print("Player's hand is ", player_hand)
#Stage 4 and 5
suits = {'C': 'Club', 'H': 'Heart', 'D': 'Diamond', 'S': 'Spade'}
names = {'2': '2', '3': '3', '4': '4',
'5':'5', '6': '6', '7': '7', '8': '8', '9': '9', 'T': '10','J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}
def score_hand(player_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in player_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in player_hand)
score -= adjustment
return score
#ask about this
def show_result(player_hand):
player_score = int(score_hand(player_hand))
if player_score > 21:
print('*** Player Bust! ***')
elif player_score == 21:
print('*** Blackjack! Player Wins! ***')
##else:
## push(player_hand,dealer_hand)
##def push(player_score,dealers_score):
## print("Dealer and Player tie! It's a push.")
##else:
## // Logic to continue game
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
hit(show_hand,player_hand) # hit() function defined above
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
def show_hand(player_hand):
score_hand(player_hand)
score = f"Player's hand is {score_hand(player_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in player_hand])
return score + cards
for hand in hands:
print(show_hand(player_hand))
show_result(player_hand)
#Stage 3 - Testing purpose only (DEALERS HAND)
### Deal first card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Deal second card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Display the player's hand to the screen using a simple print statement
#Stage 4 and 5
def score_hand(dealers_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in dealers_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in dealers_hand)
score -= adjustment
return score
#ask about this
def show_result(dealers_hand):
dealers_score = int(score_hand(dealers_hand))
if dealers_score > 21:
print('*** Dealer Bust! ***')
elif dealers_score == 21:
print('*** Blackjack! Dealer Wins! ***')
def show_hand(dealers_hand):
score = f"Dealers's hand is {score_hand(dealers_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in dealers_hand])
return score + cards
for hand in hands:
print(show_hand(dealers_hand))
print('')
show_result(dealers_hand)
hit_stand(show_hand, player_hand)
import random
Dealer_Cards=[]
Player_Cards=[] # im also beginner in programming just little know some C from College
Total_Player=0 # and watched some tutorial like 5 min and get the whole algorithm
# then start thinking and coding i have little excuse like how to i
Total_Dealer=0 # stop when player or dealer hit >=21 expect option .
#Deal the cards
#Dealer Cards
while len(Dealer_Cards) != 2:
Dealer_Cards.append(random.randint(1,11))
if len(Dealer_Cards) == 2:
print("Dealer has ",Dealer_Cards)
# Player Cards
while len(Player_Cards) != 2:
Player_Cards.append(random.randint(1,11))
if len(Player_Cards) == 2:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Hit and if you want to Stay click '0']:")
option= int(input(""))
if option == 0:
Total_Dealer+= sum(Dealer_Cards) #Dealer_Cards= i
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards) # Player_Cards= x
print("sum of the Player cards:",Total_Player)
if Total_Dealer > Total_Player:
print("Dealer Wons")
break
elif Total_Player > Total_Dealer:
print("You Won")
break
else:
print("Scoreless.")
break
elif option == 1:
while len(Player_Cards) != 3:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 3:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option== 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 4:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 4:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option == 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 5:
Player_Cards.append(random.randint(1, 11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 5:
print("You have ",Player_Cards)
Total_Dealer+= sum(Dealer_Cards)
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards)
print("sum of the Player cards:",Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
Maybe this will get you on the right track (I couldn't find a 'hit' function defined, so you can do all the work right in hit_stand, as follows):
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
player_hand.append(playing_cards.deal_one_card())
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
That will solve how the player hits, but I didn't see logic in your code for the dealer to decide to hit or stand, which are based on standard house rules.

unexpected 'NoneType' object is not iterable error when returning a tuple

I'm building a simple blackjack game and sometimes after a when either you want to stay, or when the dealer stays I get a 'NoneType'object is not iterable error. I believe that it is happening at the return of True, total in both the move() and dealer() functions, but can't see why this would be happening. I'm very new to python so I'm sure it's an easy fix.
Any help?
import random
import re
def make_deck(deck):
deck.append("Clubs_Ace")
deck.append("Clubs_2")
deck.append("Clubs_3")
deck.append("Clubs_4")
deck.append("Clubs_5")
deck.append("Clubs_6")
deck.append("Clubs_7")
deck.append("Clubs_8")
deck.append("Clubs_9")
deck.append("Clubs_10")
deck.append("Clubs_Jack")
deck.append("Clubs_Queen")
deck.append("Clubs_King")
deck.append("Spades_Ace")
deck.append("Spades_2")
deck.append("Spades_3")
deck.append("Spades_4")
deck.append("Spades_5")
deck.append("Spades_6")
deck.append("Spades_7")
deck.append("Spades_8")
deck.append("Spades_9")
deck.append("Spades_10")
deck.append("Spades_Jack")
deck.append("Spades_Queen")
deck.append("Spades_King")
deck.append("Hearts_Ace")
deck.append("Hearts_2")
deck.append("Hearts_3")
deck.append("Hearts_4")
deck.append("Hearts_5")
deck.append("Hearts_6")
deck.append("Hearts_7")
deck.append("Hearts_8")
deck.append("Hearts_9")
deck.append("Hearts_10")
deck.append("Hearts_Jack")
deck.append("Hearts_Queen")
deck.append("Hearts_King")
deck.append("Diamonds_Ace")
deck.append("Diamonds_2")
deck.append("Diamonds_3")
deck.append("Diamonds_4")
deck.append("Diamonds_5")
deck.append("Diamonds_6")
deck.append("Diamonds_7")
deck.append("Diamonds_8")
deck.append("Diamonds_9")
deck.append("Diamonds_10")
deck.append("Diamonds_Jack")
deck.append("Diamonds_Queen")
deck.append("Diamonds_King")
return deck
def draw_card(deck):
card=deck[len(deck)-1]
deck.remove(card)
return card
def shuffle_deck(deck):
shuffled_deck=random.shuffle(deck)
return deck
def cardval(card,total):
if "2" in card or "3" in card or "4" in card or "5" in card or "6" in card or "7" in card or "8" in card or "9" in card or "10" in card:
return int(re.findall("\d+",card)[0])
elif "Jack" in card or "Queen" in card or "King" in card:
return 10
elif "Ace" in card:
if total <= 10:
return 11
else:
return 1
def deal(deck):
print("Your cards:")
draw1=draw_card(deck)
draw2=draw_card(deck)
total=0
dealersTotal=0
total=cardval(draw1,total)
total+=(cardval(draw2,total))
print(draw1,draw2," Total:",total,"\n")
print("Dealers cards:")
draw3=draw_card(deck)
dealersTotal+=cardval(draw3,dealersTotal)
print(draw3," face_down_card Dealers Total:",dealersTotal)
face_down=draw_card(deck)
dealersTotal+=cardval(face_down,dealersTotal)
return total, dealersTotal,face_down;
def move(total,deck):
choice = input("Would you like to hit or stay? (h to hit, s to stay)")
if choice is 'h':
draw=draw_card(deck)
total+=cardval(draw,total)
print(draw," Total:",total,"\n")
if total > 21:
print('bust')
return False, total
else: move(total,deck)
elif choice is 's':
return True, total
def dealer(dealersTotal,deck):
if dealersTotal < 17:
draw=draw_card(deck)
dealersTotal+=cardval(draw,dealersTotal)
print("\nDealer hits ",draw,"dealers Total ",dealersTotal)
if dealersTotal > 21:
print("Dealer bust, you win!")
return True,dealersTotal
elif dealersTotal in range(17,21):
return False,dealersTotal
elif dealersTotal < 17:
dealer(dealersTotal,deck)
def again():
again=input("Would you like to play again? (y for yes, n for no):")
if again is 'y':
print("\n\n\n")
driver()
elif again is 'n':
print("Thanks for playing")
def driver():
deck=[]
shuffled_deck=[51]
total=0
dealersTotal=0
deck=make_deck(deck)
shuffled_deck=shuffle_deck(deck)
total, dealersTotal, face_down=deal(shuffled_deck)
player_move,total=move(total,shuffled_deck)
if player_move is False:
again()
elif player_move is True:
result,dealersTotal=dealer(dealersTotal,shuffled_deck)
if result is False:
again()
elif result is True:
print("Your total:",total,"Dealers total:",dealersTotal)
if total > dealersTotal:
print("\nYou win!\n")
again()
elif dealersTotal > total:
print("\nYou loose :(\n")
again()
driver()

getting the correct value in blackjack [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a question about the sum of the cards dealt. When running the code, it doesn't give you the right amount of the two cards added up, i.e. cards [2, 8] would equal 24.. when it is only 10. What is going on? Any help is greatly appreciated!
Is there anything else that seems wrong? If any of my comments are wrong, please, feel free to correct me!
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4
def deal(deck): # deck function
hand = []
for i in range(2):
random.shuffle(deck) # shuffles deck
card = deck.pop() # removes and returns the value back to card
if card == 11: card = "J" # sets 11 to jack
if card == 12: card = "Q" # sets 12 to queen
if card == 13: card = "K" # sets 13 to king
if card == 14: card = "A" # sets 14 to ace
hand.append(card)
return hand
def play_again(): # ask payer if wants to play again function
again = raw_input("Do you want to play again? (Y/N) : ").lower()
if again == "y": # if answers yes, will give the player more cards
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 # sets deck to values of cards
game()
else:
print ("Bye!") # exits program
exit()
def total(hand):
total = 0 # start off with total of zero
for card in hand: # for the cards you dealt
if card == "J" or card == "Q" or card == "K": # if the card is j,q,k it equals 10
total += 10
elif card == "A":
if total >= 11: total += 1 # if the card is an A, if the total is more than 11, it makes the vaue 1
else:
total += 11 # makes the value of the ace 1 if the total is greater than 11
else:
total += card # adds up your cards
return total
def hit(hand):
card = deck.pop() # removes and returns the value back to card
if card == 11: card = "J" # setting the card number to the face value
if card == 12: card = "Q"
if card == 13: card = "K"
if card == 14: card = "A"
hand.append(card)
return hand
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
def print_results(dealer_hand, player_hand): # funtcion for results of hand
clear()
print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand))) # gives you dealers hand
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # gives you your hand
def blackjack(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand) # prints dealers and your hand
print ("Congratulations! You got a Blackjack!\n")
play_again()
elif total(dealer_hand) == 21: # if hand is more than 21,
print_results(dealer_hand, player_hand) # prints out dealer and your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
play_again()
def score(dealer_hand, player_hand):
if total(player_hand) == 21: # if your hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations! You got a Blackjack!\n")
elif total(dealer_hand) == 21: # if dealer hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
elif total(player_hand) > 21: # if your hand is greater than
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. You busted. You lose.\n")
elif total(dealer_hand) > 21: # if dealer hand is greater than 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Dealer busts. You win!\n")
elif total(player_hand) < total(dealer_hand): # if your hand is less than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. Your score isn't higher than the dealer. You lose.\n")
elif total(player_hand) > total(dealer_hand): # if your hand is higher than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations. Your score is higher than the dealer. You win\n")
def game():
choice = 0
clear()
print ("WELCOME TO BLACKJACK!\n") # welcomes player to game
dealer_hand = deal(deck) # deals to dealers
player_hand = deal(deck) # deals to player
while choice != "q":
print ("The dealer is showing a " + str(dealer_hand[0])) # shows what one of the dealers card is
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # shows you your hand
blackjack(dealer_hand, player_hand) # send inormation to blackjack funciton
choice = raw_input(
"Do you want to [H]it, [S]tand, or [Q]uit: ").lower() # gets user input on if they want to hit, stand, or quit
clear()
if choice == "h":
hit(player_hand) # adds a new card value to your exisiting han d
while total(dealer_hand) < 17: # dealer has to hit is value of cards below 17
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "q":
print("Bye!")
exit()
if __name__ == "__main__":
game()
The code you pasted has some indentation issues. I fixed that and ran the code, and getting proper results:
WELCOME TO BLACKJACK!
The dealer is showing a 5
You have a ['A', 8] for a total of 19
Do you want to [H]it, [S]tand, or [Q]uit: S
The dealer has a [5, 4, 7] for a total of 16
You have a ['A', 8] for a total of 19
Congratulations. Your score is higher than the dealer. You win
Do you want to play again? (Y/N) :
Also pasting here the indented code:
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
def deal(deck): # deck function
hand = []
for i in range(2):
random.shuffle(deck) # shuffles deck
card = deck.pop() # removes and returns the value back to card
if card == 11:
card = "J" # sets 11 to jack
if card == 12:
card = "Q" # sets 12 to queen
if card == 13:
card = "K" # sets 13 to king
if card == 14:
card = "A" # sets 14 to ace
hand.append(card)
return hand
def play_again(): # ask payer if wants to play again function
again = raw_input("Do you want to play again? (Y/N) : ").lower()
if again == "y": # if answers yes, will give the player more cards
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4 #sets deck to values of cards
game()
else:
print ("Bye!") # exits program
exit()
def total(hand):
total = 0 # start off with total of zero
for card in hand: # for the cards you dealt
if card == "J" or card == "Q" or card == "K": # if the card is j,q,k it equals 10
total += 10
elif card == "A":
if total >= 11:
total+= 1 # if the card is an A, if the total is more than 11, it makes the vaue 1
else:
total += 11 # makes the value of the ace 1 if the total is greater than 11
else:
total += card # adds up your cards
return total
def hit(hand):
card = deck.pop() # removes and returns the value back to card
if card == 11:
card = "J" # setting the card number to the face value
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
def print_results(dealer_hand, player_hand): # funtcion for results of hand
clear()
print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand))) # gives you dealers hand
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # gives you your hand
def blackjack(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand) # prints dealers and your hand
print ("Congratulations! You got a Blackjack!\n")
play_again()
elif total(dealer_hand) == 21: # if hand is more than 21,
print_results(dealer_hand, player_hand) # prints out dealer and your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
play_again()
def score(dealer_hand, player_hand):
if total(player_hand) == 21: # if your hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations! You got a Blackjack!\n")
elif total(dealer_hand) == 21: # if dealer hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
elif total(player_hand) > 21: # if your hand is greater than
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. You busted. You lose.\n")
elif total(dealer_hand) > 21: # if dealer hand is greater than 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Dealer busts. You win!\n")
elif total(player_hand) < total(dealer_hand): # if your hand is less than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. Your score isn't higher than the dealer. You lose.\n")
elif total(player_hand) > total(dealer_hand): # if your hand is higher than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations. Your score is higher than the dealer. You win\n")
def game():
choice = 0
clear()
print ("WELCOME TO BLACKJACK!\n") # welcomes player to game
dealer_hand = deal(deck) # deals to dealers
player_hand = deal(deck) # deals to player
while choice != "q":
print ("The dealer is showing a " + str(dealer_hand[0])) # shows what one of the dealers card is
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # shows you your hand
blackjack(dealer_hand, player_hand) # send inormation to blackjack funciton
choice = raw_input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower() # gets user input on if they want to hit, stand, or quit
clear()
if choice == "h":
hit(player_hand) # adds a new card value to your exisiting han d
while total(dealer_hand) < 17: # dealer has to hit is value of cards below 17
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "q":
print("Bye!")
exit()
if __name__ == "__main__":
game()
Let me know if this helped.

Categories