Variable does not change in IF statement - python

I've tried to make a very simple RPG combat system.
But there's an error when the health goes below 0 and does nothing:
jack_battle_loop_1 = True
while jack_battle_loop_1:
battle_menu()
choise = input("> ")
if choise == "1":
#(jack_health + jack_defense) - my_damage = jack_health
jack_health = (jack_health + jack_defense) - random.randrange(20, 25)
#Processing the updated enemy health
print(deskemon + " HAVE INFLICTED " + str(random.randrange(20, 25)) + " TO CHIPHEAD")
print("CHIPHEAD HAS " + str(jack_health) + " HITPOINTS LEFT!")
time.sleep(1)
print("...")
time.sleep(1)
print("...")
time.sleep(1)
print("...")
time.sleep(1)
#(my_health + my_defense) - jack_damage = my_health
my_health = (my_health + my_defense) - jack_damage
print("CHIPHEAD HAVE INFLICTED " + str(jack_damage) + " TO " + deskemon)
print(deskemon + " HAS " + str(jack_health) + " HITPOINTS LEFT!")
jack_battle_loop = True
elif jack_health <= 0:
jack_battle_loop = False
elif my_health <= 0:
jack_battle_loop = False
elif choise == "":
jack_battle_loop = True
But instead, it outputs this:
TIMOHA HAVE INFLICTED 23 TO CHIPHEAD
CHIPHEAD HAS -24 HITPOINTS LEFT!

The elif statements are only executed if choise != "1". It seems the ifs that check health should be independent of the ifs that check the choices.
Something like
if choice == "1":
# do stuff
if jack_health <= 0 or my_health <= 0:
jack_battle_loop = False

Try this after your if choise == "1": line:
jacksdamage=random.randrange(20, 25)
jack_health = (jack_health + jack_defense) - jacksdamage
if jack_health<=0:
print "Jack recieved %.i damage and was killed!"%(jacksdamage)
break
else:
print "Jack took %.i damage. from CHIPHEAD."%(jacksdamage)
print "Jack has %.i hitpoints left."%(jack_health)
for _ in range(5):
time.sleep(1)
print "..."
mydamage=random.randrange(20,25)
my_health = (my_health + my_defense) - mydamage
if my_health<=0:
print deskemon+' took %.i damage from jack and was killed!'%(mydamage)
break
else:
print deskmon+' took %.i damage from jack.'%(mydamage)
print deskmon+' has %.i health left.'%(my_health)
for _ in range(5):
time.sleep(1)
print "..."

Related

Can someone please explain to me why the 'health' var is not updated when calling the updateGame() func

Been looking online for some answers, however it's still unclear to me why the 'health' var is not updated when calling the getDamage() func
I'm on my first few miles learning python
health = 200.0
maxHealth = 200
healthDashes = 20
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
gameOver = False
def updateGame():
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health = 10
while gameOver == False:
answer = raw_input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Is there anything I can do to properly update the "health" var and disply a reduced health the next time I call the getDamage() func?
Basically what I'm trying to achieve is a text-based game to run in a while loop and have different functions to update a primary function (updateGame) that display relevant info about the player's state like health, inventory items.
The logic I'm trying to implement is:
have getDamage() reduce the health var and then display the newly change variable with updateGame()
Many thanks
health will change to 10 when you call getDamage() but healthDisplay, remainingDisplay and percent are set at the first of script and won't change everytime that healt global variable is changed. so you must change them in updateGame() function everytime it's called. Also i guess health = 10 must change to health -= 10!
health = 200.0
maxHealth = 200
healthDashes = 20
gameOver = False
def updateGame():
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health -= 10
while gameOver == False:
answer = input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Inside the updateGame function, you never make reference to the global variable health. If you want health to change inside the function, you will need to access it.
This means you should have something like:
def updateGame():
global health
health = updatedHEALTH
...
Then it should change each time you call the function

Why is it that the list variables in this code gets values in them backwards? HP is the last assigned variable despite being there first in the list

I'm making a simple program (I am a beginner at python) where I fight a monster with random assigned values. I used 2 lists with 4 variables each depicting hp atk def and spd. They get assigned a random number of 10 to 15 and get multiplied by 2. I don't really know what I am doing wrong here.
import random
monsters = ["slime","goblin","troll","dryad","bard","clown"]
hp,atk,dfn,spd = 0,0,0,0
mhp,matk,mdfn,mspd = 0,0,0,0
stats = [hp,atk,dfn,spd]
mstats = [hp,atk,dfn,spd]
damage = 0
defend = 0
action = "none"
name = input()
print("Your name is " + name + ", time to battle!")
for x in stats:
stats[x] = random.randint(10,15) * 2
print("Your stats(hp/a/d/s): " + str(stats[x]))
for y in mstats:
mstats[y] = random.randint(10,15) * 2
print("Monster stats(hp/a/d/s): " + str(mstats[y]))
while stats[hp] > 0 or mstats[hp] > 0:
print("What will you do? 1 for attack, 2 for defend, others to give up")
action = input()
if action == "1":
damage = stats[atk] / 2 + random.randint(1,5)
mstats[hp] = mstats[hp] - damage
print("You slash the monster for " + str(damage) + " damage!" )
print("Monster HP: " + str(mstats[hp]))
damage = mstats[atk] / 2
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action == "2":
damage = mstats[atk] / 2 - random.randint(3,5)
if damage > 0:
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action != "1" and action != "2":
stats[hp] = 0
if stats[hp] < 0 or stats[hp] == 0:
print("You lose!")
if mstats[hp] < 0:
print("You win!")
Hopefully this code isn't a mess, I thank you all in advance if extra corrections can be given.

Can't call list from within class.

When I run the code I get the error message:
"AttributeError: type object 'Player' has no attribute 'hkslist'"
Why can't I call the list from within the class? The Idea is that the list is supposed to choose one of two of the functions from within the list and then run that once it's called upon.
Full code:
import random
from time import *
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Player:
coins = 100
health = 100
p = 3 #Potions
hoursslept = 0
def __init__(self):
random.seed()
print("init instance variables here")
#self.coins = random.randint(100, 500) Förlegad kod.
def hk1():
print("Du sprang iväg")
def hk2():
#print("Du försökte springa iväg men trillade och slog i knät: - 20 HP")
print("Du sprang iväg")
sleep(3)
print("men du trillar och slår i knät: -20 HP")
self.health = self.health - 20
print("Your health is: " + str(self.health), " HP")
#Fortsätt 'storyn'
def hkf1():
print("Du besegrade håkan")
print("Du tar hans droger och säljer det själv till Eleverna: +150 coins")
print("Your health is ", str(self.health), " HP")
self.coins = self.coins + 150
print("You have: ", str(self.coins), " coins")
def hkf2():
print("Håkan besegrade dig: -50 HP")
print("Your health is ", str(self.health), " HP")
print("You have: ", str(self.coins), " coins")
self.coins = self.coins + 150
self.hkslist = [hk1, hk2]
self.hkflist = [hkf1, hkf2]
self.indhks = random.randint(0,len(self.hkslist)-1)
self.indhkf = random.randint(0,len(self.hkflist)-1)
def report_status(self):
status_message = "Your health is %s, \nCoins left %s" % (self.health, self.coins)
return status_message
william = Player()
hakan = Player()
print("Welcome to a poorly made text-based game:")
print("you have ", william.p, " potions")
print("Your health is ", str(william.health), " HP")
print("You have: ", str(william.coins), " coins")
while True:
print("Commands: add, drink, coins, sleep, quest")
a = input("Enter a command: ")
if a == "add" or a == "Add" or a == "buy" or a == "Buy":
if william.coins == 0:
print("You can't afford a potion")
else:
william.coins = william.coins - 25
william.p = Player.p + 1
print("You bought a potion for 25 coins")
print("You have ", william.coins, " coins left")
print("you have ", william.p, " potions")
print("Your health is now ", str(william.health), " HP")
if a == "drink":
if Player.p == 0:
print("You can't drink any potions.")
print("You have zero potions left!")
print("Your health is ", str(william.health), " HP")
elif william.health >= 250:
print("Your health is already maxed out. You can't drink a potion.")
print("you have ", str(william.p), " potions")
print("Your health is ", str(william.health), " HP")
else:
william.health = william.health + 20
william.p = william.p - 1
print("you have ", william.p, " potions")
print("Your health is ", str(william.health), " HP")
if a == "sleep":
if william.health >= 250:
print("Your health is already maxed out. You can't drink a potion.")
print("Your health is ", str(william.health), " HP")
else:
william.health = william.health + 5
print("you have ", str(william.p), " potions")
print("Your health is ", str(william.health), " HP")
if a == "I" or a == "i" or a == "inv" or a == "inventory":
if william.p == 0:
print("Your backpack is empty")
else:
print("you have ", str(william.p), " potions")
print("Your health is ", str(william.health), " HP")
if a == "quest":
quest = input("Choose from quest: 1, 2 or 3 ")
if quest == "1" or quest == "option 1" or quest == "opt 1":
print("Du vandrar runt på Rudbeck när du ser Håkan, din samhällslärare, i ett mörkt hörn")
print("Du väljer att gå närmare för att investigera.")
print("Håkan står och säljer knark till eleverna.")
hk = input("Vad gör du? Spring: Slåss:")
if hk == "Spring" or hk == "spring":
Player.hkslist[Player.indhks]()
if hk == "slåss" or hk == "Slåss" or hk == "s":
Player.hkflist[Player.indhkf]()
if a == "coins":
if william.coins >= 500:
print("You're filthy rich!!!")
print("You have: ", str(william.coins), " Coins")
else:
print("You have: ", str(william.coins), " Coins")
#Debug tools
if a == "add coin" or a == "AC" or a == "ac" or a == "more":
extracoins = input("How many coins do you want?: ")
Player.coins = int(extracoins)
print("You now have: ", str(william.coins), " Coins")
hkslist is an attribute of an instance of Player not of the Player class itself. You can see this in the definition of hkslist (self.hkslist = [hk1, hk2]) where hkslist is defined on self. If you want to access hkslist you'll need to create an instance of Player. For example:
player = Player()
player.hkslist[player.indhks]()

Python - print name shows None

import re
import time
import sys
def main():
name = getName()
getOption()
nameForTicket, done = getTraveling(name)
price, destination = getWay()
fare = getFare()
seat = getSeat()
age = getAge()
totalcost = getTotalCost(price, fare, seat, age)
print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket).title())
main2(name, done)
def getName():
name = input("Welcome to Tropical Airlines! Please enter your name >>> ")
if not re.match("^[a-zA-Z ]*$", name):
print("Error, only letters allowed!")
getName()
elif len(name) > 15:
print("Error, Only 15 characters allowed!")
getName()
else:
print ("Welcome " + name.title())
return name
def getOption():
print("(I) Information" + "\n" + "(O) Order" + "\n" + "(E) Exit")
user_choice = input("Choose one of the following option >>> ")
if user_choice.upper() == "I":
displayInfo()
else:
if user_choice.upper() == "O":
return
else:
if user_choice.upper() == "E":
print("Thank you for visiting Tropical Airlines")
exit()
else:
print("Error")
getOption()
def displayInfo():
print("Thank you for choosing Tropical Airlines for your air travel needs." + "\n" + "You will be asked questions regarding what type of ticket you would like to purchase as well as destination information." + "\n" + "We also offer 50% discounted fares for children.")
getOption()
def getTraveling(name):
option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else")
if option.upper() == "Y":
nameForTicket = name
done = True
return nameForTicket, done
elif option.upper() == "S":
nameForTicket = getName2()
done = False
return nameForTicket, done
else:
print("Error")
getTraveling(name)
def getName2():
name2 = input("What is the travelling person name?")
if not re.match("^[a-zA-Z ]*$", name2):
print("Error, only letters allowed!")
getName2()
elif len(name2) > 15:
print("Error, Only 15 characters allowed!")
getName2()
else:
return name2
def getWay():
option = input("What kind of trip?" + "\n" + "(1) One way" + "\n" + "(2) Round trip")
if option == "1":
cost, destination = getDest1()
return cost, destination
elif option == "2":
cost, destination = getDest2()
return cost, destination
else:
print("Error")
getWay()
def getDest1():
option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $200" + "\n" + "(P) Perth -- $250" + "\n" + "(S) Sydney -- $300")
if option.upper() == "C":
initialCost = 200
dest = "Cairns"
return initialCost, dest
elif option.upper() == "P":
initialCost = 250
dest = "Perth"
return initialCost, dest
elif option.upper() == "S":
initialCost = 300
dest = "Sydney"
return initialCost, dest
else:
print("Error")
getDest1()
def getDest2():
option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $300" + "\n" + "(P) Perth -- $400" + "\n" + "(S) Sydney -- $500")
if option.upper() == "C":
initialCost = 300
dest = "Cairns"
return initialCost, dest
elif option.upper() == "P":
initialCost = 400
dest = "Perth"
return initialCost, dest
elif option.upper() == "S":
initialCost = 500
dest = "Sydney"
return initialCost, dest
else:
print("Error")
getDest2()
def getFare():
option = input("Choose one of the following type of fare: " + "\n" + "(B) Business -- Extra $200" + "\n" + "(E) Economy -- Extra $50" + "\n" + "(F) Frugal -- Free")
if option.upper() == "B":
fare = 200
return fare
elif option.upper() == "E":
fare = 50
return fare
elif option.upper() == "F":
fare = 0
return fare
else:
print("Error")
getFare()
def getSeat():
option = input("Choose one of the following type of seat: " + "\n" + "(W) Window -- $20" + "\n" + "(A) Aisle -- $15" + "\n" + "(M)Middle -- $10")
if option.upper() == "W":
seat = 20
return seat
elif option.upper() == "A":
seat = 15
return seat
elif option.upper() == "M":
seat = 10
return seat
else:
print("Error")
getSeat()
def getAge():
age = int(input("Enter the age, if the age is bellow 17, you will get 50% discount >>> "))
while age < 6 or age > 100:
print("Invalid age")
age= int(input("Enter the valid age >>>"))
return age
def getTotalCost(price, fare, seat, age):
if age <18:
finalCost = (price + fare + seat)/2
else:
finalCost = price + fare + seat
return finalCost
def loading():
for i in range(101):
time.sleep(0.02)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
def main2(name, done):
getOption()
nameForTicket = getTraveling2(name, done)
price, destination = getWay()
fare = getFare()
seat = getSeat()
age = getAge()
totalcost = getTotalCost(price, fare, seat, age)
print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket2).title())
main2(name, done)
def getTraveling2(name, done):
option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else")
if option.upper() == "Y":
if done == True:
print("You have already ordered ticket for you!")
getTraveling2(name, done)
elif done == False:
nameForTicket = name
done = True
return nameForTicket, done
elif option.upper() == "S":
nameForTicket = getName2()
return nameForTicket
else:
print("Error")
getTraveling2(name, done)
main()
Short story I was writing these long codes.
If from def main() in nameForTicket, done = getTraveling(name) I choose Y, the code shows the name instr(nameForTicket).title() for the def main() just fine.
but in def main2(): for the function getTraveling2(name, done) if I choose S, the str(nameForTicket2).title() in def main2(): will show None.
And the same happens if from main() I choose S, the main2() if I choose S will show none, and if I choose Y, it will display (Name, True)
how to fix it so the name will show based on the input for S?
In main2, change
nameForTicket = getTraveling2(name, done)
to
nameForTicket2 = getTraveling2(name, done)
because your print statement in main2 addresses str(nameForTicket2).title(), which is trying to print the title of nameForTicket2 when you set the result of the getTraveling2 method to nameForTicket instead. Therefore, the print statement gives you None since nameForTicket2 was never really defined.

When my conditional is false in when it turns true why wont the loop stop

Here is my code
in python 3.4 it just keeps running the loop until the system exit when the player dies this is part of an rpg game i have been making for fun
Not entire code please note if you would like to see entire code please ask only combat function shown
def combat(h, a, d, x):
global attack
global health
global defence
global xp
death = False
while death == False:
eab = random.randint(1, 10)
yab = random.randint(1, 10)
cattack = 0
cdefence = 0
cattack = attack
cdefence = defence
cattack = cattack + yab
a = a + eab
d = d - cattack
print("you strike for " + str(cattack) + " damage")
cattack = cattack - d
if cattack > 0:
h = h - cattack
if d > 0:
print("the enemy has " + str(d) + "defence left")
if h > 0:
print("the enemy has " + str(h) + "Health left")
else :
print("the enemy dies")
death == True
xp = xp + x
print("they strike back for " + str(a))
cdefence = cdefence - a
a = a - cdefence
if a > 0:
health = health - a
if cdefence > 0:
print("you have " + str(cdefence) + " defence left!")
if health > 0:
print("you have " + str(health) + " health left")
else :
sys.exit("YOU DIED A HORRIBLE DEATH")
Your problem is with this line: death == True
This compares the variable 'death' with the True function, which will never work. What you need to do instead is replace that with death = True.
This should fix your code.

Categories