Horse Racing Simulation Loop - python

So I have this program that basically runs a horse betting simulation. When the user chooses the horse from a list of names I have created, my program returns a % that predicts the horse's chances of winning the race (I am still working on this so just don't mind it). However, the program asks the user if they want to change horses. If they do, they get to choose their horse again, if not, the program continues to the race. I want to make my program so that it only allows the user to change horses once to make it a gamble. Is there a way I can do that? If there are any other changes that should be made let me know! (Created in Python).
code:
import random
import time
# percentage for the chosen horse to win the race
def Percent():
min = 1
max = 100
win = random.randint(min, max)
print(win)
# asks user if they want to change their chosen horse
def Horserestart():
new_horse = input("Do you wan to change you horse? Type Y or N. ")
if new_horse == "Y":
Horse()
elif new_horse == "N":
New()
# user chooses a horse
def Horse():
print("Horses to bet on: Tyrone, Jamal, Jaquavious, Quandale, Quantavious, and Charlie.")
horse_pick = input("What horse do you want to choose? ")
if horse_pick == "Tyrone":
option = print("You chose Tyrone, your chances of winning are: ")
Percent()
Horserestart()
elif horse_pick == "Jamal":
option = print("You chose Jamal, your chances of winning are: ")
Percent()
Horserestart()
elif horse_pick == "Jaquavious":
option = print("You chose Jaquavious, your chances of winning are: ")
Percent()
Horserestart()
elif horse_pick == "Quandale":
option = print("You chose Quandale, your chances of winning are: ")
Percent()
Horserestart()
elif horse_pick == "Quantavious":
option = print("You chose Quantavious, your chances of winning are: ")
Percent()
Horserestart()
elif horse_pick == "Charlie":
option = print("You chose Charlie, your chances of winning are: ")
Percent()
Horserestart()
# user inputs their total money and bet amount
def New():
while True:
total_money = int(input("What is the total amount of money you have? "))
goal = total_money * 2
if total_money < 10:
print("Sorry but that is too low, please input a higher amount.")
Horserestart()
elif total_money > 10:
print("Your goal is $",goal,"to reach.")
bet_amount = int(input("What is the amount you want to bet on? "))
bet_total = total_money - bet_amount
print("You will bet $",bet_amount,". You now have $",bet_total," left to bet with. ")
print("The race will start in:")
Race()
# race countdown
def Race():
time_sec = 10
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("..........THE RACE HAS STARTED..........")
Mech_race()
# functino of the race (not completed)
def Mech_race():
horse1 = "Tyrone"
horse2 = "Jamal"
horse3 = "Jaquavious"
horse4 = "Quandale"
horse5 = "Quantavious"
horse6 = "Charlie"
horses = [horse1, horse2, horse3, horse4, horse5, horse6]
random_horse = random.choice(horses)
random_horse1 = random.choice(horses)
random_horse2 = random.choice(horses)
random_horse3 = random.choice(horses)
random_horse4 = random.choice(horses)
random_horse5 = random.choice(horses)
random_horse6 = random.choice(horses)
random_horse7 = random.choice(horses)
random_horse8 = random.choice(horses)
random_horse9 = random.choice(horses)
if random_horse is horse1:
print(horse1,"has taken the lead!")
else:
print(random_horse,"has taken the lead!")
for positions in range(10):
overtakes = "overtakes"
trips = "trips"
falls_behind = "falls behind"
gaining = " is gaining on"
takes = "takes"
positions = [overtakes, trips, falls_behind, gaining, takes]
place = random.choice(positions)
if place is overtakes:
print(random_horse,"overtakes",random_horse1)
elif place is trips:
print(random_horse2,"trips",random_horse3)
elif place is falls_behind:
print(random_horse4,"falls behind",random_horse5)
elif place is gaining:
print(random_horse6,"gains on",random_horse7)
elif place is takes:
print(random_horse8,"takes",random_horse9,"position")
# introduction to the program/race
def Main():
print("Hello and welcome to the Sussy Baka horse race! ")
user_name = input("What is your name? ")
print("Hello",user_name,"this is when you choose your horse and your bet. ")
Horse()
Main()

You could paste the code for the Horserestart function anywhere Horserestart() is in the code.
def Horse():
print("Horses to bet on: Tyrone, Jamal, Jaquavious, Quandale, Quantavious, and Charlie.")
horse_pick = input("What horse do you want to choose? ")
if horse_pick == "Tyrone":
option = print("You chose Tyrone, your chances of winning are: ")
Percent()
new_horse = input("Do you wan to change you horse? Type Y or N. ")
if new_horse == "Y":
Horse()
elif new_horse == "N":
New()
You could also add a counter.
horse_restart = 0
def Horserestart():
new_horse = input("Do you wan to change you horse? Type Y or N. ")
if new_horse == "Y":
horse_restart += 1
Horse()
elif new_horse == "N":
New()
def Horse():
print("Horses to bet on: Tyrone, Jamal, Jaquavious, Quandale, Quantavious, and Charlie.")
horse_pick = input("What horse do you want to choose? ")
if horse_pick == "Tyrone":
option = print("You chose Tyrone, your chances of winning are: ")
Percent()
if(horse_restart < 1):
Horserestart()
OR
horse_restart = False
def Horserestart():
new_horse = input("Do you wan to change you horse? Type Y or N. ")
if new_horse == "Y":
horse_restart = True
Horse()
elif new_horse == "N":
New()
def Horse():
print("Horses to bet on: Tyrone, Jamal, Jaquavious, Quandale, Quantavious, and Charlie.")
horse_pick = input("What horse do you want to choose? ")
if horse_pick == "Tyrone":
option = print("You chose Tyrone, your chances of winning are: ")
Percent()
if(horse_restart == False):
Horserestart()

Related

Turn/chance feature in following code is not working

I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.

simple python text adventure game errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.

I am having trouble with my for loops working

My For loops don't seem to be "activating" or working. I am writing a program about the Oregon trail and I am working on the "shop" part. Here is what its been doing,
First it was asking the same question "How much food would you like to buy" until I pressed E to break out of it. Now its not doing the math or activating the for loop. Here is the code i'm working with:
import random
global all
global PlayerPerk
#Organ Trail Start--
print("You may:")
print("1. Travel the road")
print("2. Learn More about the road")
choiceStart = input("What is your choice? ")
def Shop(PlayerPerk, money):
global all
#intro
print("Before You set off on your Journey, you will need some supplies to survive the dangerous trail. You will need Food, Ammo, Spare Parts, Clothing, and Oxen")
#money define
if PlayerPerk == "1":
print("You are A cop. You have $400 to spend.")
money = 400
elif PlayerPerk == "2":
print("You are a Clerk. You have $700 to spend.")
money = 700
elif PlayerPerk == "3":
print("You are a Banker. You have $1600 to spend.")
money =1600
print("Welcome to My shop! First thing, how much Food would you like to buy?")
#Food -------------------------------------------------------------------------------
FoodToBuy = input("How Much food would you like (each cost $2):")
MoneySubtract = FoodToBuy*2
for i in range(1,1000):
if FoodToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent: ",MoneySubtract, "You now have: ",money)
Food = FoodToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif FoodToBuy == "e":
break
#Ammo --------------------------------------------------------------------------------
print("Now lets buy some Ammo!")
AmmoToBuy = input("How Much Rifle Ammo would you like to buy (each box cost $5):")
MoneySubtract = AmmoToBuy*5
for i in range(1,1000):
if AmmoToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:",MoneySubtract, "You now have: ",money)
Ammo = AmmoToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
#Spare Parts---------------------------------------------------------------------------
print("Now lets buy some Spare Parts!")
SparePartsToBuy = input("How much Spare Parts would you like to buy (each costs $20 [max of 9]):")
MoneySubtract = SparePartsToBuy*20
for i in range(1,1000):
if SparePartsToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = SparePartsToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#chlothing-----------------------------------------------------------------------------
print("Now, you need to buy some chlothes!")
ClothesToBuy = input("How many Clothes would you like to buy (each pair costs $5):")
MoneySubtract = ClothesToBuy*5
for i in range(1,1000):
if ClothesToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = ClothesToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#oxen-------------------------------------------------------------------------------------
print("Finally, you need to buy some Ox!")
OxenToBuy = input("How many Oxen would you like to buy (each costs $30):")
MoneySubtract = OxenToBuy*30
for i in range(1,1000):
if OxenToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = OxenToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
if AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#----------------------------------------------------------------------------------------------
def MonthStart(PlayerPerk):
global all
print("It is 1848. Your jumping off place for oregon is Independence, Missouri. You must decide which month to leave Indepence.")
print("1. March")
print("2. April")
print("3. May")
print("4. June")
print("5. July")
print("6. ask for advice")
StartingMonth = input("What is your choice? ")
if StartingMonth == ("6"):
global all
print("You attend a public meeting held for 'folks with the California - Oregon fever.' You're told:")
print("If you leave too early, there won't be any grass for your oxen to eat.")
print("if you leave to late, you may not get to Oregon before winter comes.")
print("If you leave at just the write time, there will be green grass and the weather will still be cool.")
exMonthChoice = input("Would you like to stop viewing?(y/n) ")
if exMonthChoice ==("Y" or "y"):
MonthStart(PlayerPerk)
elif exMonthChoice == ("N"or"n"):
print("Still viewing")
else:
print("Unknown usage.")
elif StartingMonth == ("1"):
Month = "March"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("2"):
Month = "April"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("3"):
Month = "May"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("4"):
Month = "June"
print("You chose: ", Month)
Shop(PlayerPerk,0)
elif StartingMonth == ("5"):
Month = "July"
print("You chose: ", Month)
Shop(PlayerPerk,0)
global all
############################
#NAMING
def NAMING(PlayerPerk):
global all
print("Now lets name your person")
Name1 = input("What is the name of the Wagon leader ")
Name2 = input("What is the name of the 2nd person in the family? ")
Name3 = input("What is the name of the 3rd person in the family? ")
Name4 = input("What is the name of the 4th person in the family? ")
Name5 = input("What is the name of the 5th person in the family? ")
NameVerification = input("Are these names correct?")
if NameVerification == ("Y" or "y"):
MonthStart(PlayerPerk)
elif NameVerification ==("N" or "n"):
NAMING(PlayerPerk)
#Start OCCUPATION
def Occupation():
global all
############################################################
print("Many people find themselves on the road. You may : ")
print("1. Be a cop from Kentucky.")
print("2. Be a clerk from Jersey City.")
print("3. Be a Banker from Boston.")
print("4. Find out the differences between these choices.")
############################################################
jobChoice = input("What is your choice? ")
if jobChoice == ("4"):
print("Traveling to Oregon isn't easy! But if you are a banker, you'll have more money for supplies and services than a cop or a clerk.")
print(" But, a cop has a higher chance of haveing a successful hunt!")
print("And a Clerk has a higher survival rate!")
exChoice1 = input("Would you like to stop viewing your options?(y/n) ")
if exChoice1 == ("y" or "Y"):
Occupation()
###############################
elif jobChoice ==("1"):
print("You chose to be a cop from Kentucky!")
PlayerPerk = ("1")
NAMING(PlayerPerk)
elif jobChoice == ("2"):
print("You chose to be a clerk from Jersey City!")
PlayerPerk = ("2")
NAMING(PlayerPerk)
elif jobChoice == ("3"):
print("You chose to be a Banker from Boston!")
PlayerPerk = ("3")
NAMING(PlayerPerk)
#Call choices
if choiceStart == ("1"):
Occupation()
And here is the specific code I'm having troubles with:
def Shop(PlayerPerk, money):
global all
#intro
print("Before You set off on your Journey, you will need some supplies to survive the dangerous trail. You will need Food, Ammo, Spare Parts, Clothing, and Oxen")
#money define
if PlayerPerk == "1":
print("You are A cop. You have $400 to spend.")
money = 400
elif PlayerPerk == "2":
print("You are a Clerk. You have $700 to spend.")
money = 700
elif PlayerPerk == "3":
print("You are a Banker. You have $1600 to spend.")
money =1600
print("Welcome to My shop! First thing, how much Food would you like to buy?")
#Food -------------------------------------------------------------------------------
FoodToBuy = input("How Much food would you like (each cost $2):")
MoneySubtract = FoodToBuy*2
for i in range(1,1000):
if FoodToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent: ",MoneySubtract, "You now have: ",money)
Food = FoodToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif FoodToBuy == "e":
break
#Ammo --------------------------------------------------------------------------------
print("Now lets buy some Ammo!")
AmmoToBuy = input("How Much Rifle Ammo would you like to buy (each box cost $5):")
MoneySubtract = AmmoToBuy*5
for i in range(1,1000):
if AmmoToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:",MoneySubtract, "You now have: ",money)
Ammo = AmmoToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
#Spare Parts---------------------------------------------------------------------------
print("Now lets buy some Spare Parts!")
SparePartsToBuy = input("How much Spare Parts would you like to buy (each costs $20 [max of 9]):")
MoneySubtract = SparePartsToBuy*20
for i in range(1,1000):
if SparePartsToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = SparePartsToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#chlothing-----------------------------------------------------------------------------
print("Now, you need to buy some chlothes!")
ClothesToBuy = input("How many Clothes would you like to buy (each pair costs $5):")
MoneySubtract = ClothesToBuy*5
for i in range(1,1000):
if ClothesToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = ClothesToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#oxen-------------------------------------------------------------------------------------
print("Finally, you need to buy some Ox!")
OxenToBuy = input("How many Oxen would you like to buy (each costs $30):")
MoneySubtract = OxenToBuy*30
for i in range(1,1000):
if OxenToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = OxenToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
if AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
The only problem i'm having is making the for loops work. I plan on using all the variables as the code develops. If you know whats wrong or have any information on anything let me know! Thank you in advance!

how to use an if else statement in another while loop

I am new to coding. I want to try writing a simple rock paper scissors game. But I can't figure out how to end the game.
In the end of this program if the user input is wrong I want to go to the end variable again. I tried with the commented lines but its not working.
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
while True:
print(player1 + " What do you choose ? rock / paper / scissors : ")
a = input()
print(player2 + " What do you choose ? rock / paper / scissors : ")
b = input()
if a == "rock" and b == "scissors" :
print(player1, "won !!!")
elif a == "scissors" and b == "rock":
print(player2, "won !!!")
elif a == "paper" and b == "rock":
print(player1, "won !!!")
elif a == "rock" and b == "paper":
print(player2, "won !!!")
elif a == "scissors" and b == "paper":
print(player1, "won !!!")
elif a == "paper" and b == "scissors":
print(player2, "won !!!")
elif a == b:
print("Its a tie :-(")
elif a or b != "rock" or "paper" or "scissors":
print("Wrong input, Try again")
end = input("Do you want to play again ? yes/no ") == "yes"
if input == "yes":
continue
else:
print('''
GAME OVER''')
break
# elif input != "yes" or "no":
# print("Wrong input, Try again. yes or no ?")
I expect it to end game if the input is "no" and restart the game if input is "yes" if the input is not correct I want the prompt to appear again.
Your code has a few issues which need some addressing, and a few places where it can be streamlined. I have made a few changes to your program as well as added a few comments explaining the changes.
player1 = input("What is player 1's name ? ").title() #This uses chaining to streamline code
player2 = input("What is player 2's name ? ").title() #Same as above
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ") #no need to use a separate print statement
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
valid_entries = ["rock", "paper", "scissors"] #To check for valid inputs
if (a not in valid_entries) or (b not in valid_entries):
print("Wrong input, try again")
continue
a_number = valid_entries.index(a) #Converting it to numbers for easier comparison
b_number = valid_entries.index(b)
if(a_number == b_number):
print("Its a tie :-(")
else:
a_wins = ((a_number > b_number or (b_number == 2 and a_number == 0)) and not (a_number == 2 and b_number == 0)) #uses some number comparisons to see who wins instead of multiple if/elif checks
if(a_wins):
print(player1, "won !!!")
else:
print(player2, "won !!!")
end = input("Do you want to play again ? yes/no ")
while (end !="yes") and (end != "no"):
print("invalid input, try again")
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print("GAME OVER")
break
These changes also make the check by using another while loop to see if the input to restart the game was valid or not
*Note that I have not tested these changes and some edits may need to be be made
Just check the value of end
if end is True:
continue
else:
break
Since, you have set the value of end as a boolean by comparing the input() to "yes", it will say whether the user wants to end the game?
Also, you are not initializing the input variable, and the last elif condition will always be true as mentioned in the comment.
Well you can simplify your code using a list and then simplify your if tests. You can check the order of the options and based on it make a decision. You can also make the tests standard to minimize the number of if statements. This my suggestion to improve your code. I hope it helps:
# get playe names
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
# init vars
options = ["rock", "paper", "scissors"]
players = [player1, player2]
# start game
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check if inputs are correct
while (a not in options or b not in options):
print("Wrong input, Try again")
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check who won
if abs(options.index(a) - options.index(b)) == 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif abs(options.index(b) - options.index(a)) > 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif a == b:
print("Its a tie :-(")
# continue or drop game
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print('''
GAME OVER''')
break

Python text RPG error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm making a textual RPG, and I'm running into a problem. So in the code below, mobHP is a global variable, which is equal to 20000. This is only a part of the code. So what's happening is that once the attack takes place, the new HP of the monster is shown, but then by the second attack, the HP again becomes 20000 and then the damage is subtracted, and again another value is shown, it isin't subtracting from the new value itself. battlem() is the battle menu from where you can attack, use potions and run. win() is a def function to what to show when the user wins.
For example if a player hits the monster by 1000, then the currentHP will show as 19000, but then when I attack again, say hit by 1400, instead of 19000-1400, it subtracts from the original value, and becomes 18600.
Help would really be appreciated
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
However, this doesn't work as the output is
You swing your sword at the enemy!
Inflicted damage: 95 enemy HP: -95
This was a solution that was given, but then removed, and when I further asked for a solution nobody replied again.
FULL CODE:
import random
import time
global playerHP
global inventory
global mobHP
global mobSpeed
global mob
global boss
global level
global strength
global speed
global potions
global exp
global mithril
playerHP= 28000
level = 74
strength = 80
speed = 120
potions = 3
exp = 0
mithril = 10000
mobHP = 20000
mobstrength = 120
mobSpeed = 180
inventory = []
def prompt():
command = input("What action will you perfrom?")
return command
def death():
if playerHP== 0:
print("Your HP has been depleted completely")
input()
print("You are now dead")
input()
print("You will be respawned at the Misgauka")
input()
townone()
def townoned():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
def Grasslands():
print(" You have already cleared the Grasslands")
input()
print("You may go there to gain more experience")
input()
print("Y/N")
input()
command = prompt()
if command == "Y" or "y":
print("You proceed to the grasslands")
input()
elif command == "N" or "n":
townoned()
else:
print("You seem to be pressing the wrong command")
Grasslands()
def win():
print("You have managed to slain the enemy")
input()
print("You now must dwell further within the greenlands")
input()
def battles():
print("A wild boar appears in front of you")
input()
print("What do you choose to do?")
input()
print("Fight or Run?")
input()
command = prompt()
if command == "Fight" or "fight":
print("Good work senpai")
input()
battlem()
elif command == "Run" or "run":
print("You turn to run")
time.sleep(1)
print("The pathway behind you is now blocked")
input()
print("Thus, you must fight")
battlem()
else:
battles()
def boss_battle():
print("Let's fight")
input()
command = prompt()
if command == "Fight" or "fight":
print("You unsheath your sword")
input()
boss_battle_m()
else:
print("You can't run away from this")
input()
boss_battle_m()
def boss_battle_m():
print("""
1. Attack
2. Potions
""")
command = prompt()
if command == "1":
boss_battle_s()
if command == "2":
if potions > 0:
print("You take a potion bottle")
input()
print("..........")
input()
pHP = playerHP +200
print("Your HP has been refilled to",pHP)
pHP = playerHP
else:
print("You have no potions left!")
input()
boss_battle_s()
def boss_battle_s():
bossdamage = random.randint(80, 220)
bossHP = 4000
bossHP = bossHP - bossdamage
print("Boss HP is now:", bossHP)
input()
if bossHP <= 0:
win()
elif playerHP <= 0:
death()
else:
boss_battle_m()
def battlem():
print("""
1. Attack 3. Run
2. Use potion
""")
command = prompt()
if command == "1":
Attack()
elif command == "2":
Potiondesu()
elif command == "3":
Run()
else:
battlem()
#CURRENT DAMAGE BY THE CURRENT HEALTH
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
def wepmenu():
print("""
1. Glorion Blades - 200 Mithril
2. Light Sword - 120 Mithril
3. Rapier - 200 Mithril
4. Dagger - 100 Mithril
Supplies Catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The Glorion Blades cost 200 mithril")
input()
if mithril>=200:
print("You buy the blades")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "2":
print("The light sword costs 120 mithril")
input()
if mithril>=150:
print("You buy the sword")
input()
wepmenu()
elif mithril<150:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "3":
print("The Rapier costs 200 mithril")
input()
if mithril>=200:
print("You buy the Rapier")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "4":
print("The Dagger costs 100 mithril")
input()
if mithril>=100:
print("You buy the blades")
input()
wepmenu()
elif mithril<100:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
print("Gotta implement weapon stats")
if command == "Supplies" or "supplies":
supplymenu()
elif command == "Exit":
townone()
def supplymenu():
print("""
1. HP potion - 20 Mithril
2. Large HP Potion - 40 Mithril
Weapons catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The HP Potion costs 20 mithril")
input()
if mithril>=20:
print("You have brought the potion")
input()
supplymenu()
elif mithril<20:
print("You cannot afford this potion")
input()
print("Choose another supply")
input()
supplymenu()
elif command == "2":
print("The Large HP potion costs 40 mithril")
input()
if mithril>=40:
print("You have brought the large potion")
input()
supplymenu()
elif mithril<40:
print("You cannot afford this potion")
input()
print("Choose another supply")
supplymenu()
elif command == "Weapons":
wepmenu()
elif command == "Exit":
townone()
def rest_inn():
print("It will cost 20 mithril to rest at this inn for tonight")
input()
if mithril>=20:
print("You check in")
elif mithril<20:
print("You can't afford to rest here")
input()
print("Kill some monsters for some mithril")
input()
print("You exit the inn")
input()
townone()
print("Your HP has been reset to",HP,"HP")
input()
print("Please press enter to exit the inn")
input()
townone()
def townone():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
if command == "Grasslands":
print("All of us have to go into the different pathways I guess")
input()
print("Three paths to each")
input()
print("Alright then, I'll take north, east and then the north pathway")
input()
print("Let's meet back here and gather intel")
input()
print("You make your way to the Grasslands")
input()
print("The pathway goes NORTH")
battles()
print("You will now proceed to the next part of the grasslands")
input()
print(".............")
input()
print("The ground rumbles.....")
input()
print("Another steel-plated guardian appears")
input()
battles()
print("The path is finally clear")
input()
print("You proceed towards the EAST pathway")
input()
print("An approximate of two monsters will spawn here")
input()
print("WHOOSH")
input()
print("A rogue warrior emerges from within the huge bushes")
input()
battles()
print("You run forward")
input()
print("Two more rogue warriors run towards you")
input()
battles()
print("Now remains the last stage of the deadly grasslands")
input()
print("You make the turn")
input()
print("You see the other end of the Grasslands")
input()
print("There is a chair at a high position")
input()
print("Two figures seem to be running towards you")
input()
print("Prepare for combat")
battles()
input()
battles()
input()
print("You seem to have beat the two orcs")
input()
print("Well, seems like it's time")
input()
print("IT's ONE OF THE HACKERS")
input()
print("Fight me, and I take this mask off")
input()
boss_battle()
print("Ahhhhhhhhhhhhhhhhhh")
input()
print("This can't be happening")
input()
print("Now that we're done here..")
input()
print("Show me your face!")
input()
print("Pfff..")
input()
print("TAKES MASK OFF")
input()
print("Oh, so it's you Chaps")
input()
print("You know you won't win right")
input()
print("Even though you defeated me, you can't get past shad....")
input()
print("Who?")
input()
print("NOTHING, now as promised, I'll give you the location of the next town")
input()
print("Where can I find the others in your pathetic group")
input()
print("Huh, you have a big mouth don't you")
input()
print("hehehehehhehhe......")
input()
print("HAHHAHAHHAHAHAHHAHA")
input()
print("A flash of blue light and the player vanishes.........")
input()
print("Well, he's done for")
input()
print("TING TING TING")
input()
print("Huh, what's th..........")
input()
print('{:^80}'.format("SERVER ANNOUNCEMENT"))
time.sleep(2)
print('{:^80}'.format("TOWN OF REPLAUD NOW AVAILABLE TO ALL PLAYERS"))
time.sleep(2)
print('{:^80}'.format("TO REACH, PLEASE CLEAR DUNGEON"))
time.sleep(2)
input()
elif command == "Dungeon":
print("The dungeon cannot be accessed yet")
input()
print("To unlcok the dungeon, you must clear the grasslands")
input()
else:
print("You seem to have entered a wrong command")
input()
print("""Please enter either of these:
1. Inn
2. Store
3. Greenlands
4. Dungeon
""")
townone()
townone()
It's not clear what's causing the error from the code you posted, but from the behavior you describe it sounds like you're not defining mobHP as a global. Here's some example code.
mobHP = 20000
playerHP = 30000
def check_hps():
if mobHP <= 0:
win()
if playerHP <= 0:
lose()
def broken_attack():
attack_value = 100 # how hard you hit
mobHP -= attack_value
check_hps()
def fixed_attack():
global mobHP
attack_value = 100
mobHP -= attack_value
check_hps()
To demonstrate:
>>> mobHP
20000
>>> broken_attack()
>>> mobHP
20000
>>> fixed_attack()
>>> mobHP
19900
>>> fixed_attack()
>>> mobHP
19800
This code is, of course, really difficult to maintain. It is, however, pretty easy to implement. Contrast with:
class Actor(object):
def __init__(self, name, maxHP, min_dmg, max_dmg):
self.name = name
self.maxHP = maxHP
self.currentHP = maxHP
self.roll_dmg = lambda: random.randint(min_dmg, max_dmg)
def attack(self, other, retaliation=False):
other.currentHP -= self.roll_dmg()
if not retaliation:
other.attack(self, retaliation=True)
def run(self, other):
if random.random() >= 0.5:
return True
return False
class Battle(object):
def __init__(self, *actors, location=None):
self.actors = actors
self.location = location
def do_round(self):
for actor in self.actors:
choice, target = self.make_choice(actor)
self.do_choice(choice, target)
yield self.check_battle_over()
def check_battle_over(self):
for actor in self.actors:
if actor.currentHP <= 0:
return actor
return None
def do_choice(self, func, target):
return func(target)
def make_choice(self, actor):
print("1. Attack\n"
"2. Run away\n")
choice = input(">> ")
if choice == '1':
action = actor.attack
elif choice == '2':
action = actor.run
actor_mapping = {num:act for num,act in enumerate(
filter(lambda a: a is not actor), start=1}
print("Target:")
print("\n".join(["{}. {}".format(*target) for target in actor_mapping.items()]))
target = actor_mapping[input(">> ")]
return (action, target)
def start(self):
while True:
loser = do_round()
if loser:
print(loser.name + " is dead!")
return
player = Actor(name="Player", maxHP=30000,
min_dmg=80, max_dmg=200)
monster = Actor(name="Monster", maxHP=20000,
min_dmg=50, max_dmg=100)
battle = Battle(player, monster)
battle.start()

Categories