use of global, but still not recognized in Python function - python

I was making a game where you need to fight monsters, just to practice my coding, when I got an error I couldn't understand. Here is the code, and the error I received:
Note: I changed it to the full code so you could see everything. Sorry about how long it is.
import random
import time
player_level = 1
player_HP = 4
player_mana = 2
player_action = "Placeholder"
entity_list = ["Nymph", "Komodo", "Free Soul"]
current_monster_level = player_level
current_monster_HP = random.randrange(current_monster_level, (current_monster_level * 3) + 1)
monster_name = entity_list[random.randrange(0, 3)]
def spawn_monster(level):
import random
global current_monster_HP
global monster_name
current_monster_HP = random.randrange(level, level * 3)
monster_name = entity_list[random.randrange(0, 3)]
print("A ", monster_name, "attacks you!")
print("The ", monster_name, " has ", current_monster_HP, " HP!")
def attack(level):
import random
global monster_name
global current_monster_HP
damage = random.randrange(level, level + 4)
current_monster_HP = current_monster_HP - damage
if damage == 0:
print("You missed! No damage done! ", monster_name, "'s HP is ", current_monster_HP, " !")
elif damage > current_monster_HP:
damage = current_monster_HP
print("You did ", damage, " damage! The ", monster_name, " was defeated!")
else:
print("You did ", damage, " damage. The enemy's HP is now ", current_monster_HP, "!")
def spell(level):
global player_mana
global player_HP
player_mana = player_mana - 2
player_HP = player_HP + level
print("A spell is cast, and you gain ", level, "HP!")
def monster_retaliate(level):
import random
global player_HP
global monster_name
global current_monster_HP
damage = random.randrange(level, level + 2)
player_HP = player_HP - damage
print("The ", monster_name, " attacked you, dealing ", damage, " damage!")
if damage == 0:
print("The enemy missed! No damage done! Your HP is ", player_HP, "!")
elif damage > current_monster_HP:
damage = current_monster_HP
else:
print("the ", monster_name, " did ", damage, " damage. Your HP is now ", player_HP, "!")
print("xxxxxxxxxxxxx")
print("xxxxxxxxxxxxx")
print("x Blind RPG x")
print("xxxxxxxxxxxxx")
print("xxxxxxxxxxxxx")
print("\n")
begin = input("Start a new game?").lower()
if begin == "yes":
print("Your tale starts when your memory does. You can't remember anything!")
time.sleep(1)
print("You wake up in an empty field, and you think you see a shadowy figure.")
time.sleep(1)
print("It slips away into the faraway trees lining the grassy field, or does it?")
time.sleep(1)
print("You stand up.")
time.sleep(1)
print("You decide to go over to where the shadow left the field.")
time.sleep(1)
print("On the ground, you see a small sword. You pick it up.")
time.sleep(1)
print("Suddenly, something jumps out at you from behind a tree.")
time.sleep(1)
spawn_monster(1)
while current_monster_HP > 0:
player_action = input("What do you do?").lower()
if player_action == "attack":
attack(player_level)
time.sleep(2)
if current_monster_HP > 0:
monster_retaliate(1)
else:
break
elif player_action == "cast spell":
spell(player_level)
time.sleep(2)
monster_retaliate(1)
else:
print("The enemy attacked you as you stood unmoving!")
monster_retaliate(1)
if current_monster_HP <= 0:
print("You win! Apparently you remember how to fight!")
break
if player_HP <= 0:
print("You died! If only you had remembered how to fight...")
break
else:
print("Then why did you open the game?")
The attack() function works, and the spell() function both work, it is only the monster_retaliate() function that is causing trouble. The Error code is:
File "/Users/(Replacing my name for privacy)/Documents/Blind RPG.py", line 57, in monster_retaliate
player_HP = player_HP - damage
NameError: name 'player_HP' is not defined
I thought this was funny, seeing as I used the global keyword

global doesn't actually create a variable; it just indicates that the name should be defined in the global scope, and to modify that (instead of a local variable) when you assign to it. You still need to give it a value before you try to access it.

Related

Python function doesn't update value of variable

def Act(enemy, pokemon, enemyHP, enemyType):
num = round(random.uniform(0.95, 1.75), 2)
print(MoveList)
Move1 = input("Choose your attack! Input a number from 1-4, depending on the order of your moves. Input 5 to view everyone's stats! \n")
if Move1 == "1":
Move1 = str(MoveList[0])
attacked = True
dmg = 10 * num
Move1 = MoveList[0]
print(pokemon + " used " + Move1 + "! \n")
enemyHP -= dmg
print("It dealt " + str(dmg) + " damage to " + enemy + "! \n")
print(enemy + " is now at " + str(enemyHP) + " HP!")
return enemyHP
while battling == true:
Act(RivalPKMN, starter, RivalHP, RivalType)
This function takes an input from the player, does a move, and deducts HP from the function parameter enemyHP (similar to Pokemon). However, after doing an input again, the enemyHP value does not update to what it was after the first move.
I tried using return statements but I'm not really sure what or where the problem even is.
Here's an example of how it looks:
Litten used Scratch!
It dealt 10.5 damage to Quaxly!
Quaxly's HP is now 44.5!
The second time I run the function it inputs the exact same thing without updating the HP value to what it was after the first move was done.
This is a simple beginner mistake. just add global [variable name] at the start of the function and it should work.

How do I make my code loop the function fight() [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Asking the user for input until they give a valid response
(22 answers)
Repeating a function in Python
(2 answers)
Closed 8 months ago.
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
Below is the function I want to loop when userhealth and dragonhealth <= 0. I want it to keep asking for input for rock, paper, or scissors and go through the conditions.
def fight(userhealth,dragonhealth):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Do you want this ?
import random
user = input("You recognize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
def fight(userhealth,dragonhealth):
while(userhealth>0 and dragonhealth>0):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Try the following code:
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
dragonhealth = 100
userhealth = 100
def fight(userhealth,dragonhealth,choice):
dragon = random.choice(["r","p","s"])
print(dragon)
if choice==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(choice,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
return userhealth,dragonhealth
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
while (userhealth>0 or dragonhealth>0):
choice=input("Rock(r), Paper(p) or Scissors(s): ").lower()
userhealth,dragonhealth = fight(userhealth,dragonhealth,choice)
if userhealth>0:
print("You won! ")
elif dragonhealth>0:
print("You lost! ")
Explanation: Sets the original healths at the start. Sets up a while loop to check if either of them have less than 0 health. Subtracts and updates the health when you lose/win. Declares a winner at the end!
Use While loop for repeating the game util someone gets 0 HP.
I created a function to terminate the game when someone is at 0 HP. See it
enter code here
import random
user_health = 100 # used underscore snake case love:)
dragon_health = 100 # I initialized both variables outside
def fight(user_health, dragon_health): # according to PEP8 I guess. we shouldn't use shadow names. Still,not a big deal
dragon = random.choice(["r", "p", "s"])
user = input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user == dragon:
print("You both missed your attacks. Bruh ;-;")
return user_health, dragon_health
elif is_win(user, dragon):
dragon_health -= 20
print("You hit BaLaKe! 20 DMG Done!!! :) ") #
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
user_health -= 20
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
def is_win(player, opponent):
if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") or (
player == "p" and opponent == "r"):
return True
# this function terminates game when someone is at 0 HP and prints output
def game_terminator(user_health, dragon_health): # I continued with the shadow names to avoid confusion
if user_health == 0:
print("Dragon killed you!")
return False
elif dragon_health == 0:
print("Thrashed dragon to dealth! YOU WON!") # Nerd outputs :)
return False
else:
return True
game_is_on = True
# Use while loop for game to run until someone gets 0 HP
while game_is_on: # game_is_on is a boolean variable
user_health, dragon_health = fight(user_health, dragon_health)
game_is_on = game_terminator(user_health, dragon_health)
# Thank Me :)

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

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]()

List Index Is Out of Range And I Don't Know Why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So this is the error:
Traceback (most recent call last):
File "E:\python\cloud.py", line 593, in <module>
inventory()
File "E:\python\cloud.py", line 297, in inventory
print("Weapon Attack Damage: ", c.weaponAttack[i])
IndexError: list index out of range
These are the only parts of the code that have the "weaponAttack" function in it. I honestly don't see why it is giving me this error.
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.sp = 0
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.money = 0
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
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"]
weaponAttack = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weapon.append(weaponAttack[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttack[w]," attack power!")
print("")
for i in range(0, len(c.weapon)):
print(i)
print("Weapon: ", c.weapon[i])
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
Although, this is the rest of the code, but before you read it, I'm warning you, it's long. Either way, I'm pretty sure that those lines of code up there are the problem.
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(.02)
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.sp = 0
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.money = 0
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
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"]
weaponAttack = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weapon.append(weaponAttack[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttack[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.weaponAttack[0]) * (.5))
s.hp = s.hp - (c.weaponAttack[0] + crithit)
elif crit >= 1:
s.hp = s.hp - c.weaponAttack[0]
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("Level: ", c.lvl)
nextlvl = c.lvl + 1
print("Experience: ", c.exp, "/", c.mexp, "level", nextlvl)
print("Amount of Skill Points:", c.sp)
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("Maximum Health: ", c.mhp)
print("Current Health: ", c.hp)
print("Your Name: ", c.name)
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: ")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
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 defeat an enemy, 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("")
inventory()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
else:
print("Level: ", c.lvl)
nextlvl = c.lvl + 1
print("Experience: ", c.exp, "/", c.mexp, "level", nextlvl)
print("Amount of Skill Points:", c.sp)
for i in range(0, len(c.weapon)):
print("Weapon:", c.weapon[i])
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for i in range(0, len(c.armor)):
print("Armor: ", c.armor[i])
print("Armor Damage Reduction: ", c.armorReduction[i])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("Maximum Health: ", c.mhp)
print("Current Health: ", c.hp)
print("Attack Power: ", c.attackPower)
print("Your Name: ", c.name)
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: ")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
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 defeat an enemy, 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("")
inventory()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
def skills():
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.")
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*")
if "yes" in sure:
c.sp = c.sp - 1
addsap = c.attackPower * .01
c.attackPower = c.attackPower + addsap
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*")
if "yes" in sure:
c.sp = c.sp - 1
c.mhp = c.mhp + 30
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("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("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. ")
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("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*")
ask3 = input("Enter desired number here, or say, cancel, to go back to the main shop screen. ")
if "1" in ask3:
Type("That's the name of this town.")
murlor()
elif "2" in ask3:
def askquest1():
quest1 = input("Well I DO know that there's this secret underground dungeon. It's VERY dangerous but it comes with a hug reward. If you ever concider 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.*")
if "yes" in quest1:
quest1()
elif "no" in quest1:
murlor()
else:
Type("The option you have selected is not valid. Please try again")
print("")
askquest1()
elif "3" in ask3:
shop()
else:
Type("The number or word you have entered is invalid. please try again.")
print("")
elif "2" in ask1:
def heal():
Type("Sure! That'll be 30 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase*")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
heal()
elif "3" in ask1:
def swords():
print("Swords: ")
print("The Belice Sword: *Type 1 for this sword*")
print("Damage: 18")
print("Cost: 70 crystals")
print("")
print("The Sword of A Thousand Truths: *Type 2 for this sword*")
print("Damage: 28")
print("Cost: 100 crystals")
print("")
print("Spyro's Sword: *Type 3 for this sword*")
print("Damage: 32")
print("Cost: 125 crystals")
print("")
print("The Sword Of The Athens: *Type 4 for this sword*")
print("Damage: 36")
print("Cost: 150 crystals")
print("")
print("Coming Soon...")
sword = input("Enter the sword ID number or say cancel to go back to the main shop screen. You now have ", c.money, "crystals.")
if "1" in sword:
if c.money < 70:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
swords()
elif c.money >= 70:
c.money = c.money - 70
Type("70 crystals has been removed from your inventory.")
print("")
weapon.append("The Belice Sword")
Type("The Belice Sword has been added to your inventory!")
print("")
swords()
elif "2" in sword:
if c.money < 250:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
swords()
elif c.money >= 250:
c.money = c.money - 250
Type("250 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("The Sword Of A Thousand Truths")
Type("The Sword Of A Thousand Truths has been added to your inventory!")
print("")
swords()
elif "3" in sword:
if c.money < 525:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
swords()
elif c.money >= 525:
c.money = c.money - 525
Type("525 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("The Spyro's Sword")
Type("The Spyro's Sword has been added to your inventory!")
print("")
swords()
elif "4" in sword:
if c.money < 1050:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
swords()
elif c.money >= 1050:
c.money = c.money - 1050
Type("1050 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("The Sword Of The Athens")
Type("The Sword Of The Athens has been added to your inventory!")
print("")
swords()
elif "cancel" in sword:
shop()
else:
Type("The number or word you have entered is invalid. Please try again.")
print("")
swords()
elif "4" in ask1:
def armory():
print("Armor:")
print("Belice Armor, ID: 1")
print("Damage Reduction: 2.5%")
print("Cost: 100 crystals")
print("")
print("Yoron's armor, ID: 2")
print("Damage Reduction: 5%")
print("Cost: 250 crystals")
print("")
print("Andrew's Custom Armor, ID: 3")
print("Damage Reduction: 10%")
print("Cost: 500 crystals")
print("")
print("Zeus' Armor, ID: 4")
print("Damage Reduction: 15%")
print("Cost: 1000 crystals")
print("")
print("Coming Soon...")
print("")
armor = input("Enter armor ID number, or type, cancel, to go back to the main shop menu.")
if "1" in armor:
if c.money < 100:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
armory()
elif c.money >= 100:
c.money = c.money - 100
Type("100 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("Belice Armor")
Type("Belice Armor has been added to your inventory!")
print("")
armory()
elif "2" in armor:
if c.money < 250:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
armory()
elif c.money >= 250:
c.money = c.money - 250
Type("250 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("Yoron's Armor")
Type("Yoron's Armor has been added to your inventory!")
print("")
armory()
elif "3" in armor:
if c.money < 500:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
armory()
elif c.money >= 500:
c.money = c.money - 500
Type("500 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("Andrew's Custom Armor")
Type("Andrew's Custom Armor has been added to your inventory!")
print("")
armory()
elif "4" in armor:
if c.money < 1000:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
armory()
elif c.money >= 1000:
c.money = c.money - 1000
Type("1000 crystals has been removed from your inventory. You now have ", c.money, "crystals.")
print("")
weapon.append("Zeus' Armor")
Type("Zeus' Armor has been added to your inventory!")
print("")
armory()
elif "cancel" in armor:
shop()
else:
Type("The word or number you have entered is invalid. Please try again")
armory()
elif "cancel" in ask1:
inventory()
else:
Type("The number or word you have entered is invalid. Please try again.")
print("")
shop()
inventory()
I think your problem is here:
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"]
weaponAttack = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weapon.append(weaponAttack[w])
That last line should probably be:
c.weaponAttack.append(weaponAttack[w])

Categories