I've been writing a shitty text-based game for the first time using python, and I've encountered a problem whilst making a function for a battle. It would be called upon each time you encounter an enemy, and the variables will be defined before each fight.
The problem I'm having is that my variable, 'ehp', is being referenced before the assignment of the variable. (Stands for Enemy Health Points). My code is listed below and I would like some help as to what to change to my code to prevent the error code that I'm getting with my program.
import random
hp = int(20)
ehp = int(10)
def fight():
print("You have encountered",(enemy))
if speed >= espeed:
first = "c"
for x in range(100):
if ehp <= 0:
print("You have won!")
break
elif hp <= 0:
print("You have died!")
break
else:
print("1: Light Attack")
print("2: Heavy Attack")
print("3: Dodge")
attack = input("1/2/3: ")
if attack == "1":
print("You have used, Light Attack!")
lightdam = (random.randint(0,damage/2))
print("You have inflicted,",edam,"to",enemy)
ehp = ehp - (random.randint(0,damage/2))
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print(enemy,"Has used attack!")
eattack = (random.randint(0,edam/2))
print(enemy,"Has inflicted",eattack,"damage!")
hp = hp - eattack
print("Enemy Health:",ehp)
print(character,"Health:",hp)
elif attack == "2":
print("You have used, Heavy Attack!")
heavydam = (random.randint(0,damage))
print("You have inflicted,",heavydam,"to",enemy)
ehp = ehp - (random.randint(0,damage))
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print(enemy,"Has used attack!")
eattack = (random.randint(0,edam))
print(enemy,"Has inflicted",eattack,"damage!")
hp = hp - eattack
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print("Welcome to the tales of Iryophia, please enter your characters name.")
character = input("Character name: ")
print("Garnier the Honorable:")
print("Welcome to the city of Iryophia, do you remember how you got here?")
y0 = input("Y/N: ")
for x in range(6):
if y0 == "N":
print("Garnier the Honorable:")
print("Well",character,", all I can remember is a certain man entering a neighbouring town, and well, I'm not sure how to put this, but, you were killed.")
print("I understand how crazy this may sound but you were brought back to life. You would have lost all of your memory, but, you are alive!")
print("Do you remember the name of the man who killed you?")
nemesis = input("Nemesis: ")
print("Garnier the Honorable:")
print("Ah yes, I remember now,",nemesis,"was his name.")
break
if y0 == "Y":
print("Garnier the Honorable:")
print("Okay, well the man that attacked you, what was his name?")
nemesis = input("Nemesis: ")
print("Garnier the Honorable:")
print("Ah yes, I remember now,",nemesis,"was his name.")
break
print("Come back with me to my home.")
print("")
print("Garnier the Honorable:")
print("I have a bow, an axe, or a sword for you. Which one do you pick?")
weapon = input("Bow/Axe/Sword: ")
for x in range(6):
if weapon == "Bow":
damage = int(3)
speed = int(5)
break
if weapon == "Axe":
damage = int(7)
speed = int(3)
break
if weapon == "Sword":
damage = int(5)
speed = (4)
break
print("You have collected:",weapon+"!")
print("Damage:",damage)
print("Speed:",(speed))
print("Garnier the Honorable:")
print("Would you like to have a practice fight?")
fight0 = input("Y/N: ")
for x in range(6):
if fight0 == "Y":
ehp = int(10)
enemy = "Garnier the Honorable"
espeed = int(3)
edam = int(4)
fight()
break
Examine these two code lines in fight() (at least these two, though there may be others):
ehp = ehp - (random.randint(0,damage/2))
hp = hp - eattack
For variables not explicitly marked as global, Python makes some assumptions:
if you only use the variable, it will follow the scope up through different levels until it finds a matching name; and
if you set or change it anywhere in a function, it's considered a local variable everywhere in the function.
Hence a simple fix would be to explicitly mark it global in the function:
def fight():
global ehp
global hp
print("You have encountered",(enemy))
:
and so on
A better fix would probably involve not using globals at all :-)
You should probably also review your hit-point processing, which contains such things as:
heavydam = (random.randint(0,damage))
print("You have inflicted,",heavydam,"to",enemy)
ehp = ehp - (random.randint(0,damage))
Telling the player they've inflicted some amount of damage then subtracting a totally different number of hit points is likely to have players scratching their heads trying to figure out how things work :-)
Related
I need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")
I'm working on a mini-project I'm doing for fun to practice python skills and I am stuck on a problem I can't seem to figure out. I have a function that gives me the default stats for every class in the game and I want it to change depending on what class/weapon I choose in the beginning. I am still trying to learn functions so any input will be valuable. So gameStat() is the default stats while gameStat() is the changed one.
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:")
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=input("What class would you like to play?\n:")
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :"))
print(baseStats(character,weapon))
Thank you so much.
When you take any input it will be in string format to compare it with an integer you need to convert it to integer using int() function
I modified the code and it returns the value of "mana" or "magic" correctly
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=int(input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:"))
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=int(input("What class would you like to play?\n:"))
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(int(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :")))
print(baseStats(userClass,weapon))
In the gameState() function the baseStats takes 5 argument but when you defined baseStats it only takes two arguments character and weapon which is confusing.
The code:
import math
import time
import os
from random import *
def intro():
print("Welcome to battle. This is a game where you battle monsters.")
print("You will try to get the highest score you can.")
print("You start with 100HP. You will need to survive.")
print("You get a max revive every 10 battles.")
print("PS: This game is still in early alpha.")
print("Bugs are expected.")
game()
def game():
health = 100
revive = 0
print("You are greeted by a monster...")
print("1 = Fight")
print("2 = Take a chance at running")
choice = input("")
if choice == 1:
damage = randint(1,100)
health = health - damage
print("You killed the monster!")
print("But you took "+damage+" damage")
print("Your new health is: "+health)
if choice == 2:
print("You tried to run but failed.")
damage = randint(70,100)
health = health - damage
print("Your new health is: "+health)
else:
print("Wrong choice. You died.")
intro()
intro()
The problem: If you use 1 for choice it leads to else. Same with 2. Thanks to anyone that helps! PS: I am using Python 3. I don't know if that's important, I just need to fill out these lines.
Convert your input to int.
Ex:
choice = int(input())
and then replace
if choice == 2:
with
elif choice == 2:
Edit as per comments
def game():
health = 100
revive = 0
print("You are greeted by a monster...")
print("1 = Fight")
print("2 = Take a chance at running")
choice = int(input(""))
if choice == 1:
damage = randint(1,100)
health = health - damage
print("You killed the monster!")
print("But you took "+str(damage)+" damage") #-->Convert int to str before concatenation
print("Your new health is: "+str(health)) #-->Convert int to str before concatenation
elif choice == 2:
print("You tried to run but failed.")
damage = randint(70,100)
health = health - damage
print("Your new health is: "+str(health)) #-->Convert int to str before concatenation
else:
print("Wrong choice. You died.")
You firstly need to cast your input to an int by using int(input(""))
Then:
You need to use elif choice == 2: instead of if choice == 2:.
I'm working on a text-based RPG, but I've found numerous problems, like:
being unable to go anywhere after entering the shop;
I cannot access the "tavern" for some reason; and
the computer just says "buy is not defined in crossbow".
Code:
gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
The first time you ask the user where to go on line 111, what happens if they enter something besides "shop"? then the if choice == "shop": condition on line 119 will fail, and buy = input("...") will never execute. At that point, buy doesn't exist, so when the next conditional executes, it crashes because it can't evaluate if buy == "crossbow". buy has no value, so you can't compare it to anything.
You need to indent all of your shop logic so that it lies inside the if choice == "shop" block.
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
#...etc
if buy == "spell":
print("this costs 35 gold")
And the same problem is present for your tavern code. Even if you don't go to the tavern, you check for tavernChoice. That needs to be indented as well.
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
At this point, your program will end, but I'm guessing you want to continue to be able to explore areas. You could put everything in a while loop, starting with the first input command.
while True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "shop":
print("Welcome to the shop!")
#...etc
elif choice == "tavern":
print("You enter the tavern...")
#...etc
elif choice == "forest":
print("You enter the forest...")
#etc
else:
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
This is also a little cleaner than your current method, since you only have to ask the user where they're going once, instead of three times on lines 112, 165, and 170.
Building on Kevin's answer, here is a version with redundancy squeezed out, so you can add a new place just by adding a new def go_xyz(): ... near the top.
def go_shop():
print("Welcome to the shop!")
#...etc
def go_tavern():
print("You enter the tavern...")
#...etc
def go_forest():
print("You enter the forest...")
#etc
places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)
inventory = ['book']
retry = False
while True:
if not retry:
print("Here is your inventory: ", inventory)
else:
print("I do not know that place")
print("Where do you wish to go?")
print("Possible places: ", placenames, '.')
choice = input("? ")
try:
places[choice]()
retry = False
except KeyError:
retry = True
I'm trying to create a simple question and answer game in Python (version 3.3.2), but can't figure out how to make an expression work. The "health" and "oppHealth" variables seen below will not change as the program runs, or at least the string display won't show them changing. Source code:
import time
#Variables
health = 30
oppHealth = 30
playStr = str(health)
oppStr = str(oppHealth)
def startBattle():
print()
print('You face off against your opponent.')
print()
print("Your health is " + playStr + ".")
print("Your opponent's health is " + oppStr + ".")
time.sleep(2)
print()
print('The opponent attacks with Fire!')
time.sleep(2)
print()
attack = input('How do you counter? Fire, Water, Electricity, or Ice?')
if attack == ('Fire'):
print("You're evenly matched! No damage is done!")
time.sleep(3)
startBattle()
elif attack == ('Water'):
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Electricity'):
print("You both damage each other!")
health - 5
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Ice'):
print("Fire beats ice! You take 5 damage.")
health - 5
time.sleep(3)
startBattle()
startBattle()
I simply want to make the appropriate health variables decrease by 5- and for the health displaying strings to reflect the change- every time a battle occurs. If anyone can help me with this, I'd greatly appreciate it. Please let me know if I've excluded any information that might help you help me.
the lines
health - 5
oppHealth - 5
and similar, do not actually modify anything, to save the subtraction back in the variables, use the -= operator instead
health -= 5
or you can also say
health = health - 5
The above two examples both achieve the same result. When you just say health - 5 you don't actually save it anywhere.
In addition to this you will need to specify global at the top of your function to modify these values or you will get an error.
def startBattle():
global health
global oppHealth
# ... rest of function
Also you don't need the playStr and oppStr variables, you can print the numeric values like this:
print("Your health is", health, ".")
print("Your opponent's health is", oppHealth, ".")
These don't really need to be global at all though, they can be within the function, sitting in a loop, my version of your program would be this:
#!/usr/bin/env python3
import time
def startBattle():
# set initial values of healths
health = 30
oppHealth = 30
print('You face off against your opponent.', end='\n\n')
while health > 0 and oppHealth > 0: # loop until someone's health is 0
print("Your health is {0}.".format(health))
print("Your opponent's health is {0}.".format(oppHealth), end='\n\n')
time.sleep(2)
print('The opponent attacks with Fire!', end='\n\n')
time.sleep(2)
print('How do you counter? Fire, Water, Electricity, or Ice?')
attack = input('>> ').strip().lower()
if attack == 'fire':
print("You're evenly matched! No damage is done!")
elif attack == 'water':
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth -= 5
elif attack == 'electricity':
print("You both damage each other!")
health -= 5
oppHealth -= 5
elif attack == 'ice':
print("Fire beats ice! You take 5 damage!")
health -= 5
else:
print("Invalid attack choice")
time.sleep(3)
if health <= 0 and oppHealth <= 0:
print("Draw!")
if health <= 0:
print("You lose")
else:
print("You win!")
startBattle()
Though I'd also get rid of all the sleeps. People don't enjoy waiting for a program to "do work" as much as you might think, it's just gonna cause people to click away.
Read a bit more about Python syntax. The correct way to change the value of a variable is, for example:
health = health - 5
oppHealth - 5 should be written as
oppHealth = oppHealth - 5
You're forgetting save the result of your computation