Blackjack python dice game fix? - python

When someone says something else in replay() except for "no" or "yes" it starts the host's turn for some reason or even no.
I'm still learning, this is my second project, any comments?
I tried many things but it still doesn't work.
# Blackjack game
import random
global playername, nameofplayer
nameofplayer = input('Enter your name').capitalize()
print ('Hello,', str(nameofplayer))
class Player():
def __init__(self, banktotal):
self.banktotal = banktotal
# adds an amount to the bank
def addtobank(self, bankadd):
self.banktotal += bankadd
# removes an amount from the bank
def subfrombank(self, subbank):
self.banktotal -= subbank
def rolldice():
global playerhand
playerhand = 0
print('Your Current hand: ' + str(playerhand))
playerhand = 0
print ('...')
print ('Rolling the dice for you')
dice = list(range(1,7))
while playerhand <= 21:
rolled = random.choice(dice)
print('Your Current hand: ' + str(playerhand))
hitstick = str(input('Hit or Stick?').capitalize())
if hitstick == 'Hit':
print('You chose to hit!')
playerhand += rolled
elif hitstick == 'Stick':
print('Your exit hand: ' + str(playerhand))
break
elif hitstick != 'Hit' or 'Stick':
print('Enter a valid argument')
else:
print('Your Current hand: ' + str(playerhand))
print ('Busted, Host Wins!')
print('Reducing 100$ from your account')
playername.banktotal -= 100
print('Your bank balance: ' + str(playername.banktotal))
replay()
def hostchance():
hosthand = 0
print ('Current host hand: ' + str(hosthand))
dice = list(range(1, 7))
while hosthand <= playerhand:
rolled = random.choice(dice)
hosthand += rolled
print('Rolling the dice for the host')
print ('Current host hand: ' + str(hosthand))
if hosthand < playerhand:
pass
elif hosthand == playerhand:
print ('Its a draw!')
break
elif hosthand > playerhand and hosthand < 22:
print('Host Wins!')
print('Reducing 100$ from your account')
playername.banktotal -= 100
break
if hosthand < playerhand or hosthand > 21:
print (str(nameofplayer) + ' Wins!')
print('Adding 100$ to your account')
playername.banktotal += 100
playername = Player(1000)
def game():
print ('Your bank balance: ' + str(playername.banktotal))
rolldice()
something = input('Enter anything for the host to start his turn')
print (something)
print('Host Chance')
hostchance()
print ('Your bank balance: ' + str(playername.banktotal))
def replay():
print('Do you want to play again?')
replay = input('Input with yes or no: ').lower()
if replay == 'yes':
game()
elif replay == 'no':
pass
game()
replay()

Rather than doing pass after receiving a no answer, you should exit() or quit().

Related

Boolean does not control while loop for me

All of this code does not get affected by a SIGKILL command and my while loop continues no matter what condition
Code:
if Play == False:
signal.SIGKILL(0)
if gameplayint == "N":
print("What are you doing here then?")
Play == False
if gameplayint == "Y":
Play == True
time.sleep(0.5)
print("We will start now.")
#Start the game.
print("")
#Actual gameplay block of code
#game start
while Play == True:
pcNum = random.randint(1,19)
anotherNum = True
total = 0
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
again = input("Try again? <Y or N>")
if again == "Y":
Play = True
else:
Play = False
print("Goodbye now.")
Output:
What's your name? Y
Very well then Y, do you want to play 13? <Y or N> N
What are you doing here then?
Your number is 3.
You have 3 in total.
The issue here is that despite N being outputted on the gameplayint variable, the while loop still continues instead of stopping the output entirely.

fruit machine GSCE challenge

I'm sure you have all heard of the GCSE fruit machine challenge. Well I am having issues with that, you see, when the user spins 3 skulls it doesn't deduct all their credits and when they only spin 2 skulls it doesn't deduct 1 credit. If anyone can help please do.
credit = 1
import time
t = 1
while True:
import random
symbols = 'Star' , 'Skull'
spin = random.choices(symbols,k=1)
spin2 = random.choices(symbols,k=1)
spin3 = random.choices(symbols,k=1)
ask = input('do you want to spin? ')
if ask == 'yes':
credit = (credit - 0.2)
credit = (round(credit, 2))
print('You now have... ' +str(credit) + ' credit(s).')
time.sleep (t)
print('** NOW ROLLING **')
time.sleep (t)
print('You rolled... ' +str(spin) +str(spin2) +str(spin3))
time.sleep (t)
if (spin == spin2 == 'Skull' or spin == spin3 == 'Skull' or spin2 == spin3 == 'Skull'):
credit = (credit - 1)
credit = (round(credit, 2))
print('Uh Oh! you rolled 2 skulls.... you lost 1 credit sorry!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == 'Skull' and spin2 == 'Skull' and spin3 == 'Skull':
credit = (credit - credit)
print('You rolled 3 Skulls!! You lost all your credits!')
break
elif spin == spin2 and spin2 == spin3:
credit = (credit + 1)
print('You won 1 credit!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == spin2 or spin == spin3 or spin2 == spin3:
credit = (credit + 0.5)
credit = (round(credit, 2))
print('You won 0.5 credits!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
else:
print('Sorry you didnt win anything.')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif ask == 'no':
print('Your total winnings are.... ' +str(credit))
break
else:
print('please say yes or no..')
continue
The problem is you are comparing list to string where "Skull" is a string and the variable "spin" is a list of one element. To solve this you can turn "spin" to a string using spin = random.choice(symbols) which will make one choice as a string.
You seem new to python so I also rewrote your code. You are more than welcome to ask questions about it :)
import time
import random
t = 1
credit = 1.0
while True:
symbols = "Star", "Skull"
spins = random.choices(symbols, k=3)
ask = input("Do you want to spin? ")
if ask == "yes":
credit -= 0.2
print(f"You now have... {credit} credit(s).")
time.sleep(t)
print("** NOW ROLLING **")
time.sleep(t)
print("You rolled... " + " ".join(spins))
time.sleep(t)
if sum(spin == "Skull" for spin in spins) == 2:
credit -= 1
print("Uh Oh! you rolled 2 skulls.... you lost 1 credit, sorry!")
elif sum([spin == "Skull" for spin in spins]) == 3:
credit = 0
print("You rolled 3 Skulls!! You lost all your credits!")
elif all(spin == spins[0] for spin in spins):
credit += 1
print("You won 1 credit!")
elif len(set(spins)) != len(spins):
credit += 0.5
print("You won 0.5 credits!")
else:
print("Sorry you didn't win anything.")
credit = (round(credit, 2))
print(f"You now have a total balance of... {credit} credits!")
if credit >= 0.2:
continue
else:
print("Sorry! You don't have enough credits.")
break
elif ask == "no":
print(f"Your total winnings are.... {credit}")
break
else:
print("Please say yes or no..")
continue
Good Luck

Unreliable nested while loops?

Im having a logic confusion here and don't know whether a solution is possible with my setup.
I am trying to prompt the user for (in order)
user answer y/n (originally set to 'y')
a bet (based on their current money)
a guess on a number 1-6.
Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.
My code below works, if the user answers with a valid guess all the time:
def roll():
return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]
# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0
# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
break
But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?
I've tried
if (int(guess) < 1 or int(guess) > 6):
guess = input('What number are you betting on? (number 1-6)')
at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.
Is my setup all wrong or how can I fix this?
Updated attempt:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
if(userAnswer.strip().lower() != 'y'):
break
From a quick glance your problem seems to lie in the fact that when you enter an invalid guessing number, you never enter the third and final loop.
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
If you enter in a number that is < 1 or > 6 then you will never enter the while loop and directly jump to the break that is in the end of the second while loop which sends you back to the very first loop and asks you how much you want to bet again.
Try removing the break in the second while loop and see what happens, the logic is currently not what you are looking for.
Alright - this was the right way to do it:
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while userAnswer.strip().lower() == 'y':
while True:
bet = int(input('You have $' + str(money) + '. How much would you like to bet?'))
if bet <=0 or bet > money:
print('Invalid bet - bet must be greater than 0 and less than '+str(money))
continue
# Valid bet entered
break
while True:
guess = int(input('What number are you betting on? (number 1-6)'))
if guess < 1 or guess > 6:
print('Invalid guess - you must enter a value 1-6')
continue
# Valid guess entered
break
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
else:
print('You lost your bet :(')
money += int(computeBetResult(theRoll, bet, guess))
userAnswer = input('Would you like to play again (y/n)?')
Change the while condition in the loop that asks for a valued number and put it inside the actual loop, so that when it is an invalid number, it asks for another one.
Edited while condition because of #AMC 's comment
Edited to put the whole code that solves the problem:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while true:
if int(guess) < 1 or int(guess > 6):
guess = input("Please choose a valid number") #will keep asking for a valid number if it is wrong
continue
else:
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
if userAnswer=="n":
break

Enter blank value in try statements

I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
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!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.

Looping and ignoring flag - Python

I am working on learning python and decided to write a small battle engine to use a few of the different items I have learned to make something a bit more complicated. The problem I am having is that I set a selection that the user makes that should cause one of either two parts to load, but instead it skips to my loop instead of performing the selection. Here is what I have so far:
import time
import random
import sys
player_health = 100
enemy_health = random.randint(50, 110)
def monster_damage():
mon_dmg = random.randint(5,25)
enemy_health - mon_dmg
print ('You hit the beast for ' + str(mon_dmg) + ' damage! Which brings its health to ' + str(enemy_health))
player_dmg()
def player_dmg():
pla_dmg = random.randint(5,15)
player_health - pla_dmg
print ('The beast strikes out for ' + str(pla_dmg) + ' damage to you. This leaves you with ' + str(player_health))
def run_away():
run_chance = random.randint(1,10)
if run_chance > 5:
print ('You escape the beast!')
time.sleep(10)
sys.exit
else:
print ('You try to run and fail!')
player_dmg()
def player_turn():
print ('Your Turn:')
print ('Your Health: ' + str(player_health) + ' Monsters Health: ' + str(enemy_health))
print ('What is your next action?')
print ('Please Select 1 to attack or 2 to run.')
action = input()
if action == 1:
monster_damage()
elif action == 2:
run_away()
while player_health > 0 and enemy_health > 0:
player_turn()
if player_health <= 0:
print ('The beast has vanquished you!')
time.sleep(10)
sys.exit
elif enemy_health <= 0:
print ('You have vanquished the beast and saved our Chimichongas')
time.sleep(10)
sys.exit
The function input returns a str not an int
action = input()
So this comparison will always return False
if action == 1:
For example
>>> '1' == 1
False
You can convert their input to an int as follows
action = int(input())

Categories