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('!')
!
Related
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.
so the ultimate goal is to run best 2 out of 3 games of rock, paper, scissors, lizard, spock. i haven't added a loop yet or anything like that i'm trying to get the game itself running first but I'm coming across a NameError, it's saying the 'result' variable is undefined.
I've tried returning it but that doesn't appear to be working, but I also maybe don't know what I'm doing?
def number_to_name(number):
if number == 1:
return 'scissors'
elif number == 2:
return 'rock'
elif number == 3:
return 'paper'
elif number == 4:
return 'lizard'
elif number == 5:
return 'spock'
else:
print ("Error: Invalid number")
def name_to_number(name):
if name == 'scissors':
return 1
elif name == 'rock':
return 2
elif name == 'paper':
return 3
elif name == 'lizard':
return 4
elif name == 'spock':
return 5
else:
print ("Error: Invalid number")
def rpsls(name):
player_score, computer_score = (0, 0)
player_input = name_to_number(name)
computer_input = random.randint(1,5)
result = (player_input - computer_input) % 5
if result == 1 or result == 2:
print("player wins")
player_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 3 or result == 4:
game = "computer wins"
computer_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 0:
game = "it's a tie"
print("Player {}, Computer {}". format(player_score, computer_score))
else:
print("error")
rpsls("rock")
rpsls("spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
Your conditions should be inside the rpsls function.Because you result variable is local variable. You can't fetch this variable globally.
> def rpsls(name):
> player_score, computer_score = (0, 0)
> player_input = name_to_number(name)
> computer_input = random.randint(1, 5)
> result = (player_input - computer_input) % 5
>
>
> if result == 1 or result == 2:
> print("player wins")
> player_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 3 or result == 4:
> game = "computer wins"
> computer_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 0:
> game = "it's a tie"
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> else:
> print("error")
Your variable result is inside the function rpsls. So the scope of result lies to the function only.
A easy solution would be assign a 0 value to result before the function 'rpsls'
This way your updating a globally defined variable inside the function.
result = 0
def rpsls(name):
#Your code
The best way would be to write a class, have a class level variable result, and put all this code into the class.
First of all, since result is only defined in the function, it is only accessable inside that specific function, unless you choose to use the global method, which I wouldn't recommend.
Second, since you called result before you called the function that actually defines result, even if you use global, it will still not be defined for that specific line.
I'm trying to write the Camel game using functions instead of so many nested if statements. I think I've done something wrong though, I've had to tinker with the native distance portion a lot as I kept getting into parts where they only got further away not closer. But now after trying to change the randomint values I can never escape them. Any suggestions for improvement are much appreciated!
Here is my code:
import random
def quitGame():
print("I am guitting now.")
return True
def status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks):
print(
"""
You have traveled %d miles
Your Camel Status is %d (lower is better)
You have %d drinks left in your canteen
Your thirst is %d (lower is better)
The Natives are %d miles behind you
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
def rest():
print("The camel is happy")
distanceN = random.randint(7,14)
return(distanceN)
def fullSpeed():
distanceT = random.randint(10,20)
print("You travel %d miles"%distanceT)
camelT = random.randint(1,3)
distanceN = random.randint(7,14)
return(distanceT,camelT,distanceN)
def moderateSpeed():
distanceB = random.randint(5,12)
print("You travel %d miles"%distanceB)
nativesB = random.randint(7,14)
return(distanceB,nativesB)
def thirsty(drinksLeft):
drinksL = drinksLeft - 1
return(drinksL)
def main():
choice = ""
done = False # loop variable
#variables for game
milesTraveled = 0
thirst = 0
camelTiredness = 0
distanceNativesTraveled = -20
drinks = 5
print(
"""
Welcome to the Camel Game!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down. Survive your
desert trek and out run the native.
"""
)
while not done:
findOasis = random.randint(1,20)
print(
"""
Here are your choices:
A - Drink from you canteen.
B - Ahead moderate speed.
C - Ahead full speed.
D - Stop and rest for night.
E - Status check.
Q - Quit the Game
"""
)
choice = input(" Your choice?\n")
if choice.upper() == "Q":
done = quitGame()
elif findOasis is 1 :
print("Wow! You've found an Oasis. Your thirst is quenched, canteen topped off, \
and your camel is now well rested and happy.")
drinks = 5
thirst = 0
camelTiredness = 0
elif choice.upper() == "A":
if drinks > 0:
drinks = thirsty(drinks)
thirst = 0
else:
print("Error: Uh oh! No water left.")
elif choice.upper() == "B":
milesB,nativesB = moderateSpeed()
milesTraveled += milesB
camelTiredness += 1
thirst += 1
distanceNativesTraveled += nativesB
elif choice.upper() == "C":
milesT,camelTired,nativesT= fullSpeed()
milesTraveled += milesT
camelTiredness += camelTired
distanceNativesTraveled += nativesT
thirst += 1
elif choice.upper() == "D":
distanceT = rest()
camelTiredness = 0
distanceNativesTraveled += distanceT
elif choice.upper() == "E":
statusCheck = status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks)
else:
print("That was not a correct choice - Enter (A through E or Q)")
if thirst > 4 and thirst <= 6:
print("You are thirsty")
elif thirst > 6:
print("GAME OVER \nYou died of thirst!")
done = True
elif camelTiredness > 5 and camelTiredness <= 8:
print("Your camel is getting tired")
elif camelTiredness > 8:
print("GAME OVER \nYour camel is dead.")
done = True
elif distanceNativesTraveled >= 0:
print("GAME OVER \nThe natives have captured you!")
done = True
elif distanceNativesTraveled > -15:
print("The natives are getting close!")
elif milesTraveled >= 200:
print("YOU WIN \nCongrats, you made it across the desert!")
done = True
# call main
main()
The game ends when distanceNativesTraveled >= 0 and yet there's no code at all to decrease distanceNativesTraveled. So with every turn distanceNativesTraveled keeping increasing, the game is bound to end quickly.
What you really want here is to check if distanceNativesTraveled has surpassed milesTraveled, so change:
elif distanceNativesTraveled >= 0:
to:
elif distanceNativesTraveled >= milesTraveled:
And for the check to see if natives are getting close, change:
elif distanceNativesTraveled > -15:
to:
elif distanceNativesTraveled - milesTraveled > -15:
And to properly show the how many miles the natives are behind you, you should show the difference between the miles you and the natives traveled, so change:
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
to:
"""%(milesTraveled,camelTiredness,drinks,thirst,milesTraveled - distanceNativesTraveled))
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!")
This is most of my code for my now working python blackjack game (or at least blackjack like game) I have now been told that I need to implement a time limit (user gets asked to input something and only has 3 or so seconds to give a response).
def deck():
cards = range(1, 12)
return choice(cards)
def dealer():
total = deck() + deck()
if total <= 15:
totalf = total + deck()
while totalf <= 21:
return totalf
if total > 15:
return total
def player():
card1 = deck()
card2 = deck()
hand = card1 + card2
print "Cards dealt: %d and %d" % (card1, card2)
while hand <= 21:
choice = raw_input("Would you like to hit or stand?: ")
print choice
if choice == "hit":
hand = hand + deck()
print "Current Total: %d" % hand
elif choice == "stand":
return hand
money = 100
highscore = 0
while money > 0:
opp = dealer()
me = player()
if me > opp:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif opp > 21:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif me > 21:
money = money - 20
print "Bust! Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif opp > me:
money = money - 20
print "Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif me == 21:
highscore = highscore + 10
money = money + 10
print "Blackjack! You have $%d!" % money
print "********************************************"
sleep(1)
print "Thank you for playing! Your highscore was $%d." % highscore
This is the code my professor has provided us with to do this:
import sys, time
from select import select
import platform
if platform.system() == "Windows":
import msvcrt
def input_with_timeout_sane(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = sys.stdin.readline().replace('\n','')
else:
s = default
print s
return s
def input_with_timeout_windows(prompt, timeout, default):
start_time = time.time()
print prompt,
sys.stdout.flush()
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32: #space_char
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
if len(input) > 0:
return input
else:
return default
def input_with_timeout(prompt, timeout, default=''):
if platform.system() == "Windows":
return input_with_timeout_windows(prompt, timeout, default)
else:
return input_with_timeout_sane(prompt, timeout, default)
I am completely lost how to merge these two pieces of code. I've tried for the past couple hours to get it to work but for whatever reason its just not working. Any help would be amazing. (I apologize for the wall of code).
You just need to call input_with_timeout function where you want the user's input.
In your player function:
def player():
card1 = deck()
card2 = deck()
hand = card1 + card2
print "Cards dealt: %d and %d" % (card1, card2)
while hand <= 21:
choice = input_with_timeout("Would you like to hit or stand?: ", 3, "stand")
print choice
if choice == "hit":
hand = hand + deck()
print "Current Total: %d" % hand
elif choice == "stand":
return hand
will prompt for an input, writing the "Would ... or stand" sentence before it. If the user do not answer before the timeout (in this case 3 second) the function will return "stand".
And be sure to include your professor's code in your main file.