Blackjack, won't restart game in python - python

Right now I'm having trouble with the code restarting. It restarts but it doesn't go back to the beginning. It just keeps asking me if I want to restart.
For example it says
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
I type in Y and it keeps saying
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
Can anyone please fix it so that it will restart. - or tell me how to my code is below.
from random import choice as rc
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def total(hand):
# how many aces in the hand
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
if t > 21 and aces > 0:
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
c2win = 0 # computer2 win
cwin = 0 # computer win
pwin = 0 # player win
while True:
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
c2bust = False # computer2 busted
while True:
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
print('Start over? Y/N')
answer = input()
if answer == 'n':
done = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
print("do you want to play again?")
answer = input()
if answer == 'y':
done = False
else:
break
else:
hs = input("Hit or Stand/Done (h or s): ").lower()
if 'h' in hs:
player.append(rc(cards))
if 's' in hs:
player.append(rc(cards))
while True:
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
comp2 = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
if pbust == False:
print ("Player wins!")
pwin += 1
print('Start over? Y/N')
answer = input()
if answer == 'y':
playAgain()
if answer == 'n':
done = True
elif tc > tp:
print ("Computer wins!")
cwin += 1
elif tc == tp:
print ("It's a draw!")
elif tp > tc:
if pbust == False:
print ("Player wins!")
pwin += 1
elif cbust == False:
print ("Computer wins!")
cwin += 1
break
print
print ("Wins, player = %d computer = %d" % (pwin, cwin))
exit = input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print
print
print ("Thanks for playing blackjack with the computer!")

fun little game, I removed the second dealer for simplicity, but it should be easy enough to add back in. I changed input to raw_input so you could get a string out of it without entering quotes. touched up the logic a bit here and there, redid formating and added comments.
from random import choice as rc
def play_again():
"""This function returns True if the player wants to play again,
otherwise it returns False."""
return raw_input('Do you want to play again? (yes or no)').lower().startswith('y')
def total(hand):
"""totals the hand"""
#special ace dual value thing
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0 # computer win
pwin = 0 # player win
while True:
# Main Game Loop (multiple hands)
pbust = False # player busted
cbust = False # computer busted
# player's hand
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
while True:
# Player Game Loop (per hand)
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
break
else:
hs = raw_input("Hit or Stand/Done (h or s): ").lower()
if hs.startswith('h'):
player.append(rc(cards))
else:
break
#Dealers Hand
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
tc = total(comp)
while tc < 18:
# Dealer Hand Loop
comp.append(rc(cards))
tc = total(comp)
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
# Time to figure out who won
if cbust or pbust:
if cbust and pbust:
print ("both busted, draw")
elif cbust:
print ("Player wins!")
pwin += 1
else:
print ("Computer wins!")
cwin += 1
elif tc < tp:
print ("Player wins!")
pwin += 1
elif tc == tp:
print ("It's a draw!")
else:
print ("Computer wins!")
cwin += 1
# Hand over, play again?
print ("\nWins, player = %d computer = %d" % (pwin, cwin))
exit = raw_input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print ("\n\nThanks for playing blackjack with the computer!")

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.

How log my score best out of three and use different symbols for the players? Python

I'm making a 2-play Battleship game in python and have been struggling with this for a while now:
I apologise if the question is poorly worded but I was to know how I can make my game log the match score at the end of the three games with something like:
print('Match score is' + score + 'Player' + (whoever) + 'wins!)
I'm not entirely sure how to implement this myself I have a range for games in range(3), but I don't know how to log the final score.
Also, how can I change the symbol for player_two so that I am not using an 'X' for both players? I've tried changing the input_check() but I get more errors than I did before.
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
else:
return player_two
# Allows new game to start
def play_again():
global ship_points
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns(turns) == player_one:
# print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
You can use style string formatting to print the log.
print('Match score is %d : %d(Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
For more information about string formatting, check this link.
To change the symbol for Player 2, you can change the following code.
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"

blackjack game for python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making a blackjack game on Python for a school project. I have made the main part of my game but I keep getting a syntax error. I have tried to debug it, but I can not work out what is wrong.
Here is my code -
def total(hand):
aces = hand.count(11)
t = sum(hand)
if t > 21 and aces > 0:
while aces > 0 and t > 21:
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0
pwin = 0
while True:
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False
cbust = False
while True:
tp = total(player)
print "The player has these cards %s with a total value of %d" % (player, tp)
if tp > 21:
print "--> The player is busted!"
pbust = True
break
elif tp == 21:
print "\a BLACKJACK!!!"
break
else:
hs = raw_input("Hit or Stand/Done (h or s): ").lower()
if 'h' in hs:
player.append(rc(cards))
else:
break
while True:
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print "the computer has %s for a total of %d" % (comp, tc)
if tc > 21:
print "--> The computer is busted!"
cbust = True
if pbust == False:
print "The player wins!"
pwin += 1
elif tc > tp:
print "The computer wins!"
cwin += 1
elif tc == tp:
print "It's a draw!"
elif tp > tc:
if pbust == False:
print "The player wins!"
pwin += 1
elif cbust == False:
print "The computer wins!"
cwin += 1
break
print
print "Wins, player = %d computer = %d" % (pwin, cwin)
exit = raw_input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print "Thanks for playing blackjack with the computer!"
I run 3.3.2 I have edited slightly and now get this.
In Python 3 print is a function. That means you must use parenthesis with print.
>>> print '?'
File "<stdin>", line 1
print '?'
^
SyntaxError: invalid syntax
>>> print('!')
!

Categories