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

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 :)

Related

Python program keeps asking question again and again

I am a python intermediate and tried to make a text based adventure game in python. There is a class called NPC which has the NPCs. In that class there is a method called attack() which will attack the player and the player can also attack or defend. It is position based so the user can enter 3 things - 'high', 'middle' and 'low'. This is the code.
turn = True
while turn:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
possible_positions = ['high', 'middle', 'low']
attack_pos = random.choice(possible_positions)
while player_defend_pos not in [possible_positions] and player_defend_pos not in possible_actions:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
if player_defend_pos == 'm':
use_medkit()
elif player_defend_pos == 'help':
help()
elif player_defend_pos == 's':
shop()
elif player_defend_pos != attack_pos:
if equipped_armour == False:
print(f'You don\'t have any armour equipped so the {self.name} will do {self.damage} damage to you.')
player['health'] -= self.damage
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif equipped_armour == True and shop_items[1][player['armours'][0] + ' protection'] > self.damage:
print(f'Since you have {[player["armours"][0]]} equipped it will not do anything.')
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif equipped_armour == True and shop_items[1][player['armours'][0] + ' protection'] < self.damage:
player['health'] -= self.damage - shop_items[1][player['armours'][0] + ' protection']
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print('You have successfully defended the attack')
turn = False
break
This is the defend code there is a similar thing in attacking the NPC also which has the same output. Now even if I enter 'high', 'middle' or 'low' It asks the question again and again. Please show me some guidance.
I have found the answer. Actually I should have told that equipped_armour is actually a function. Sorry about that. I actually wanted the return value of equipped_armour() without running everything in it. So I searched my question on stackoverflow. Even that didn't work. So I searched for the global keyword, used it and then got the answer. Maybe your answers were right if equipped_armour was a variable. Anyways thank you all for trying.
I think your problem is in
# this will produce always true
while player_defend_pos not in [possible_positions]
it should be
while player_defend_pos not in possible_positions
I hope my answer help your problem
import random
possible_actions = ['m', 'help', 's']
turn = True
equipped_armour = True
def use_medkit():
print('Medkit!')
def shop():
print('Shop!')
while turn:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
possible_positions = ['high', 'middle', 'low']
attack_pos = random.choice(possible_positions)
while player_defend_pos not in possible_positions and player_defend_pos not in possible_actions:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
print(player_defend_pos)
if player_defend_pos == 'm':
use_medkit()
elif player_defend_pos == 'help':
help()
elif player_defend_pos == 's':
shop()
elif player_defend_pos != attack_pos:
turn = False
else:
print('You have successfully defended the attack')
turn = False
break
Try something simple and then make it complex. The code above works for example.

Opponents health not decreasing, and turns not flipping over [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 4 years ago.
Improve this question
So, for the main action sequence of my game, I have this code for the battle. It works, sort of. I can choose the moves and all the text will display, but it doesn't take health off of the opponent, and the turn doesn't change over. I can't for the life of me figure out what I've done wrong. Here is the code:
I'm using python 2.7.
play_again = True
while play_again is True:
winner = None
player_health = 100
computer_health = random.randrange(1,200)
player_turn = True
computer_turn = False
while (player_health != 0 or computer_health != 0):
heal_up = False
miss = False
moves = {"Punch": random.randint(18, 25),
"Slap": random.randint(10, 35),
"Kick": random.randint(10, 25)}
if player_turn is True:
print("""1. Punch
2. Slap
3. Kick
""")
player_move = raw_input(">>> ")
move_miss = random.randint(1,10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
player_move = 0
print("You missed!")
else:
if player_move in ("1", "punch"):
player_move = moves["Punch"]
print("You used Punch! It dealt %s damage!") % player_move
elif player_move in ("2", "slap"):
player_move = moves["Slap"]
print("\nYou used Slap!. It dealt %s damage.") % player_move
elif player_move in ("3", "kick"):
player_move = moves["Kick"]
print("\nYou used Kick! It dealt %s damage.") % player_move
else:
print("\nThat is not a valid move. Please try again.")
else:
move_miss = random.randint(0, 10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
computer_move = 0
print('The Opponent Missed!')
else:
imoves = ["Punch", "Slap","Kick"]
imoves = random.choice(imoves)
CPU_move = moves[imoves]
if CPU_move == moves["Punch"]:
print("The opponent used Punch. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Slap"]:
print("\nThe opponent used Slap. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Kick"]:
print("\nThe opponent used Kick. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if player_turn is true:
computer_health -= player_move
if computer_health <= 0:
computer_health = 0
winner = "Player"
break
else:
if player_health <= 0:
player_health = 0
winner = "Computer"
break
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
# switch turns
player_turn = not player_turn
computer_turn = not computer_turn
if winner == "Player":
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print('Congratulations! You have won.')
else:
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print("Sorry, but your opponent wiped the floor with you. Better luck next time.")
Your entire code that deals with decreasing the opponent's health and flipping the turns are improperly indented to be inside the outer loop (which checks if the player wants to play again) instead of the inner loop (which is the main loop that actually plays each turn).
Simply indent that code with two more spaces, and fix your typo of True in if player_turn is true: (the first letter of True has to be capitalized), and your code would work:
import random
play_again = True
while play_again is True:
winner = None
player_health = 100
computer_health = random.randrange(1,200)
player_turn = True
computer_turn = False
while (player_health != 0 or computer_health != 0):
heal_up = False
miss = False
moves = {"Punch": random.randint(18, 25),
"Slap": random.randint(10, 35),
"Kick": random.randint(10, 25)}
if player_turn is True:
print("""1. Punch
2. Slap
3. Kick""")
player_move = raw_input(">>> ")
move_miss = random.randint(1,10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
player_move = 0
print("You missed!")
else:
if player_move in ("1", "punch"):
player_move = moves["Punch"]
print("You used Punch! It dealt %s damage!") % player_move
elif player_move in ("2", "slap"):
player_move = moves["Slap"]
print("\nYou used Slap!. It dealt %s damage.") % player_move
elif player_move in ("3", "kick"):
player_move = moves["Kick"]
print("\nYou used Kick! It dealt %s damage.") % player_move
else:
print("\nThat is not a valid move. Please try again.")
else:
move_miss = random.randint(0, 10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
computer_move = 0
print('The Opponent Missed!')
else:
imoves = ["Punch", "Slap","Kick"]
imoves = random.choice(imoves)
CPU_move = moves[imoves]
if CPU_move == moves["Punch"]:
print("The opponent used Punch. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Slap"]:
print("\nThe opponent used Slap. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Kick"]:
print("\nThe opponent used Kick. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if player_turn is True:
computer_health -= player_move
if computer_health <= 0:
computer_health = 0
winner = "Player"
break
else:
if player_health <= 0:
player_health = 0
winner = "Computer"
break
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
# switch turns
player_turn = not player_turn
computer_turn = not computer_turn
if winner == "Player":
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print('Congratulations! You have won.')
else:
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print("Sorry, but your opponent wiped the floor with you. Better luck next time.")
Here's a sample output with the fix:
1. Punch
2. Slap
3. Kick
>>> 2
You used Slap!. It dealt 34 damage.
Your health: 100, Opponents health: 59
The opponent used Slap. It dealt 31 Damage.
Your health: 69, Opponents health: 59
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 21 damage!
Your health: 69, Opponents health: 38
The Opponent Missed!
Your health: 69, Opponents health: 38
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 19 damage!
Your health: 69, Opponents health: 19
The opponent used Kick. It dealt 19 Damage.
Your health: 50, Opponents health: 19
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 22 damage!
Your health: 50, Opponents health: 0
Congratulations! You have won.
1. Punch
2. Slap
3. Kick
>>>

use of global, but still not recognized in Python function

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.

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

Python text RPG error [closed]

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

Categories