calling a function in Python? - python

I don't know how to call the functions below I listed a box with what I want to do but don't know how to.
import random
import time
startingP_health = 30
startingE_health = 30
def player_attack():
global startingE_health
time.sleep(1)
print ("What ability would you like to use? (free speach(fs), capatalism(c), or punch(p)")
ability_choice = input()
if(ability_choice == "fs"):
enemy_health = startingE_health-3
enemy_heath = int(enemy_health)
elif(ability_choice == "c"):
enemy_health = startingE_health-(random.randint(1,6))
enemy_heath = int(enemy_health)
elif(ability_choice == "p"):
enemy_health = startingE_health-(random.randint(2,4))
enemy_heath = int(enemy_health)
else:
print("you fell.")
time.sleep(1)
print ("Enemie's health is now: ",enemy_health)
print("")
return int(enemy_health)
def enemy_attack():
global startingP_health
time.sleep(1)
print ("Enemy kicks you")
print("")
player_health = startingP_health - (random.randint(1,3)
player_health = int(player_health)
time.sleep(1)
print ("Your health is now ",player_health)
print ("")
return int(player_health)
def battle_trotsky():
global player_health
print ("Enemy appears")
print ("")
time.sleep(1)
while player_health > 0 and enemy_health > 0:
##############################
#call function player_attack
#call enemy_attack
##############################
if player_health <=0:
break
if enemy_health <= 0:
time.sleep(1)
print ("You have killed the enemy")
if player_health <= 0:
print("Sorry you failed the mission you must restart the mission"))
################################
#initate function sequence
################################

import random
import time
You need to declare enemy_health and player_health as globals so they persist:
startingP_health = 30
startingE_health = 30
enemy_health = startingE_health
player_health = startingP_health
This function doesn't have to return anything, since you declare global enemy_health and then assign it the new value:
def player_attack():
global enemy_health
time.sleep(1)
print ("What ability would you like to use? (free speech(fs), capitalism(c), or punch(p)")
ability_choice = input()
This wasn't working because you were doing enemy_health = starting health - 3, which means every round it would start again from the starting health. Instead here, -= is subtract from the current value: enemy_health = enemy_health - 3:
if(ability_choice == "fs"):
enemy_health -= 3
elif(ability_choice == "c"):
enemy_health -= random.randint(1,6)
elif(ability_choice == "p"):
enemy_health -= random.randint(2,4)
else:
print("you fell.")
time.sleep(1)
print ("Enemy's health is now: ",enemy_health)
print("")
def enemy_attack():
global player_health
time.sleep(1)
print ("Enemy kicks you")
print ("")
player_health -= random.randint(1,3)
time.sleep(1)
print ("Your health is now ",player_health)
print ("")
def battle_trotsky():
global player_health
global enemy_health
print ("Enemy appears")
print ("")
time.sleep(1)
while player_health > 0 and enemy_health > 0:
Functions are called via name(), as seen:
player_attack()
enemy_attack()
if enemy_health <= 0:
time.sleep(1)
print ("You have killed the enemy")
if player_health <= 0:
print("Sorry you failed the mission you must restart the mission")
battle_trotsky()

This is a not a good question for this site as it is not specific, but I feel compelled to fixed this code by a deep power. I'm not sure why you're doing the sleeps, the print("") statements can be replaced with a '\n' in the previous prints, and you are continuously reassigning player health to the starting health - number, which will never reach 0, so you must make the healths global.
Here's a working example
import random
player_health = 30
enemy_health = 30
def player_attack():
global enemy_health
ability_choice = input("What ability would you like to use? (free speach(fs), capatalism(c), or punch(p)")
if(ability_choice == "fs"):
enemy_health -= 3
elif(ability_choice == "c"):
enemy_health -= random.randint(1,6)
elif(ability_choice == "p"):
enemy_health -= random.randint(2,4)
else:
print("you fell.")
print ("Enemy's health is now: "+str(enemy_health)+'\n')
def enemy_attack():
global player_health
print ("Enemy kicks you")
player_health -= random.randint(1,3)
print ("Your health is now "+str(player_health)+"\n")
def battle_trotsky():
print ("Enemy appears\n")
while player_health > 0 and enemy_health > 0:
player_attack()
if check_game_over():
return
enemy_attack()
if check_game_over():
return
def check_game_over():
global player_health, enemy_health
if enemy_health <= 0:
print ("You have killed the enemy\n")
return True
elif player_health <= 0:
print("Sorry you failed the mission you must restart the mission")
return True
else:
return False
if __name__=='__main__':
battle_trotsky()

Related

Doesn't run IF statement even though condition is true, but loops other IF

import random
player_health = 100
boss_health = 80
guard1_health = 10
guard1_status = "alive"
guard2_health = 15
gladiator_health = 20
weapon = 0
level = 0
turn = 0
def choose_weapon():
global weapon
global level
weapon = int(input("Choose your weapon:\n 1: Sword \n 2: Daggers \n 3: Bow \n Type here to choose:"
"\n--------------------------"))
if weapon == 1:
weapon = str("Sword")
print("You have chosen", weapon)
elif weapon == 2:
weapon = str("Daggers")
print("You have chosen", weapon)
else:
weapon = str("Bow")
print("You have chosen", weapon)
level += 1
choose_weapon()
def level_1_enemy():
global guard1_status
global guard1_health
global level
global turn
global weapon
print("Player turn")
if guard1_status == "alive" and guard1_health > 0 and turn == 1:
print("test")
if weapon == 1:
guard1_health -= 8
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 2:
guard1_health -= 5
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 3:
bow_crit = random.randint(1, 10)
if bow_crit == 1:
guard1_health -= 20
print("Guard health:", guard1_health)
else:
guard1_health -= 5
print("Guard health:", guard1_health)
if guard1_health <= 0:
print("You defeated the Guard, next level!")
guard1_status = "dead"
level += 1
return
def level_1_player():
global player_health
global weapon
global level
global turn
if player_health > 0 and turn == 0:
if weapon == 2:
dodge = random.randint(1, 3)
if dodge == 1:
print("You dodged the attack!")
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
print("You have died, Game Over.")
return
while level == 1:
if turn == 0:
level_1_player()
turn += 1
elif turn == 1:
level_1_enemy()
turn -= 1
I want to have the game loop through player and enemy turns until either the player is dead or the enemy. It reaches the first IF in level_1_enemy and prints "test", but does not continue to the next if statement even though the condition "weapon == 1" is true.
The last while loop is meant to repeat the level_1_enemy and level_1_player functions. It does do both but will also not stop looping once the guard or player is dead.

how can I subtract the amount Randint generates in the while loop from enemies HP without getting 2 different numbers?

If you run the code you should see that the print says "14" for example, but It retracts something else from enemies HP.
Calculating attack damage for each "spell":
from random import randint
import time
class Player(object):
def __init__(self, health):
self.health = health
#staticmethod
def use_heal():
return randint(9, 21)
#staticmethod
def attack_slice():
return randint(5, 29)
#staticmethod
def attack_bash():
return randint(11, 18)
class Enemy(object):
def __init__(self, health):
self.health = health
#staticmethod
def enemy_attack():
return randint(9, 19)
For setting HP:
player = Player(100)
enemy = Enemy(100)
The loop that is the "game":
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
print(f"You hit for {Player.attack_bash()}")
enemy.health -= Player.attack_bash()
elif attack_choice == 2:
print(f"You hit for {Player.attack_slice()}")
enemy.health -= Player.attack_slice()
elif attack_choice == 3:
print(f"You heal for {Player.use_heal()}")
player.health += Player.use_heal()
when it calls Player.attack_* it returns a random value to print, and then calls it a second time to actualy damage the enemy so it is likely a defarent value. what it should do is call it once, store it in a variable and use the variable
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 2:
damage = Player.attack_slice()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 3:
damage = Player.use_heal()
print(f"You heal for {damage}")
player.health += damage
The problem is you are generating two random numbers for each case: The one that gets print and the one that gets subtracted/added.
...
print(f"You hit for {Player.attack_bash()}") # Generates a random number
enemy.health -= Player.attack_bash() # Generates another random number
...
You need to use a temporary variable so you can use the same value twice:
...
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
...

Why does my program exit unexpectedly when I call input?

I'm trying to get this RPG program to work, but I can't figure it out. I run it and well, you will see when you run the program. For some reason when I run this it stops at 1,2,3,4 after every move I make. Am I not returning anything? What am I doing wrong here, and how can I improve my organization and code in the future?
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == input('1'):
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == input('2'):
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == input('3'):
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == input('4'):
Loop = False
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
The problem is you are using input() in if statement. Whenever interpreter tries to check if condition is true or not it executes the input() which demands an input even when you didn't expect it. In one of the methods your input was in wrong order so I fixed that too. So correct code should be :-
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run \n')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
elif choice == '2':
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
elif choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
Loop = False
def enemy_battle(character, enemy):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
You didn't need two classes here clearly. But I suppose you might be thinking of adding some more features in future I guess. You can study more about oop and inheritance and figure out a smarter solution in general. I think you should focus on basics. Also try not to name the temporary variable same as that of class. It is a very hastly written code imo. But I fixed it's working.
Looks interesting, send me a copy after you finish will ya?
so basically you use too much input()
you have to enter a value for every input() function
you need to organize your code, maybe look at how others write their code
this is a quick fix, but it doesn't mean that this is the standard, you still have a lot to learn
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball','iceblock']
Loop = True
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = character(30, 30, 5, 0, 10) # enemy
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == '2':
print('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
spellchoice = input()
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
print("You cowardly run away")
exit()
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
else:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)

Python Error: ValueError: Non-integer arg 1 for randrange()

I'm getting the above error in my code. It's just a simple text-based game.
Here's the code:
import os
import sys
import random
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 10
self.gold = 0
self.potions = 0
class Goblin:
def __init__(self, name):
self.name = name
self.maxhealth = 50
self.health = self.maxhealth
self.attack = 5
self.goldgain = 10
GoblinIG = Goblin("Goblin")
class Zombie:
def __init__(self, name):
self.name = name
self.maxhealth = 70
self.health = self.maxhealth
self.attack = 7
self.goldgain = 15
ZombieIG = Zombie("Zombie")
def main():
#os.system("cls")
print("Welcome to my game!")
print("1) Start")
print("2) Load")
print("3) Exit")
option = input("-> ")
if option == "1":
start()
elif option == "2":
pass
elif option == "3":
pass
else:
main()
def start():
#os.system("cls")
print("Hello, what is your name?")
option = input("-> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
#os.system("cls")
print("Name: %s" % PlayerIG.name)
print("Attack: %s" % PlayerIG.attack)
print("Gold: %i" % PlayerIG.gold)
print("Potions: %i" % PlayerIG.potions)
print("Health: %i/%i" % (PlayerIG.health, PlayerIG.maxhealth))
print("1) Fight")
print("2) Store")
print("3) Save")
print("4) Exit")
option = input("-> ")
if option == "1":
prefight()
elif option == "2":
store()
elif option == "3":
pass
elif option == "4":
sys.exit()
else:
start1()
def prefight():
global enemy
enemynum = random.randint(1,2)
if enemynum == 1:
enemy = GoblinIG
else:
enemy = ZombieIG
fight()
def fight():
print("%s vs %s" % (PlayerIG.name, enemy.name))
print("%s's Health: %s/%s %s Health: %i/%i" % (PlayerIG.name, PlayerIG.health, PlayerIG.maxhealth, enemy.name, enemy.health, enemy.maxhealth))
print("Potions Left: %s\n" % PlayerIG.potions)
print("1) Attack")
#Implement defend system
print("2) Drink Potion")
print("3) Run")
option = input()
if option == "1":
attack()
elif option == "2":
drinkPotion()
elif option == "3":
run()
else:
fight()
def attack():
global PlayerAttack
global EnemyAttack
PlayerAttack = random.randint(PlayerIG.attack / 2, PlayerIG.attack)
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if PlayerAttack == PlayerIG.attack / 2:
print("You missed!")
else:
enemy.health -= PlayerAttack
print("You dealt %i damage!" % PlayerAttack)
option = input(" ")
if enemy.health <= 0:
win()
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input("")
if PlayerIG.health <= 0:
dead()
else:
fight()
def drinkPotion():
if PlayerIG.potions == 0:
print("You don't have any potions!")
else:
PlayerIG.health += 50
if PlayerIG.health >= PlayerIG.maxhealth:
PlayerIG.health = PlayerIG.maxhealth
print("You drank a potion!")
option = input(" ")
fight()
def run():
runnum = random.randint(1,3)
if runnum == 3:
print("You have ran away!")
option = input(" ")
start1()
else:
print("You've failed to run away!")
option = input(" ")
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input(" ")
if PlayerIG.health <=0:
dead()
else:
fight()
def win():
enemy.health = enemy.maxhealth
PlayerIG.gold -= enemy.goldgain
print("You have defeated the %s!" % enemy.name)
print("You found %i gold!" % enemy.goldgain)
option = input(" ")
start1()
def dead():
print("You have died!")
option = input(" ")
def store():
pass
main()
I get the error in def run(), in the else: statement. The line that goes like: EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
Any ideas? Should I elaborate more on my issue? Thanks :)
Use EnemyAttack = random.randint(math.floor(enemy.attack / 2), enemy.attack), or use math.ceil() to round the result of enemy.attack / 2.
randrange() expects whole integers. The error is occurring because the result of enemy.attack / 2 isn't a whole number; it has decimal places whenever enemy.attack is odd. One option is to scale randrange() after it is calculated if you need decimal results.
For example: 0.5*randrange(2*(enemy.attack/2), 2*enemy.attack), which can be simplified into 0.5*randrange(enemy.attack, 2*enemy.attack)

Need help fixing my game in Python

import random
hp = 100
eh = 100
x = 0
y = 0
print("Hello welcome to the beta version of my game.
This game is a 1 v 1 fight to the death against an unknown enemy.
In this game you and the enemy both start out with 100 health.
You can choose to either attack or heal each turn. Have fun and
pay attention to the following rules.")
print("Rule 1: You cannot heal while your health is over 84 points.
If you break this rule your turn will be void.")
print("Rule 2: You can only enter attack, Attack, heal, or Heal.
If you break this rule your turn will be void.")
print("Please press enter to start")
while hp > 0 and eh > 0:
print("Action? (attack, heal, nothing):")
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("You have dealt %s damage" % attack)
elif act == "heal" and hp < 85:
hp = hp + heal
print("You have healed %s points" % heal)
elif act == "heal" and hp > 84:
while x == 0:
if act == "attack":
x +=1
else:
print("You cannot heal at this time, please try again.")
act = input(">")
if enemy_decision == 1:
hp = hp - enemy_attack
print("The enemy has dealt %s damage" % enemy_attack)
elif enemy_decision == 2 and eh > 94:
pass
elif enemy_decision == 2:
eh = eh + enemy_heal_within_5
print("The enemy has healed %s points" % enemy_heal_within_5)
elif enemy_decision == 2 and eh < 85:
eh = eh + enemy_heal
print("The enemy has healed %s points" % enemy_heal)
else:
print("Your health is now %s" % hp)
print("The enemy's health is now %s" % eh)
if hp <= 0:
print("You have lost")
elif eh <= 0:
print("You have won")
I need help creating an else statement where if the player enters something other than attack or heal, it asks them to try to input either attack or heal again. I tried repeating what I did in the hp > 84 section, but it ended up running that section instead of the else section.
You can make something like:
...
while hp > 0 and eh > 0:
act = "empty"
print("Action? (attack, heal, nothing):")
# With this while, you are accepting anything like "aTTaCk", "AttaCK", etc
while act.lower() not in ["attack","heal", "", "nothing"]:
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
...
I added the option nothing and also an empty string("") as an option if the player doesn't want to make anything. If you don't need any of them, just delete both from the list in while statement.
import random
hp = 100
eh = 100
x = 0
y = 0
print("Hello welcome to the beta version of my game. This game is a 1 v 1 fight to the death against an unknown enemy. In this game you and the enemy both start out with 100 health. You can choose to either attack or heal each turn. Have fun and pay attention to the following rules.")
print("Rule 1: You cannot heal while your health is over 84 points. If you break this rule your turn will be void.")
print("Rule 2: You can only enter attack, Attack, heal, or Heal. If you break this rule your turn will be void.")
print("Please press enter to start")
while hp > 0 and eh > 0:
act = ""
print("Action? (attack, heal, nothing):")
while act.lower() != "attack" and act.lower() != "heal":
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("You have dealt %s damage" % attack)
elif act == "heal" and hp < 85:
hp = hp + heal
print("You have healed %s points" % heal)
elif act == "heal" and hp > 84:
while x == 0:
if act == "attack":
x +=1
else:
print("You cannot heal at this time, please try again.")
act = input(">")
if enemy_decision == 1:
hp = hp - enemy_attack
print("The enemy has dealt %s damage" % enemy_attack)
elif enemy_decision == 2 and eh > 94:
pass
elif enemy_decision == 2:
eh = eh + enemy_heal_within_5
print("The enemy has healed %s points" % enemy_heal_within_5)
elif enemy_decision == 2 and eh < 85:
eh = eh + enemy_heal
print("The enemy has healed %s points" % enemy_heal)
else:
print("Your health is now %s" % hp)
print("The enemy's health is now %s" % eh)
if hp <= 0:
print("You have lost")
elif eh <= 0:
print("You have won")
Use a while loop that checks whether the input is not "attack" and if it is not "heal", or any capitalized version of the two. I use !=, but you can also use not, as Ruben Bermudez showed below.

Categories