Python repeat random integer in while loop - python

I am trying to code player and mob attacks for a text based RPG game I am making, I have randomint set up for player and mob hitchance and crit chance but I can't figure out how to get a new integer for them every time I restart the loop, it uses the same integer it got the first time it entered the loop.
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
roll = roll_dice()
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
while True:
roll.mobcrit
roll.mobhitchance
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
if roll.mobcrit <= 5 and roll.mobhitchance >= 25:
print("\nOrc crit for",str(orcMob.atk * 2),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk * 2
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance >= 25:
print("\nOrc hit for",str(orcMob.atk),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk
print("Your HP",str(userPlayer.hp))
break
elif roll.mobcrit <= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
elif orcMob.hp >= 1:
continue

The problem is with your roll_dice class. You have the values defined when the class initializes, but then you never update them again. Therefore self.escape or self.spawn will always be the same value after the program starts. The easiest way to solve your problem without rewriting much would be to make another instance of roll_dice() every time you want to roll the dice. Something like:
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
# roll = roll_dice() # you don't need to make an instance here
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll = roll_dice() # make a new instance with each loop
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###

Use functions like
import random
for x in range(10):
print random.randint(1,101)
use a array around for a max 100 people and generate random digits to add in your code.
You can also use a array to create random umber structure and then use the numbers to be shuffled and added as you create them
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

Related

Python - How to return to previous function after calling another function?

Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()

Caught in a Python infinite loop

I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break

printing win / loss results in my guessing game

Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.

im unable to break the loop when the timer comes to an end

from time import *
import threading
def countdown():
global my_timer
my_timer = 5
for x in range(5):
my_timer = my_timer - 1
sleep(1)
print("Time is up! Sorry!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
again="yes"
while again=="yes":
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
player1=int(input("Player 1 please enter a number from 1 to 99: "))
guess= eval(input("Player 2 please enter your guess between 1 and 99 "))
count=1
lives=int(7)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 10:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 10:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
elif difficulty == "medium":
player1=int(input("Player 1 please enter a number from 1 to 199: "))
guess= eval(input("Player 2 please enter your guess between 1 and 199 "))
count=1
lives=int(10)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 20:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 20:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
elif difficulty == "hard":
player1=int(input("Player 1 please enter a number from 1 to 299: "))
guess= eval(input("Player 2 please enter your guess between 1 and 299 "))
count=1
lives=int(14)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 30:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 30:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
I'm unable to make break the loop when my timer comes to an end.
I tried to include if my_timer==0 break but it doesn't really work for some reason, and the program just continues on.
I'm really confused by this; can you help me to understand?
Unfortunately I can't comment as I don't have a reputation greater than 50 due to being relatively new here.
I don't have a solution as to why the timer is not stopping the program when it runs out but I think I know the reason.
I think it is due to the fact that upon first entering the while my_timer>0:, my_timer is greater than 0 which means it goes onto the next while loop which then runs your main body. This means the my_timer variable isn't continuously checked until the second while loop is re-checked. So basically you can't break from the first loop until you break out of the second loop after the timer has finished.
When I ran your code I also found a couple issues:
1)Even if I answer "no" to playing again, if the timer is still running then I am put into the game to select a difficulty again
2)If the timer ends and I answer "yes" to playing again I can continue playing as long as I like
3)After selecting a difficulty, I can still specify a number outside the range you want.
Although the following code does not solve the problem of the timer not stopping the game.
It will stop after the timer runs out even if I choose "yes" to playing again and it will break and stop the timer if i choose no to playing again. I also think the code is a little neater as it has less repitition.
import threading
import time
def countdown():
global my_timer
global stop_thread
while True:
time.sleep(1)
my_timer -= 1
if my_timer == 0:
print("Time is up! Sorry!")
break
elif stop_thread:
break
def process_guess(lives, guess, player1, boundary):
player2_lives = lives
guess_count = 1
while guess != player1:
guess_count += 1
if guess > player1 + boundary:
print("Too high!")
elif guess < player1 - boundary:
print("Too low!")
elif guess > player1:
print("Getting warm but still high!")
elif guess < player1:
print("Getting warm but still Low!")
player2_lives -= 1
if player2_lives <= 0:
print(" No more lives, GAME OVER")
return None
else:
print("lives remaining: ", player2_lives)
guess = eval(input("Try again "))
else:
if lives != 0:
print("You rock! You guessed the number in", guess_count, "tries!")
if lives >= 1:
again = str(input("Do you want to play again?, type yes or no "))
if again == "no":
print("Bye")
return None
elif again == "yes":
return True
def guessing_game():
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
while my_timer > 0:
global stop_thread
guess_result = None
while True:
difficulty = input("Difficulty? easy, medium or hard? ")
while difficulty not in ["easy", "medium", "hard"]:
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
boundary = 10
player1 = int(input("Player 1 please enter a number from 1 to 99: "))
guess = eval(input("Player 2 please enter your guess between 1 and 99 "))
lives = 7
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "medium":
boundary = 20
player1 = int(input("Player 1 please enter a number from 1 to 199: "))
guess = eval(input("Player 2 please enter your guess between 1 and 199 "))
lives = 10
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "hard":
boundary = 30
player1 = int(input("Player 1 please enter a number from 1 to 299: "))
guess = eval(input("Player 2 please enter your guess between 1 and 299 "))
lives = 14
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
break
if guess_result:
continue
else:
stop_thread = True
break
if __name__ == "__main__":
my_timer = 5
stop_thread = False
guessing_game()
If you wanted to you could even reduce the first two while loops to one by using:
def guessing_game():
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
global stop_thread
while True and my_timer > 0:
guess_result = None
difficulty = input("Difficulty? easy, medium or hard? ")
while difficulty not in ["easy", "medium", "hard"]:
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
boundary = 10
player1 = int(input("Player 1 please enter a number from 1 to 99: "))
guess = eval(input("Player 2 please enter your guess between 1 and 99 "))
lives = 7
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "medium":
boundary = 20
player1 = int(input("Player 1 please enter a number from 1 to 199: "))
guess = eval(input("Player 2 please enter your guess between 1 and 199 "))
lives = 10
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "hard":
boundary = 30
player1 = int(input("Player 1 please enter a number from 1 to 299: "))
guess = eval(input("Player 2 please enter your guess between 1 and 299 "))
lives = 14
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
if guess_result:
continue
else:
break
stop_thread = True
To fix the problem of people being able to enter numbers outside the ones you specify you can use a while loop similar to how I have for specifying the difficulty. Alternatively you can use assertions but that's more for raising errors.
Hope that helps, sorry I couldn't make the timer stop the program.

Program not performing the elif statement when balance equals bet

import random
print("Welcome to the Dice Game!")
Balance = int(input("How much money would you like to play with?:"))
Dice_again = "yes"
while Dice_again.casefold() == "y" or Dice_again.casefold() == "yes":
Bet = int(input("How much would you like to bet?:"))
if Bet > Balance:
print("Sorry, you dont not have enough funds to bet this much.")
print(f"You have ${Balance}.")
continue
elif Balance == 0:
print("Sorry, you have $0 and cannot play the game anymore.")
break
Betnumber = int(input("What number would you like to bet on?:"))
if Betnumber > 12:
print("You have entered an invalid input.")
continue
Dice1 = random.randint(1,6)
Dice2 = random.randint(1,6)
Balance -= Bet
Numberrolled = (Dice1 + Dice2)
print("Now rolling....")
while Balance >= Bet:
if (Betnumber == 2) and (Numberrolled == 2):
Winning1 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning1}!")
Balance += Winning1
print(f"You now have ${Balance}.")
break
elif (Betnumber == 3) and (Numberrolled == 3):
Winning2 = Bet * 18
print(f"Congratulations! You rolled a 3 and won ${Winning2}!")
Balance += Winning2
print(f"You now have ${Balance}.")
break
elif (Betnumber == 4) and (Numberrolled == 4):
Winning3 = Bet * 12
print(f"Congratulations! You rolled a 4 and won ${Winning3}!")
Balance += Winning3
print(f"You now have ${Balance}.")
break
elif (Betnumber == 5) and (Numberrolled == 5):
Winning4 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning4}!")
Balance += Winning4
print(f"You now have ${Balance}.")
break
elif (Betnumber == 6) and (Numberrolled == 6):
Winning5 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning5}!")
Balance += Winning5
print(f"You now have ${Balance}.")
break
elif (Betnumber == 7) and (Numberrolled == 7):
Winning6 = Bet * 6
print(f"Congratulations! You rolled a 2 and won ${Winning6}!")
Balance += Winning6
print(f"You now have ${Balance}.")
break
elif (Betnumber == 8) and (Numberrolled == 8):
Winning7 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning7}!")
Balance += Winning7
print(f"You now have ${Balance}.")
break
elif (Betnumber == 9) and (Numberrolled == 9):
Winning8 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning8}!")
Balance += Winning8
print(f"You now have ${Balance}.")
break
elif (Betnumber == 10) and (Numberrolled == 10):
Winning9 = Bet * 12
print(f"Congratulations! You rolled a 2 and won ${Winning9}!")
Balance += Winning9
print(f"You now have ${Balance}.")
break
elif (Betnumber == 11) and (Numberrolled == 11):
Winning10 = Bet * 18
print(f"Congratulations! You rolled a 2 and won ${Winning10}!")
Balance += Winning10
print(f"You now have ${Balance}.")
break
elif (Betnumber == 12) and (Numberrolled == 12):
Winning11 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning11}!")
Balance += Winning11
print(f"You now have ${Balance}.")
break
else:
print(f"Sorry, but you rolled a {Numberrolled}.")
print(f"You now have ${Balance}.")
break
Dice_again = input("Would you like to play again (N/Y)?")
if Dice_again.casefold() == "yes" or Dice_again.casefold() == "y":
continue
elif Dice_again.casefold() == "no" or Dice_again.casefold() == "n":
print(f"You have stopped the game with ${Balance} in your hand.")
break
else:
print("You have entered an invalid input.")
break
Whenever I run the program and the bet value equals the balance, it doesn't display the else statement I have it set to display but instead, it goes down the program and outputs the other information that is supposed to be outputted later on.
Here's an example of what happens when the bet doesn't equal the balance and when they equal each other:
Welcome to the Dice Game!
How much money would you like to play with?:100
How much would you like to bet?:50
What number would you like to bet on?:12
Now rolling....
Sorry, but you rolled a 7.
You now have $50.
Would you like to play again (N/Y)?yes
How much would you like to bet?:50
What number would you like to bet on?:12
Now rolling....
Would you like to play again (N/Y)?
Like people said in comments. The issue you have is this
Balance -= Bet
...
while Balance >= Bet:
# do rest
So when you have Bet equal to Balance then it subtracts it and the condition is no longer valid. What you want is to move subtraction inside of while loop
...
while Balance >= Bet:
Balance -= Bet
# do rest
Another issue I notices is that you have two whiles loops, and second loop will always runs once. So there is no reason to even have it, it would make sense to replace it with if statement and remove break inside of if statements that are inside of this while loop.
Edited:
Answer to Author's question in the comment. You replace make second while an if:
if Balance >= Bet:
Balance -= Bet
if (Betnumber == 2) and (Numberrolled == 2):
Winning1 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning1}!")
Balance += Winning1
print(f"You now have ${Balance}.")
elif (Betnumber == 3) and (Numberrolled == 3):
Winning2 = Bet * 18
print(f"Congratulations! You rolled a 3 and won ${Winning2}!")
Balance += Winning2
print(f"You now have ${Balance}.")
elif (Betnumber == 4) and (Numberrolled == 4):
Winning3 = Bet * 12
print(f"Congratulations! You rolled a 4 and won ${Winning3}!")
Balance += Winning3
print(f"You now have ${Balance}.")
elif (Betnumber == 5) and (Numberrolled == 5):
Winning4 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning4}!")
Balance += Winning4
print(f"You now have ${Balance}.")
elif (Betnumber == 6) and (Numberrolled == 6):
Winning5 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning5}!")
Balance += Winning5
print(f"You now have ${Balance}.")
elif (Betnumber == 7) and (Numberrolled == 7):
Winning6 = Bet * 6
print(f"Congratulations! You rolled a 2 and won ${Winning6}!")
Balance += Winning6
print(f"You now have ${Balance}.")
break
elif (Betnumber == 8) and (Numberrolled == 8):
Winning7 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning7}!")
Balance += Winning7
print(f"You now have ${Balance}.")
elif (Betnumber == 9) and (Numberrolled == 9):
Winning8 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning8}!")
Balance += Winning8
print(f"You now have ${Balance}.")
break
elif (Betnumber == 10) and (Numberrolled == 10):
Winning9 = Bet * 12
print(f"Congratulations! You rolled a 2 and won ${Winning9}!")
Balance += Winning9
print(f"You now have ${Balance}.")
elif (Betnumber == 11) and (Numberrolled == 11):
Winning10 = Bet * 18
print(f"Congratulations! You rolled a 2 and won ${Winning10}!")
Balance += Winning10
print(f"You now have ${Balance}.")
break
elif (Betnumber == 12) and (Numberrolled == 12):
Winning11 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning11}!")
Balance += Winning11
print(f"You now have ${Balance}.")
else:
print(f"Sorry, but you rolled a {Numberrolled}.")
print(f"You now have ${Balance}.")

Categories

Resources