I'm looking to create a simple craps game and I am having issues.
When this code is inputted:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
rounds = input("Play again? (Y/N): ")
while rounds != "n" and rounds == "y":
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
break
main()
this happens when I input "n".
Enter your bet: 5
Dice roll 1: 6
Dice roll 2: 6
Your roll: 12
Play again? (Y/N): n
and this happens when I input "y".
Enter your bet: 5
Dice roll 1: 2
Dice roll 2: 3
Your roll: 5
Play again? (Y/N): y
You push.
You have $10 remaining.
In both instances, it needs to tell the user whether or not they push, win, or lose before it asks if they want to play again. How can I accomplish this?
If I put "rounds" within the while loop, it tells me that rounds is referenced before it's assigned.
I think there's a lot here to neaten up, but why not start with:
rounds = 'y'
while .....
....
....
else:
....
rounds = input("Play again (y/n)")
This way you automatically fall into the while loop after the first roll and give the user results before asking if they want to play again. The next problem you have to deal with is that within the while loop, there is no provision for placing new bets or rolling the dice again.
The first problem is that all of the code that tells the user whether they push, win, or lose is inside the loop, and if the user enters "n", that code never runs. The real problem is that most of your code really should be inside the loop, including asking the user how much they want to bet and rolling the dice.
I would start by initializing the rounds variable to a default value of "y" so that the loop runs at least once, then don't ask the user if they want to play again until the end of the loop. Then move all of your other code inside the loop. (Except for the "How much do you have to gamble?" part. That should probably stay outside the loop.)
This is untested, but the order of things should be something like:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
rounds = "y"
while rounds != "n" and rounds == "y":
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
rounds = input("Play again? (Y/N): ")
main()
You should probably also think about ending the game if the player runs out of money.
Related
I'm a python beginner and i was making a simple number guessing game, but every time i accidently type in a letter or a symbol instead of a number, i get the ValueError. How do I pass this error throughout the entire program? i know the code is messy, and I'm sorry for that but I'm just trying to have some fun with it.
import random
tries = 15
money = 0
cheat = 0
run = True
random_number = random.randint(1, 20)
while run:
if cheat >= 1:
print(random_number)
cheat -= 1
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
guess = int(guess)
if guess == random_number:
money += 5
print("You got it right! You got it with " + str(tries) + " tries left", "your balance is", + money)
again = input("Play again? yes/no")
if again == "yes":
random_number = random.randint(1, 20)
else:
break
#store system
shop = input("Would you like to access the shop? yes/no")
if shop == "yes":
try_cost = 10
cheat_cost = 20
#if player has enough money
buy_try = input("Would you like to purchase more tries? price is 10 dollars for 5 tries. yes/no")
if buy_try == "yes" and money >= 10:
tries += 5
money -= 10
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
buy_cheat = input("Would you like to purchase a cheat? price is 20 dollars for 2 cheats")
if buy_cheat == "yes" and money >= 20:
cheat += 2
money -= 20
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
# if player doesn't have enough money
elif buy_try == "yes" and money != 10:
print("You don't have enough for that, you have", money, "dollars")
elif buy_cheat == "yes" and money != 20:
print("You don't have enough for that, you have", money, "dollars")
elif guess > random_number:
print("Try a little lower!")
tries -= 1
elif guess < random_number:
print("Try a little higher!")
tries -= 1
if tries == 0:
print("you ran out of tries!")
run = False
Pick a number from 1-20! You have 15 triess
Traceback (most recent call last):
File "C:\Users\bashr\PycharmProjects\pythonProject1\main.py", line 15, in
guess = int(guess)
ValueError: invalid literal for int() with base 10: 's'
In this situation, use a try and except clause.
Documentation: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
assuming you want to access that error inside this whole file then you can use global variable or you can use class concept
I think the fastest way to solve that is a while: while the input Is not a digit ask again the input.
So, in your case, every time you use the input function you should use something likes this:
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
while not guess.isdigit():
print("the input Is not a digit, please retry")
guess = input("Pick a number from 1-20! You have...")
Or you can use you can use try and except
I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.
import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
money = money + 250000
else:
print("you lose")
money = money - 250000
print ("your balance is",money)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
game()
if replay == "n":
sys.exit("goodbye")
This is the output:
do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
you need to call game() at the end of the code once more.
import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
fact=1
else:
print("you lose")
fact=-1
print ("your balance is",money+fact*step)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
print("welcome again")
game()
if replay == "n":
sys.exit("goodbye")
game()
Add this up in your game function:
global money, flip
I'll try to keep it short and sweet.
I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.
Essentially, here's what's supposed to happen:
Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.
What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:
venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py
Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.
The related code is below:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
print("You rolled a " + str(RollD20()) + "!")
PostGen()
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
def PostGen():
if RollD20() <= 5:
print("You start as a human.")
PostStartHum()
elif RollD20() >= 6:
print("You start as an elf.")
PostStartElf()
elif RollD20() >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
def RollD20():
n = random.randint(1, 20)
return n
def PostStartHum():
print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
print("However, even mighty decendants of gods have a weakness. Be careful."
Thanks for all your help.
Turn your PostGen function into the following:
def PostGen(rollValue):
if rollValue <= 5:
print("You start as a human.")
PostStartHum()
elif rollValue >= 6:
print("You start as an elf.")
PostStartElf()
elif rollValue >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
Change your NewGame function to the following:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
rollValue = RollD20()
print("You rolled a " + str(rollValue) + "!")
PostGen(rollValue)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
You are generating a new random number every time you call RollD20(). You need to store the value somewhere and reuse it for the game session.
Each time you call RollD20, you get a new random number. So if you want to use the same random number in multiple ifs, you need to tuck that value into another variable.
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
result = RollD20()
print("You rolled a " + str(result) + "!")
PostGen(result)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
And from there you change PostGen() to accept the result:
def PostGen(result):
if result <= 5:
print("You start as a human.")
PostStartHum()
elif result >= 6:
print("You start as an elf.")
PostStartElf()
elif result >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
I am trying to restart this program if what the user gets from picking the two numbers from the dice roll is already gone from the overall list. It will ask them to roll again and everything that just happened will go back like they never clicked 'e'.
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid ----- Please enter 'e' to roll the dice")
# Add in the invalid input error
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
while True:
sum1 = dice_choose + dice_choose1
if sum1 in lst_player:
break
else:
print("You have made an invalid choice")
sum1 = dice_choose + dice_choose1
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
If you want to repeat code until some conditions are met, you can use a while True loop or while <condition> loop, using continue (continue to the next iteration) to "reset" when some invalid situation is reached:
while True:
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid input")
continue # Go back to asking the player to roll
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
sum1 = dice_choose + dice_choose1
if sum1 not in lst_player:
print("You have made an invalid choice")
continue # Go back to asking the player to roll
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
break # Break out of the loop
I'm not entirely sure how this code is intended to work, but you may need to move blocks around and/or reset dice before continue.
#Setting up RNG
loop = "y"
while loop == "y" or loop == "yes":
from random import randint
dice = (randint(1,10))
dice2 = (randint(1,10))
roll = (dice + dice2)
win = 3
loss = 2
cash = 20
if roll == 3 or roll == 7 or roll == 11 or roll == 17:
cash += (win)
else:
cash -= (loss)
#Starting game
print("""Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3 but any other number
takes $2
You have a 20% of winning
""")
x = input("Press ENTER to start.")
#Results
if roll == 11 or roll == 8 or roll == 18:
print("You rolled an " + str(roll) + "!")
else:
print("You rolled a " + str(roll) + "!")
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower()
Had to change the indenting to show it as code
When it runs, I hit enter to start the game and it adds and subtracts correctly but when I select continue, it plays as if I never lost or gained any money. It is 1AM and idk if my brain died but I can't think of anything to fix it
You reinitialize the variable cash with 20 before every game. To fix the game, just move that code out of the loop.
The initialization of win and loss can also be moved out of the loop since they do not change.
Same for the from random import randint statement, it is considered a good practice to put all import statements at the top of the file.
from random import randint
#Setting up RNG
loop = "y"
win = 3
loss = 2
cash = 20
while loop == "y" or loop == "yes":
dice = (randint(1,10))
dice2 = (randint(1,10))
roll = (dice + dice2)
if roll == 3 or roll == 7 or roll == 11 or roll == 17:
cash += win
else:
cash -= loss
#Starting game
print("""Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3 but any other number
takes $2
You have a 20% of winning
""")
x = input("Press ENTER to start.")
#Results
if roll == 11 or roll == 8 or roll == 18:
print("You rolled an " + str(roll) + "!")
else:
print("You rolled a " + str(roll) + "!")
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower()
I would reorder your code to make the control-flow more clear.
For comparison "if a in several elemets" you should use set()s - they are very efficient when looking up if something is in them (and for other set-operations).
For printing look up the str.format() or python 3.6+ string interpolation: PEP-498
You only ever use the sum of 2 random numbers, you can get them in one go using random.choices(iterable, k=2)
from random import choices
cash = 20
winAmount = 3
lossAmount = 2
#Starting game
print("""Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3, else you loose $2
You have a 20% chance of winning
""")
x = input("Press ENTER to start.")
lucky_numbers = {3,7,11,17}
# needed for outputting text
pluralize = {8,11,18}
win = False
loop = "y"
while loop and loop[0]== "y":
sum_dice = sum(choices(range(1,11), k=2))
if sum_dice in lucky_numbers:
win = True
cash += winAmount
else:
win = False
cash -= lossAmount
print("You {}. You rolled a{} {}!".format(
"won" if win else "lost",
"n" if sum_dice in pluralize else "",
sum_dice))
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower().strip()
Output:
Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3, else you loose $2
You have a 20% of winning
Press ENTER to start.
You lost. You rolled a 6!
Cash - $18
Continue? (Y/N) y
You lost. You rolled a 16!
Cash - $16
Continue? (Y/N) y
You lost. You rolled a 16!
Cash - $14
Continue? (Y/N) y
You lost. You rolled a 15!
Cash - $12
Continue? (Y/N) y
You won. You rolled a 7!
Cash - $15
Continue? (Y/N) n
Beside print formatting the outputs use a ternary (do x if this else y) operator. More here: Does Python have a ternary conditional operator?