So I ran into trouble with this code again with output. Basically, there are some key features I need it to print, but whenever I manage to get it to print one thing it completely messes up the rest of the printing. So for example, I need it to print Roll # 1 (1 - 3) was (whatever number) not Roll (whatever number) if that makes sense. But I also need it to only max out to 3 rolls. This is where my second issue comes in; whenever I try to code it to subtract the bet from the bank when a user doesn't match any rolls, it counts my subtraction as a fourth roll and screws up the math. So instead of Roll #1 through #3 its now up to Roll #4
My third problem is, I need to the program to continue looping until the user enters 0 (zero) to end the script or the bank amount reaches 0 (zero).
You should redesign your program. First of all, you are generating new results for each condition check at
if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
Your code is not properly indented.
[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
And so on...
Have a function that simulates a single dice roll, like:
def roll():
return random.randint(1, 6)
And handle the rest in your main function like:
prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
A couple changes get the result you want
Pass the roll count to the rollDice function
Add an else to the bottom of the if block to check 0 bank
Here is the updated code:
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet # no match
if bank == 0:
print('You have no money left. Thanks for playing!')
exit()
Output
You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!
Related
How do I combine my guesses and credits in my python guessing game? for example, if it took me 6 guesses with the first attempt then when I press y to do the game again and it took me 10 guesses how can I get those two to combine for 16 total guesses, same thing with credits (sorry if its a bad explanation) Heres what I have so far:
import random
# this function is for the welcome part of my code or the part where I give instructions on how to play
def game_intro():
print(" ---- G U E S S I N G G A M E ----")
print("\n L E T S P L A Y ")
print("""\nThe adjective of this game is to solve guess a 3 digit combination,
and it is your job to guess numbers 100-999 to find that combination!!""")
print("Credits")
print("1-4 guesses: up to 60 credits")
print("5-10 guesses: 10 credits")
print("if guesses more than 10 no credits")
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
num_of_guess = 0
while not done:
try: # anything other than a number between 100, 999 gets an error
user_input = int(input("\nEnter a guess between 100-999: "))
num_of_guess += 1
if user_input == i:
print('you got it right in ', str(num_of_guess), 'tries')
print(creditScore())
new_game_plus()
elif user_input < i: # if player guess lower than I tell player
print("To low")
elif user_input > i: # if player guess higher than tell players
print("to high")
elif user_input not in range(100, 999):
print("Invalid. Enter a number between 100-999")
num_of_guess += 1
except ValueError:
print("Invalid. Enter a number between 100-999")
def new_game_plus():
global done, num_of_guess
new_game = input("Do you want to start a new game? press y for yes n for no: ")
if new_game == "y":
check_range_main()
else:
done = True
def statistics(new_game): # statistics for games after players finish
global total_games, num_of_guess
if new_game == "n":
print()
total_games += 1
num_of_guess += num_of_guess
print("P O S T G A M E R E P O R T")
print()
print(f"total {total_games} games played.")
print('total guesses', num_of_guess)
print("your average guess per game is", num_of_guess / total_games)
def creditScore():
global credit, done
credit = num_of_guess
if 1 <= num_of_guess <= 4:
print("game credits", 60 / credit)
elif 5 <= num_of_guess <= 10:
print("game credits", 10)
else:
print("no credits")
#print("total credits", )
# def functions matches() that computes and returns the number of matching digits in a guess, you may assume that the
# combination and the guess are unique three-digit numbers.
# def play_one_game():
# global done
# i = random.randint(100, 999)
# while not done:
# try:
# user_input = int(input("\nEnter a guess between 100-999: "))
# if user_input == i:
# print("Nice Job")
# done = True
#
# elif user_input > i:
# print("input to high")
#
# elif user_input < i:
# print("input to low")
#
# elif user_input not in range(100, 999):
# print("invalid input a number in range of 100,999")
#
# except ValueError:
# print("invalid. input a number between 100,999")
# this is where all the different functions go
def main():
game_intro()
check_range_main()
new_game_plus()
statistics("n")
creditScore()
# play_one_game()
if __name__ == '__main__':
main()
Put out the num_of_guess = 0 from inside the check_range_main()
...
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
num_of_guess = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
while not done:
The condition is that the program will end:
-if the balance is less than or equal to zero.
-if the balance is greather than or equal to 200.
But the problem is that it ends after I input 1 or 2 (1 for heads and 2 for tails) and you need to run it again and the balance is not saved.
Here is my code:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = int( random.choice([1,2]))
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return(1)
if Balance >=200:
print("Congrats!! You reached your Target $200.")
return(1)
balance = 100 #beginning amount
while True:
bal = Balance_Check(balance) #check the available balance
if bal==1:
break
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
Balance = Guess_Check(guess,balance)
You messed up a few of the things like which balance to take at the right time when to stop the loop etc.
Here's the code if you want to take the user input once and then check the guess:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
balance = Guess_Check(guess,balance)
But if you want to take user input on every chance use:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
guess = int(input("Guess heads by entering 1 or tails by entering 2 for this coin flip."))
balance = Guess_Check(guess,balance)
Sample output: (Not complete output as it was long)
Congrats you guessed right, You won $9.
Avalilable balanace is : 206
Congrats!! You reached your Target $200.
I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")
Python 3.5
I have a project for a class to create a Roulette wheel minigame and I'm having issues. I set the initial cash to $100 and let the user play roulette. After they've given their wager and it's time to tally up the cash for the next round, I'm having issues setting the new cash value. Basically, I need to add the winnings/losings to the value of cash so that it's accurately updated for the next round. I know that declaring cash as a global variable is wrong, but we haven't learned the proper way to do it and haven't had time to check it out for myself. Anyways, the issue is near the bottom. Thank you for any help! -
import math
import random
def main():
global cash
print('Welcome to Roulette! We\'ll start you with $100')
cash = 100 #set to 100 for intitial
menu()
def menu():
print('Place your bet! ',cash,'bucks!', '''
=======================================
1. Bet on Red (pays 1:1)
2. Bet on Black (pays 1:1)
3. First 12 (pays 2:1)
4. Middle 12 (pays 2:1)
5. Last 12 (pays 2:1)
6. Choose any number (pays 35:1)
7. Cash out
Please enter your choice: ''')
menuChoice = int(input())
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if cash > 0 and menuChoice != 7: #Determine if quit or broke
if menuChoice == 6:
number = int(input('Please choose a number from 0-36!')) #Get their specific number
while number < 0 or number > 36: #Validation
number = int(input('Please enter a number from 0-36'))
wager = int(input('How much would you like to bet? '))
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print('Press any key to spin the wheel! ')
input()
print(menuChoice, wager)
##
## ball = random.randint(0,36)
ball = 19 #set to 19 for testing. REMOVE AND RESET BALL!!!!!!!!!!!!!!!!!
if ball == 0:
color = ('green')
elif ball % 2 == 0:
color = ('black')
else:
color = ('red')
print('Your ball was',ball, 'and landed on the color',color)
#Determine if winner
if menuChoice == 1 and color == 'red':
winner = True
odds = 1
elif menuChoice == 2 and color == 'black':
winner = True
odds = 2
elif menuChoice == 3 and ball >= 1 and ball <= 12 :
winner = True
odds = 2
elif menuChoice == 4 and ball >= 13 and ball <= 24:
winner = True
odds = 2
elif menuChoice == 5 and ball >= 25 and ball <= 36:
winner = True
odds = 2
elif menuChoice == 6 and ball == number:
winner = True
odds = 35
else:
winner = False
odds = 0
#End determine if winner
if odds == 0:
pass
else:
amount = wager * odds #Get amount won/lost
print(amount)
if winner == True:
cash += amount #<~~~~~~~~~~~~~Problem Area
print('Congratulations! You won', wager,'dollars!')
print('Your total is now :',cash,'dollars.')
else:
cash -= wager
print('Sorry! You lost',wager,'dollars. Better luck next time!')
print('Your total is now :',cash,'dollars.')
input('Press a key to go back to the menu!')
print('====================================================================')
#New round
menu()
else:
print('Thank you for playing! ')
exit
main()
You could create your own python class, with the methods you already have. Than you can declare cash a class variable, with the parameter self. With self.cash you can than access the variable in every method. If that does not help please comment this answer with your issue.
I am trying to make a full-on guessing game with a shop that you can buy stuff with coins. but I had a function that was supposed to give the user a certain amount of coins depending on how many attempts it took them to guess the number. However, when I have a variable called 'coins' and when a player gets the number, I add coins to 'coins' it doesn't actually add coins. When I print 'coins' it still tells me 0. It's very confusing I know but I just want to fix this. I am using a mac with python 3, and am using two files, one for the main code, and the other for the functions. Do you see where I'm going wrong?
Main Code:
from guessing_functions import guess_game, guess_home
home = False
attempt = 0
coins = 0
print ("Atemps:Coins, 10:5, 7:10, 5:20, 3:40, 1:100 ")
guess_game(coins, attempt)
while not home:
guess_home(coins)
Functions:
import random
def guess_game(coins, attempt):
print ("This is a guessing game. ")
found = False
num = random.randint(1, 100)
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == num:
print ("You got it!")
found = True
elif userGuess > num:
print ("Guess Lower!")
else:
print ("Guess Higher")
attempt += 1
if attempt == 1 and found == True:
print ("You won 100 coins!")
coins += 100
elif attempt == 2 and found == True:
print ("You won 40 coins")
coins += 40
elif attempt == 3 and found == True:
print ("You won 40 coins")
elif attempt == 4 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 5 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 6 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 7 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 8 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 9 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 10 and found == True:
print ("You won 5 coins")
coins += 5
Your function uses coins in it's local scope. In order for the function to change the value of the outter scope (global) coins variable you need to explicity state that.
Add global coins inside your function before changing coins value.
coins = 0
def f():
global coins
coins = 5
f()
print coins
# 5
Or, an alternative way is to return coins value from the function, and call your function coins = guess_game(attempt)
Here is some useful resource for this subject
To get it to work, you need only add return coins to the end of the guess_game function and collect the returned value in your main code as coins = guess_game(coins, attempt). However, if you'd like, you can simplify your code a little bit like so:
import random
def guessing_game(coins):
print("This is a guessing game. ")
attempts = 0
number = random.randint(1, 100)
user_guess = -number
while user_guess != number:
user_guess = int(input("Your Guess: "))
if user_guess > number:
print("Guess Lower!")
elif user_guess < number:
print("Guess Higher")
else:
print("You got it!")
if attempts == 1:
winnings = 100
elif attempts in [2, 3]:
winnings = 40
elif attempts in [4, 5]:
winnings = 20
elif attempts in [6, 7]:
winnings = 10
elif attempts in [8, 9, 10]:
winnings = 5
else:
winnings = 0
print("You won {} coins!".format(winnings))
return coins + winnings
attempts += 1
With your main code as:
from guessing_functions import guessing_game
coins = 0
print("Starting balance: {} coins".format(coins))
print ("Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100")
coins = guessing_game(coins)
print("Current balance: {} coins".format(coins))
Where the output from a sample run is as follows:
Starting balance: 0 coins
Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100
This is a guessing game.
Your Guess: 50
Guess Lower!
Your Guess: 25
Guess Higher
Your Guess: 37
Guess Higher
Your Guess: 44
Guess Higher
Your Guess: 47
Guess Lower!
Your Guess: 46
You got it!
You won 20 coins!
Current balance: 20 coins
You should return the number of coins from the function and assign it to coins:
def guess_game(coins, attempt):
... # code to determine coin amount
return coins
coins = guess_game(coins, attempt)
Defining Functions