List Index Out of Range, Why Is This Happening? - python
Here's the error I'm getting:
Traceback (most recent call last):
File "E:\python\cloud.py", line 34, in <module>
c = Cloud()
File "E:\python\cloud.py", line 18, in __init__
self.cweaponAttack = self.weaponAttack[0]
IndexError: list index out of range
I'm having trouble with my code and I have checked for spelling errors everywhere but I haven't found any.
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
The lines above is where i'm positive that the error is coming from, but just in case, here's the rest of the code. Warning: It's very long.
import random
import time
import sys
def asky():
ask = input("Would you like to check you player stats and inventory or go to the next battle? Say inventory for inventory or say next for the next battle: ")
if "inventory" in ask:
inventory()
elif "next" in ask:
user()
def Type(t):
t = list(t)
for a in t:
sys.stdout.write(a)
time.sleep(.035)
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
class Soldier:
def __init__(self):
dmg = random.randint(5,20)
self.lvl = 0
self.attackPower = dmg
self.hp = 100
self.mhp = 100
self.name = "Soldier"
s = Soldier()
def enemy():
ad = random.randint(0,2)
if ad >= 1: #Attack
Type("Soldier attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0, 2)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,10)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((s.attackPower) * (.5))
c.hp = c.hp - (s.attackPower + crithit)
elif crit >= 1:
c.hp = c.hp - s.attackPower
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
elif ad == 0:#Defend
Type("Soldier Defends!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if s.hp == s.mhp:
print("")
elif s.hp > (s.mhp - 15) and s.hp < s.mhp:
add = s.mhp - s.hp
s.hp = add + s.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif s.hp < (s.mhp - 15):
s.hp = s.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
def user():
User = input("attack or defend? ")
if "attack" in User:#attack
Type("Cloud attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0,4)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,7)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((c.dmg) * (.5))
s.hp = s.hp - (c.dmg + crithit)
elif crit >= 1:
s.hp = s.hp - c.dmg
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
elif "defend" in User:#defend
Type("Cloud Heals!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp == c.mhp:
Type("You are at the maximum amount of health. Cannot add more health.")
print("")
elif c.hp > (c.mhp - 15) and c.hp < c.mhp:
add = c.mhp - c.hp
c.hp = add + c.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif c.hp <= (c.mhp - 15):
c.hp = c.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("Congratulations!")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
else:
Type("The option you have entered is not in the game database. Please try again")
print("")
user()
def inventory():
if c.exp == c.mexp:
print("LEVEL UP!")
c.exp = 0
adde = int((c.mexp) * (.5))
c.mexp = c.mexp + adde
c.sp = c.sp + 1
c.lvl = c.lvl + 1
if c.lvl > s.lvl:
s.lvl = s.lvl + 1
print("")
print("")
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print(i)
print("Weapon: ", c.weapon[i])
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for j in range(0, len(c.armor)):
print("Armor: ", c.armor[j])
print("Armor Damage Reduction: ", c.armorReduction[j])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Overall Damage: ", c.dmg)
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), or say, *help* for help: ")
print("")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
else:
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print("Weapon:", c.weapon[i])
print("")
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for i in range(0, len(c.armor)):
print("Armor: ", c.armor[i])
print("")
print("Armor Damage Reduction: ", c.armorReduction[i])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), say, *weapon* to switch your current weapon, or say, *help* for help: ")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power. To switch out your weapons, type in, *weapon*.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
def weapChange():
for i in range(0, len(c.weapon)):
print("Weapon:", "To equip", c.weapon[i], ",say", i)
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
weapchoice = input("Enter the weapon ID to the sword you would like to equip, or say, *cancel*, to go back to your inventory. ")
print("")
if "0" in weapchoice:
c.cweapon = c.weapon[0]
c.cweaponAttack = c.weaponAttack[0]
print("Success!", c.weapon[0], "is now equipped!")
inventory()
elif "1" in weapchoice:
c.cweapon = c.weapon[1]
print("Success!", c.weapon[1], "is now equipped!")
inventory()
c.cweaponAttack = c.weaponAttack[1]
elif "2" in weapchoice:
c.cweaponAttack = c.weaponAttack[2]
c.cweapon = c.weapon[2]
print("Success!", c.weapon[2], "is now equipped!")
inventory()
elif "3" in weapchoice:
c.cweaponAttack = c.weaponAttack[3]
c.cweapon = c.weapon[3]
print("Success!", c.weapon[3], "is now equipped!")
inventory()
elif "4" in weapchoice:
c.cweaponAttack = c.weaponAttack[4]
c.cweapon = c.weapon[4]
print("Success!", c.weapon[4], "is now equipped!")
inventory()
elif "5" in weapchoice:
c.cweaponAttack = c.weaponAttack[5]
c.cweapon = c.weapon[5]
print("Success!", c.weapon[5], "is now equipped!")
inventory()
elif "6" in weapchoice:
c.cweaponAttack = c.weaponAttack[6]
c.cweapon = c.weapon[6]
print("Success!", c.weapon[6], "is now equipped!")
inventory()
elif "7" in weapchoice:
c.cweaponAttack = c.weaponAttack[7]
c.cweapon = c.weapon[7]
print("Success!", c.weapon[7], "is now equipped!")
inventory()
elif "8" in weapchoice:
c.cweaponAttack = c.weaponAttack[8]
c.cweapon = c.weapon[8]
print("Success!", c.weapon[8], "is now equipped!")
inventory()
elif "9" in weapchoice:
c.cweaponAttack = c.weaponAttack[9]
c.cweapon = c.weapon[9]
print("Success!", c.weapon[9], "is now equipped!")
inventory()
elif "cancel" in weapchoice:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
print("")
weapChange()
def skills():
print("")
print("You have", c.sp, "skill points to use.")
print("")
print("Upgrade attack power *press the number 1*")
print("")
print("Upgrade maximum health *press the number 2*")
print("")
skill = input("Enter the number of the skill you wish to upgrade, or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in skill:
sure = input("Are you sure you want to upgrade your character attack power in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your attack power. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.attackPower = float(c.attackPower + .1)
addsap = int(100 * c.attackPower)
print("Your attack power has been upgraded to deal", addsap, "% more damage")
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "2" in skill:
sure = input("Are you sure you want to upgrade your maximum health in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your maximum health. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.mhp = c.mhp + 30
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "cancel" in skill:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
skills()
def shop():
print("")
Type("Welcome to Andrew's Blacksmith! Here you will find all the weapons, armor, and health you need, to defeat the horrid beast who goes by the name of Murlor! ")
print("")
print("")
print("Who's Murlor? *To ask this question, type in the number 1*")
print("")
print("Can you heal me? *To ask this question, type in the number 2*")
print("")
print("What weapons do you have? *To ask this question, type in the number 3*")
print("")
print("Got any armor? *To ask this question, type in the number 4*")
print("")
ask1 = input("Enter desired number here or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in ask1:
def murlor():
Type("Murlor is a devil-like creature that lives deep among the caves of Bricegate. He has been terrorising the people of this village for centuries.")
print("")
print("")
print("What is Bricegate? *To choose this option, type in the number 1*")
print("")
print("Got any more information about this village? *To choose this option, type in the number 2*")
print("")
print("Thank you! *To choose this option, type in the number 3*")
print("")
ask3 = input("Enter desired number here, or say, cancel, to go back to the main shop screen. ")
print("")
if "1" in ask3:
def questionTown():
Type("That's the name of this town.")
print("")
print("")
town = input("Go back? *Say, yes, to go back to the previous screen*")
print("")
if "yes" in town:
murlor()
else:
Type("I'm sorry but the word you have entered is invalid. Please try again.")
print("")
print("")
questionTown()
questionTown()
elif "2" in ask3:
def askquest1():
Type("Well I DO know that there's this secret underground dungeon. It's VERY dangerous but it comes with a huge reward. If you ever consider it, could you get my lucky axe? I dropped it down a hole leading to the dungeon and i was too afraid to get it back. *If you accept the quest, say yes, if you want to go back, say, no.*")
quest1 = input(" ")
print("")
if "yes" in quest1:
quest1()
elif "no" in quest1:
murlor()
else:
Type("The option you have selected is not valid. Please try again")
print("")
print("")
askquest1()
askquest1()
elif "3" in ask3:
shop()
else:
Type("The number or word you have entered is invalid. please try again.")
print("")
print("")
murlor()
murlor()
elif "2" in ask1:
def heal():
if c.hp == c.mhp:
Type("I can't heal you because there's nothing to heal.")
print("")
print("")
shop()
elif c.hp > 10 and c.hp < c.mhp:
Type("Sure! That'll be 30 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
elif c.hp > 0 and c.hp <= 10:
Type("How are you still alive?!")
print("")
print("")
Type("That'll be 50 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
else:
Type("HELP!! IT'S THE WALKING DEAD!!")
print("")
print("")
shop()
heal()
user()
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
You set self.weaponAttack to be an empty list, and then try to assign cweaponAttack to be the element at index 0 in weaponAttack - empty lists don't have anything at index 0, as they are empty. I'm guessing you want self.cweaponAttack to be nothing when a new Cloud instance is created, in which case if you need it to be nothing you can set it to be None, else you can just assign to it when needed.
self.cweaponAttack = None
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
At the time of the second line, self.weaponAttackis an empty list, and therefore doesn't have any elements. Hence, an index of 0 is out of range for self.weaponAttack.
At the time the instance of the class is first created with Cloud(), self.weaponAttack is an empty list, and there will be no such thing as an index 0.
You may consider passing a non-empty list to self.weaponAttack as an argument via the class constructor:
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c = Cloud(weaponAttacks)
And your class becomes:
class Cloud:
'''This is the Cloud class etc.'''
weaponAttack = list()
def __init__(self, weaponAttacks):
self.weaponAttack = weaponAttacks
self.cweaponAttack = self.weaponAttack[0]
Related
I'm trying to make a code so when the player attacks the enemy, the enemy's health goes down and doesn't reset
I'm new to coding and was struggling to make it so that when the player attacks the enemy, it updates the enemies health and the player is able to attack again until the health of the enemy is 0. Ive come up with this but every time I make a second attack the goblins health goes back to 100 and goes from there. For example, if I do a "basic attack" it does 100-20 = 80, but when I attack again, lets say another "basic attack" it displays 80 again instead of 60. def combat_enemy_goblin(): small_goblin_health = 100 attack_basic = 20 attack_special = 50 attack_ultimate = 100 print("You are now in combat with a small goblin!") print("") print("") print("Small Goblin: ", small_goblin_health, "Health Points") while True: try: users_attack = int(input(""" Your Moves ---------------------------- 1 - Basic attack [20] 2 - Special attack [50] 3 - Ultimate attack [100] 4 - Run [repeating action] ---------------------------- What do you choose? """)) if users_attack == 1: print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health - 20, "Health points") print("") else: if users_attack == 2: print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health - 50, "Health points") print("") else: if users_attack == 3: print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health - 100, "Health points") print("") else: if users_attack == 4: print("") print(" You tried to run away but failed!") except: print("") print("You cant do that!") print("") combat_enemy_goblin()
Your problem in code is you are only subtracting value from goblin health but not changing it. I have written a comment where I change the code. -= in code means that you are removing the value from a variable and assigning it to the result. num = 10 print(num) # Output: 10 num-=1 print(num) # Output: 9 One more change in your code is you do not exit the program even if the goblin health is 0 or less I am adding this in the below code. small_goblin_health = 100 attack_basic = 20 attack_special = 50 attack_ultimate = 100 print("You are now in combat with a small goblin!") print("") print("") print("Small Goblin: ", small_goblin_health, "Health Points") while True: if small_goblin_health<=0: # edited break # exit the loop if small_goblin_health is less than or equal to 0. try: users_attack = int(input(""" Your Moves ---------------------------- 1 - Basic attack [20] 2 - Special attack [50] 3 - Ultimate attack [100] 4 - Run [repeating action] ---------------------------- What do you choose? """)) if users_attack == 1: small_goblin_health-=20 #edited print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health, "Health points") print("") elif users_attack == 2: small_goblin_health-=50 #edited print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health, "Health points") print("") elif users_attack == 3: small_goblin_health-=100 #edited print("") print("You use your basic attack") print("") print("The goblin has taken some damage") print("") print("Small Goblin: ", small_goblin_health, "Health points") print("") elif users_attack == 4: print("") print(" You tried to run away but failed!") except ValueError: # edited print("") print("You cant do that!") print("")
In hope this helps if users_attack == 1: small_goblin_health -= 20 elif users_attack == 2: small_goblin_health-=50 elif users_attack == 3: small_goblin_health-=100
How can I short this code with class and object
I am making an investment game in which the Gold and Bitcoin prices go down and up day by day but here I am getting a problem how can I make this code easy so I can add any other crypto and share with just 2-3 lines of code but now I have to code whole if-else statement to do this Can I use Classes and objects but how This is the code How can I Improve goldPrice = 63 # $ dollars per gram bitcoinPrice = 34000 # $ dollars per bitcoin day = 1 # life start with this day myGold = 0 # in Grams myBitcoin = 0.0 # in bitcoin def newspaper(): print("GOLD: " + str(goldPrice) + '$ per gram') print("BITCOIN: " + str(bitcoinPrice) + "$") print("An investment in knowledge pays the best interest.") def invest(): global balance, myGold, myBitcoin print("====Which Thing you want to Buy====") print("1. Gold") print("2. Bitcoin") print("3. Nothing, Go Back") investInputKey = int(input()) if investInputKey == 1: print("Gold: " + str(goldPrice) + ' per gram' +'\n') print("1. Buy") print("2. Sell") print("3. Exit") goldInput = int(input()) if goldInput == 1: print("Enter Amount in Grams: ") howMuch = int(input()) totalGoldBuy = howMuch * goldPrice print(totalGoldBuy) if totalGoldBuy > balance: print("Insufficient Balance!") else: print("Thank you! Have a Nice Day") balance -= totalGoldBuy myGold += howMuch elif goldInput == 2: print("Enter Amount in Grams: ") howMuch = int(input()) if howMuch > myGold: print("Insufficient Gold!") else: print("Thank you! Have a Nice Day") myGold -= howMuch newGold = howMuch * goldPrice balance += newGold elif goldInput == 3: print("Thank you! Have a Nice Day") else: print("Wrong Input!") elif investInputKey == 2: print("Bitcoin: " + str(bitcoinPrice) +'\n') print("1. Buy") print("2. Sell") print("3. Exit") bitcoinInput = int(input()) if bitcoinInput == 1: print("Enter Bitcoin Amount in Dollars") howMuch = int(input()) if howMuch > balance: print("Insufficient Balance!") elif howMuch > 500: myBitcoin = howMuch / bitcoinPrice balance -= howMuch else: print("You can only buy above 500$") elif bitcoinInput == 2: print("Enter Bitcoin Amount in Dollars") howMuch = int(input()) if howMuch > (myBitcoin * bitcoinPrice): print("Insufficient Bitcoin"); elif howMuch < 500: print("You can only sale above 500 Dollars") else: myBitcoin -= howMuch / bitcoinPrice balance += howMuch elif goldInput == 3: print("Thank you! Have a Nice Day") else: print("Wrong Input!") elif investInputKey == 3: print("Thank you! Have a Nice Day"); else: print("Wrong Input!") while True: print("========HOME========" + '\n') print("====Day-" + str(day) + "====") print("====Balance-" + str(balance) + "$ ====") print('\n') print("1. Newspaper") print("2. Invest") print("3. My Portfolio") print("4. Next Day") print("5. Exit") inputKey = int(input()) if inputKey == 1: newspaper() elif inputKey == 2: invest() elif inputKey == 3: print("========Portfolio========" + '\n') print("Gold: " + str(myGold) + " gram") print("Bitcoin: " + str(myBitcoin)) elif inputKey == 4: day += 1 print("This is day " + str(day)) # Change price of gold and bitcoin elif inputKey == 5: # Add sure you want to exit break else: print("Wrong Input! Try Again") Help me, Thank You
User/Player Health is not saved during attack simulation using a coin and random
I am a novice to python. My longterm project is to design a choose your own adventure text-based game. A major component of this game is attack scenarios. With that in mind, I have been constructing a python program for simulating an attack scenario. In this case, by flipping a coin to first determine whether the player or the enemy attacks first. Afterwards, a random integer between 1 and 10 is used as the attack damage. A function (HealthCheck), checks the health of the player/enemy to determine whether the player/enemy is dead. My main problem is that the enemy's and player's health restarts after an attack. How can my program save the user's health after an attack, instead of resetting to 10 HP? Below is my python code. Thank you for your help. import random import time import sys enemyHealth = 10 playerHealth = 10 def playerAttack(enemyHealth): attack_damage = random.randint(1, 10) print("The player does " + str(attack_damage) + " damage points to the enemy.") enemyHealth -= attack_damage print("The enemy has " + str(enemyHealth) + " HP left!") enemyHealthCheck(enemyHealth) pass def enemyAttack(playerHealth): attack_damage = random.randint(1, 10) print("The enemy does " + str(attack_damage) + " damage points to the player.") playerHealth -= attack_damage print("The player has " + str(playerHealth) + " HP left!") playerHealthCheck(playerHealth) pass def turnChoice(): h = 1 t = 2 coin = "" while coin != "h" and coin != "t": coin = input("Player, flip a coin to decide who attack first.\n" "Heads or tails? H for heads. T for tails.\n") if coin == "h": print("You chose heads.\n" "Flip the coin. \n" ". . .") time.sleep(2) else: print("You chose tails.\n" "Flip the coin. \n" ". . .") time.sleep(2) choice = random.randint(1, 2) if choice == coin: print("Great choice. You go first.") playerAttack(enemyHealth) else: print("Enemy goes first.") enemyAttack(playerHealth) def replay(): playAgain = "" while playAgain != "y" and playAgain != "n": playAgain = input("Do you want to play again? yes or no") if playAgain == "y": print("You chose to play again.") print(".") print(".") print(".") time.sleep(2) turnChoice() else: print("Game over. See you soon.") sys.exit() def playerHealthCheck(playerHealth): if playerHealth <=0: print("Player is dead. Game over.") replay() else: print("The player has " + str(playerHealth) + " HP points!") print("It is your turn to attack.") playerAttack(enemyHealth) def enemyHealthCheck(enemyHealth): if enemyHealth <=0: print("Enemy is dead. You win.") replay() else: print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.") print("It is their turn to attack.") enemyAttack(playerHealth) turnChoice()
To make the code edit the variables you need to use globals. When you call the variable with the parentheses in the function they are only edited in the scope of that variable, but when you use globals they get edited for the whole program. Here is an example. Below is the code that is using globals: import random import time import sys enemyHealth = 10 playerHealth = 10 def playerAttack(): global enemyHealth attack_damage = random.randint(1, 10) print("The player does " + str(attack_damage) + " damage points to the enemy.") enemyHealth -= attack_damage print("The enemy has " + str(enemyHealth) + " HP left!") enemyHealthCheck() pass def enemyAttack(): global playerHealth attack_damage = random.randint(1, 10) print("The enemy does " + str(attack_damage) + " damage points to the player.") playerHealth -= attack_damage print("The player has " + str(playerHealth) + " HP left!") playerHealthCheck() pass def turnChoice(): h = 1 t = 2 coin = "" while coin != "h" and coin != "t": coin = input("Player, flip a coin to decide who attack first.\n" "Heads or tails? H for heads. T for tails.\n") if coin == "h": print("You chose heads.\n" "Flip the coin. \n" ". . .") time.sleep(2) else: print("You chose tails.\n" "Flip the coin. \n" ". . .") time.sleep(2) choice = random.randint(1, 2) if choice == coin: print("Great choice. You go first.") playerAttack() else: print("Enemy goes first.") enemyAttack() def replay(): playAgain = "" while playAgain != "y" and playAgain != "n": playAgain = input("Do you want to play again? yes or no") if playAgain == "y": print("You chose to play again.") print(".") print(".") print(".") time.sleep(2) turnChoice() else: print("Game over. See you soon.") sys.exit() def playerHealthCheck(): global playerHealth if playerHealth <= 0: print("Player is dead. Game over.") replay() else: print("The player has " + str(playerHealth) + " HP points!") print("It is your turn to attack.") playerAttack() def enemyHealthCheck(): global enemyHealth if enemyHealth <= 0: print("Enemy is dead. You win.") replay() else: print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.") print("It is their turn to attack.") enemyAttack() turnChoice()
Run-time error when setting the value of a variable in Python
I want to make an RPG game, and I'm trying to make a system of buying items and potions. What I intended was for the player to get 3 potions of each in the beginning, but you need to buy more to continue with them. My problem is that they keep on resetting every time I call the fight function. I've tried making them global in the beginning and defining them, but they keep on saying "Referenced before assignment" def Fight(monster): global HealPotionsLeft global WeakPotionsLeft HealPotionsLeft = 3 WeakPotionsLeft = 3 Potion = ['Yes', 'No'] currentFighter = "" if myPlayer.dexterity >= monster.dexterity: currentFighter = myPlayer.name else: currentFighter = monster.name while myPlayer.isDead is not True and monster.isDead is not True: print(currentFighter + "'s turn!") print("===========================") print("Name:", myPlayer.name) print("Health:", myPlayer.health, "/", myPlayer.maxHealth) print("===========================") print("Name:", monster.name) print("Health:", monster.health, "/", monster.maxHealth) print("===========================") if currentFighter == monster.name: monster.Attack(myPlayer) currentFighter = myPlayer.name continue userInput = "" validInput = False while validInput is not True: print("-Attack") print("-Spells") print("-Items") print("-Flee") userInput = input() if userInput == "Attack": myPlayer.Attack(monster) break if userInput == "Spells": print("TO DO - Spells") if userInput == "Items": secure_random = random.SystemRandom() item = secure_random.choice(Potion) if item == ('Yes'): print("You have", HealPotionsLeft, "Potions of Healing Left and", WeakPotionsLeft, "Potions of Damage Left.") PotionUsage = input("Would you like to use your *Potion of Healing*? y/n") if PotionUsage == str("n"): if HealPotionsLeft == 0: print("You spent too much time trying to get the healing potion so you got attacked! *Out of Healing Potions*.") break elif HealPotionsLeft > 0: if PotionUsage == ("y"): myPlayer.health = 100 print(myPlayer.name, "Healed to 100 HP!") HealPotionsLeft = HealPotionsLeft - 1 PotionsLeft() break if PotionUsage == str("y"): if WeakPotionsLeft == 0: print("You spent too much time trying to get the Potion of Damage so you got attacked! *Out of Potions of Damage*.") break elif WeakPotionsLeft > 0: weakPotion = input("Would you like to use your Potion of Damage? y/n") if weakPotion == str("y"): monster.health = monster.health - 20 print(myPlayer.name, "Used their Potion of Damage on" , monster.name, "for 20 damage!") WeakPotionsLeft = WeakPotionsLeft - 1 PotionsLeft() break if item == ('No'): print("You didn't get to your potions in time!") break I expect the potions to go to three when the player goes into battle in the first time, but afterwards when going to battle the amount of potions resets the the amount remaining from last battle.
Outside this Fight() function initialize your potion counts to 3 each. Then pass the current amount of potions in to the Fight() function something like: Fight(monster,Hpots,Wpots) then return the remaining potions to the outer scope with a return(HealPotionsLeft,WeakPotionsLeft) ********* Example Requested: ********* I can not test this code and this is just an example BattleResults = [] global CurrentHealPotions global CurrentWeakPotions CurrentHealPotions = 3 CurrentWeakPotions = 3 def Fight(monster,HealPotionsLeft,WeakPotionsLeft): Potion = ['Yes', 'No'] currentFighter = "" if myPlayer.dexterity >= monster.dexterity: currentFighter = myPlayer.name else: currentFighter = monster.name while myPlayer.isDead is not True and monster.isDead is not True: print(currentFighter + "'s turn!") print("===========================") print("Name:", myPlayer.name) print("Health:", myPlayer.health, "/", myPlayer.maxHealth) print("===========================") print("Name:", monster.name) print("Health:", monster.health, "/", monster.maxHealth) print("===========================") if currentFighter == monster.name: monster.Attack(myPlayer) currentFighter = myPlayer.name continue userInput = "" validInput = False while validInput is not True: print("-Attack") print("-Spells") print("-Items") print("-Flee") userInput = input() if userInput == "Attack": myPlayer.Attack(monster) break if userInput == "Spells": print("TO DO - Spells") if userInput == "Items": secure_random = random.SystemRandom() item = secure_random.choice(Potion) if item == ('Yes'): print("You have", HealPotionsLeft, "Potions of Healing Left and", WeakPotionsLeft, "Potions of Damage Left.") PotionUsage = input("Would you like to use your *Potion of Healing*? y/n") if PotionUsage == str("n"): if HealPotionsLeft == 0: print("You spent too much time trying to get the healing potion so you got attacked! *Out of Healing Potions*.") break elif HealPotionsLeft > 0: if PotionUsage == ("y"): myPlayer.health = 100 print(myPlayer.name, "Healed to 100 HP!") HealPotionsLeft = HealPotionsLeft - 1 PotionsLeft() break if PotionUsage == str("y"): if WeakPotionsLeft == 0: print("You spent too much time trying to get the Potion of Damage so you got attacked! *Out of Potions of Damage*.") break elif WeakPotionsLeft > 0: weakPotion = input("Would you like to use your Potion of Damage? y/n") if weakPotion == str("y"): monster.health = monster.health - 20 print(myPlayer.name, "Used their Potion of Damage on" , monster.name, "for 20 damage!") WeakPotionsLeft = WeakPotionsLeft - 1 PotionsLeft() break if item == ('No'): print("You didn't get to your potions in time!") break if myPlayer.isDead is True result="You have been defeated!" else result="You have slain the Beast!" BattleEnd=[result, HealPotionsLeft, WeakPotionsLeft] return(BattleEnd) A call to this function might look like: BattleResults = Fight("Your Monster Reference Here",CurrentHealPotions,CurrentWeakPotions) Then assign the new values to potions: CurrentHealPotions = BattleResults[1] CurrentWeakPotions = BattleResults[2]
How come my ork fight stops and doesn't go to the move() command :/
At some parts of my code its just stop and doesn't go back to the move(). I want it to add the score and i did that with score = score + 100 BUT it just disrupts the code ;-;. Its a bit messy and i'm sorry about that but please help I have NO clue why it does this. Fyi I'm using this code on pythonroom if that helps. import random weapon = "Wooden Sword" Damage0 = 1 Damage1 = 8 Speed = 6 lives = 5 score = 0 gold = 80 armor = "Nothing" health = 20 def please(): name = input("Please put a name and not nothing.") if name == "": please1(name) else: yon(name) def please1(name): name = input("Please put a name and not nothing.") if name == "": please1(name) else: yon1(name) def yon(name): print("So your name is " + name + "?") yon = input("Is this your name? ''" + name + "'' [Yes] or [No]?") if yon == "Yes": begining() elif yon == "yes": begining() else: sorry(name) def yon1(name): yon = input("Is this your +name? ''" + name + "'' [Yes] or [No]?") if yon == "Yes": begining() elif yon == "yes": begining() else: sorry1(name) def sorry(name): print(" ") print("I'm sorry, so what is your name?") print(" ") name = input("What is you name?") if name != "": yon(name) else: please1(name) def sorry1(name): name = input("What is you name?") if name != "": yon1(name) else: please1(name) def move(): Next = input("Will you go and fight a monster or check stats or quit the game? [Fight] [Stats] [Travel] [Quit]") Next = Next.lower() if "tat" in Next: Stats() elif "ight" in Next: Fight() elif "ravel" in Next: travel() elif "uit" in Next: print("As you quit the game your character disapears...") else: move() def Fight(): your_speed = Speed enemy_speed = 2 if enemy_speed >= your_speed: print("The " + enemy + " is faster, it goes first!") enemy_first() else: print("You're faster and get to go first!") your_first() def end(enemy_health,your_health): if your_health > 0: print(" ") print("You defeat the Ork") score = score + 100 gold = gold + 50 'it stops here and won't continue why? print(gold) print(score) move() else: print("The ork beat you!") move() def your_first(): enemy_health = 20 your_health = health while your_health > 0 and enemy_health > 0: your_damage = random.choice(range(Damage0, Damage1)) enemy_health -= your_damage if enemy_health <= 0: enemy_health = 0 print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy's health:" + str(enemy_health)) end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy's health:" + str(enemy_health)) enemy_damage = random.choice(range(3, 12)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("Ork dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) end(enemy_health,your_health) else: print(" ") print("Ork dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) def enemy_first(): enemy_health = 20 your_health = health while your_health > 0 and enemy_health > 0: enemy_damage = random.choice(range(3, 12)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("Ork dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) end(enemy_health,your_health) else: print(" ") print("Ork dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) your_damage = random.choice(range(Damage0, Damage1)) enemy_health -= your_damage if enemy_health <= 0: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy's health:" + str(enemy_health)) end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy's health:" + str(enemy_health)) def Stats(): if weapon == "Wooden Sword": Damage = 1, 8 Damage0 = 1 Damage1 = 8 Speed = 6 if weapon == "Rusty Sword": Damage = 13, 17 Damage0 = 13 Damage1 = 17 Speed = 4 if weapon == "Bow": Damage = 2, 13 Damage0 = 2 Damage1 = 13 Speed = 10 if weapon == "Bronze Sword": Damage = 18, 24 Damage0 = 18 Damage1 = 24 Speed = 1 if weapon == "Magic Spell": Damage = 25, 33 Damage0 = 25 Damage1 = 33 Speed = 10 if armor == "Nothing": health = 20 print(" ") print(" ") print("(+)~~~~~~~~~~~~~~~~~~~~~~") print(" | Your | Health: ") print(" | Stats | " + str(health) + " ") print(" |----------------------- ") print(" | Weapon Stats: ") print(" | Damage: "+str(Damage)+" ") print(" | Speed: "+str(Speed)+" ") print("(+)~~~~~~~~~~~~~~~~~~~~~~") print(" Your Score:"+ str(score) +" ") print(" ") print(" ") move() def begining(): print(" ") print("Welcome to the nexus!") print("It is the center of this world.") print("It is also called the hub.") print("During the game you can gather items and get xp") print("At the end of the game you can see your score based") print("on how well you did and how many items you found!") move() def travel(): travel = input("Where will you travel to? [Cave] [Market] [Boss]") if "ve" in travel: cave() elif "et" in travel: market() elif "ss" in travel: Boss_fight() else: move() def cave(): print("pie") def market(): print("pie") def Boss_fight(): your_speed = Speed enemy_speed = 2 if enemy_speed >= your_speed: print("The " + enemy + " is faster, it goes first!") Boss_Boss_first else: print("You're faster and get to go first!") Boss_Your_First() def Boss_end(enemy_health,your_health): if your_health > 0: print(" ") print("You defeat The Boss") score = score + 2000 move() else: print(" ") if lives == 3 or lives == 2 or lives == 1: print("The Boss beats you!") lives = lives - 1 print("You have " + str(lives) + " left") move() else: start= input("Restart or Quit?") if "start" in start or "try" in start: reset(xp,lvl,weapon) else: print(" ") def Boss_Your_First(): enemy_health = 50 your_health = health while your_health > 0 and enemy_health > 0: your_damage = random.choice(range(Damage0, Damage1)) enemy_health -= your_damage if enemy_health <= 0: enemy_health = 0 print(" ") print("You dealt " + str(your_damage) + " damage!") print("The Boss's health:" + str(enemy_health)) Boss_end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("The Boss's health:" + str(enemy_health)) enemy_damage = random.choice(range(15, 19)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("The Boss dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) Boss_end(enemy_health,your_health) else: print(" ") print("The Boss dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) def Boss_Boss_first(): enemy_health = 50 your_health = health while your_health > 0 and enemy_health > 0: enemy_damage = random.choice(range(15, 19)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("The Boss dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) Boss_end(enemy_health,your_health) else: print(" ") print("The Boss dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) your_damage = random.choice(range(Damage0, Damage1)) enemy_health -= your_damage if enemy_health <= 0: print(" ") print("You dealt " + str(your_damage) + " damage!") print("The Boss's health:" + str(enemy_health)) Boss_end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("The Boss's health:" + str(enemy_health)) print(" ") print("Hello. What is your name?") print(" ") name = input("What is you name?") if name == "": please() else: yon(name)
You're trying to assign to global variable score within function end like this: val = 5 def func(): val += 5 It won't work and will result to UnboundLocalError. In order to fix the issue just use keyword global: val = 5 def func(): global val val += 5