i wanted to make the calculation stop on zero (self.health == 0), but it keeps subtract until below the zero. the subtraction is impossible to reach 0. How do i make the calculation, so the code doesn't reach the negative numbers?
class Hero:
def __init__(self, name, health, damage, armor, m_speed):
self.name = name
self.health = health
self.damage = damage
self.armor = armor
self.m_speed = m_speed
def attack(self, enemy):
print(self.name + " has attacked " + enemy.name)
enemy.attacked(self, self.damage)
def attacked(self, enemy, damage_enemy):
print(self.name + " has been attacked by " + enemy.name)
attack_received = (damage_enemy/(2.5*self.armor))
print(str(attack_received) + " is taken")
self.health -= attack_received
print(self.name + " health is now " + str(self.health))
def dead(self, enemy):
while self.health > 0:
h1.attack(h2)
print("\n")
h2.attack(h1)
print("\n")
if self.health == 0:
break
h1 = Hero("Hero1", 532, 129, 5, 310)
h2 = Hero("Hero2", 476, 176, 4, 296)
h1.dead(h2)
print("\n")
h2.dead(h1)
Define a method alive (maybe worth defining as a property if you are familiar with it):
def alive(self):
if self.health > 0:
return True
return False
You had h1 and h2 inside the dead method, you wanted to refer to self and enemy.
Change the dead method to something like this (dead is a bad name, use something else):
def combat(self, enemy):
while enemy.alive() and self.alive():
if enemy.alive():
enemy.attack(self)
if self.alive():
self.attack(enemy)
print("\n")
Also worth putting
if not self.alive():
print(self.name + " is dead.")
to the end of attacked method. There are more things to improve, but I think this should be enough to get you started.
Related
The part with the goblin works but the part with the elf doesn't.
#importing the random module
import random
#creating the game object class
class GameObject:
class_name = ""
desc = ""
objects = {}
def __init__(self, name):
self.name = name
GameObject.objects[self.class_name] = self
#defining the description
def get_desc(self):
return self.class_name + "\n" + self.desc
#creating the goblin class
class Goblin(GameObject):
def __init__(self, name):
self.class_name = "goblin"
self.health = 3
self._desc = "A foul creature"
super().__init__(name)
#property
def desc(self):
if self.health >= 3:
return self._desc
elif self.health == 2:
x = random.randint(13, 35)
health_line = "You struck and dealt " + str(x) + " damage!"
elif self.health == 1:
y = 40 - random.randint(13, 35)
health_line = "You rushed and dealt " +str(y) + " damage! \n Goblin activated effect Rage!"
elif self.health <= 0:
health_line = "It is dead."
return self._desc + "\n" + health_line
#desc.setter
def desc(self, value):
self._desc = value
#creating the goblin object
goblin = Goblin("Gobbly")
#creating the elf class
class Elf(GameObject):
def __init__(self, name):
self.class_name = "Elf"
self.health = 5
self._desc = "A strong warlock"
super().__init__(name)
#property
def desc(self):
if self.health >= 5:
return self._desc
elif self.health == 4:
x = random.randint(20, 50)
health_line = " You struck and dealt " + str(x) + " damage!"
elif self.health == 3:
x = random.randint(20, 40)
health_line = " You countered and dealt " + str(x) + " damage!"
elif self.health == 2:
y = 40 - random.randint(20, 50)
health_line = "You rushed and dealt " +str(y) + " damage! \n Elf activated effect Sectum Sempra!!"
elif self.health == 1:
y = 40 - random.randint(20, 50)
health_line = " You struck and dealt " + str(x) + " damage!"
elif self.health <= 0:
health_line = "It is dead."
return self._desc + "\n" + health_line
#desc.setter
def desc(self, value):
self._desc = value
#creating an elf object
elf = Elf("Elfy")
#defining the hit verb
def hit(noun):
if noun in GameObject.objects:
thing = GameObject.objects[noun]
if type(thing) == Goblin:
thing.health -= 1
if thing.health <= 0:
msg = "You killed the goblin!"
else:
msg = "You hit the {}".format(thing.class_name)
elif type(thing) == Elf:
thing.health -= 1
if thing.health <= 0:
msg = "You killed the elf!"
else:
msg = "You hit the {}".format(thing.class_name)
else:
msg = "There is no {} here.".format(noun)
return msg
#defining the examine verb
def examine(noun):
if noun in GameObject.objects:
return GameObject.objects[noun].get_desc()
else:
return "There is no {} here.".format(noun)
#getting input
def get_input():
command = input(": ").split()
verb_word = command[0]
if verb_word in verb_dict:
verb = verb_dict[verb_word]
else:
print("Unknown verb {}".format(verb_word))
return
if len(command) >= 2:
noun_word = command[1]
print(verb(noun_word))
else:
print(verb("nothing"))
#defining the say verb
def say(noun):
return 'You said "{}"'.format(noun)
#the verbs
verb_dict = {
"say": say,
"examine": examine,
"hit": hit
}
while True:
get_input()
It's supposed to say |you hit the elf| when I type |hit elf| like how it says |you hit the goblin| when I type |hit goblin|
I just started learning oop in python and some parts are confusing. If anyone understands, please help me fix the code.
At first elif refers to else if , that simply means that if statement is activated then the elif statement gets skipped . So try replacing elif with if . If problem still continues , reply.
I don't see that you need to check the type of the object here:
def hit(noun):
if noun in GameObject.objects:
thing = GameObject.objects[noun]
thing.health -= 1
if thing.health <= 0:
msg = "You killed the {}!".format(thing.class_name.lower())
else:
msg = "You hit the {}".format(thing.class_name)
else:
msg = "There is no {} here.".format(noun)
return msg
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am making a text game for fun and can't find a pythonic way to update the player's stats.
I tried variables like h = 100 player = class(h,d,a,w) (health, defense, attack, weight) but then to have the players health change, I have to do this: h -= enemy attack (ea) player = class(h,d,a,w). Which is long and later on brakes when I add in defense and weapons. Variables work but are very long and unstable when I start to do a lot of math with them to make it more interesting. I also looked into class methods but couldn't find a way to pass player some stat as so that it would update.
import random as ran
class Client:
def __init__(self, health, defense, attack, weight):
self.health = health
self.defense = defense
self.attack = attack
self.weight = weight
class NPC:
def __init__(self, health, defense, attack):
self.health = health
self.defense = defense
self.attack = attack
#client inventory
inv = []
#a set of true or false statements to create a loop
alive = True
enemy_alive = False
while alive == True:
message = input()
player = Client(100, 0, 0, 0)
enemy = NPC(100, 0, 20)
# A way to brake the loop at any time
if message == "q":
alive = False
# Now we need a way to choice a wepon
if len(inv) == 0:
if message == "pick up bow":
print("The bow is now in your inventory.")
inv.append("Bow")
# This was my latest atempt to set player attack to the damage of the bow
player.attack += 25
combat = True
if len(inv) > 0 and combat == True:
if enemy_alive == False:
print("""A enemy is chargeing at you!
HP: 100""")
#We start the fight now that the player has a bow
enemy_alive = True
if "Bow" in inv:
#This is where I said to my self what if I could have attack directly effect health so that when the fight loop is broke the players stats stay with them and so that the math is more set and stone
if minotaur.defense == 0:
if message == "shoot":
hit = ran.randint(0,9)
if hit == 9:
print("Head Shot")
enemy.health = 0
if hit <= 4:
print("Miss")
player.health = player.health-enemy.attack
print("HP :"+str(player.health))
if hit >= 5:
print("HIT!")
enemy.health = enemy.health-player.attack
print("Enemy HP: "+str(enemy.health))
if enemy.defense > 0:
#I made this so I could see if it worked but like above nothing saves correctly
player.attack = player.attack/minotar.defense
if message == "shoot":
hit = ran.randint(0,9)
if hit == 9:
print("Head Shot")
enemy.health = 0
if hit <= 4:
print("Miss")
player.health = player.health-enemy.attack
print("HP :"+str(player.health))
if hit > 4:
print("HIT!")
enemy.health = enemy.health-player.attack
print("Enemy HP: "+str(enemy.health))
if enemy.health <= 0:
print("The Minotaur died a painful death.")
minotaur_alive = False
combat = False
if player.health <= 0:
print("You died!")
alive = False
When I execute the code the only thing that doesn't work is the stat updates. I have a debug layer on my real code that allows me to see if the current state of the game so I know for sure that it isn't updating.
You could maybe consider have every object in the game handle its own behavior: for instance, a Player object could have a Stats object that gets updated when some event happens.
When this works well with one type of Player, you can consider subclassing to modify the behavior; make it harder to kill, of with faster recovery, etc...
Maybe something like this:
class Player:
def __init__(self, name, stats):
self.name = name
self.stats = stats
def get_hit(self, hit_value):
self.stats.update_health(-hit_value)
def rest(self):
self.stats.update_health(10)
def __str__(self):
return f'Player {self.name}: {self.stats}'
class FastRecoveryPlayer(Player):
def rest(self):
self.stats.update_health(20)
class Stats:
"""maintains the Player's stats up to date
"""
def __init__(self, health=100, defense=100, attack=100):
self.health = health
self.defense = defense
self.attack = attack
def update_health(self, value):
self.health += value
self.health = max(0, self.health)
self.health = min(100, self.health)
def __str__(self):
return f'health: {self.health}, defense: {self.defense}, attack: {self.attack}'
hero = Player('Python King', Stats())
print(hero)
print('the Hero gets hit hard')
hero.get_hit(30)
print(hero)
print('the Hero rests a little bit')
hero.rest()
print(hero)
print()
hero2 = FastRecoveryPlayer('Python Emperor', Stats())
print(hero2)
print('the Hero2 gets hit hard')
hero2.get_hit(30)
print(hero2)
print('the Hero2 rests a little bit')
hero2.rest()
print(hero2)
output:
Player Python King: health: 100, defense: 100, attack: 100
the Hero gets hit hard
Player Python King: health: 70, defense: 100, attack: 100
the Hero rests a little bit
Player Python King: health: 80, defense: 100, attack: 100
Player Python Emperor: health: 100, defense: 100, attack: 100
the Hero2 gets hit hard
Player Python Emperor: health: 70, defense: 100, attack: 100
the Hero2 rests a little bit
Player Python Emperor: health: 90, defense: 100, attack: 100
This is generally related to OO design, I suggest that you have a base class of Character (although not essential) and have Client and NPC inheriting that base class, then have an attack and receive_attack method.
class Character():
def __init__(self, health, defense, damage, weight):
self.health = health
self.defense = defense
self.damage = damage
self.weight = weight
def attack(self,target):
target.receive_attack(self.damage)
def receive_attack(self,damage):
self.health -= damage
class Client(Character):
pass
class NPC(Character):
pass
class NPC_harder_to_take_down(Character):
def receive_attack(self,damage):
self.health -= (damage/2)
me = Client(100,100,100,100)
other = NPC(10,10,10,10)
print(me.health)
>>>100
other.attack(me)
print(me.health)
>>>90
I'm a beginner and stumbled across an issue with inheritance.
When I use this block of code, the program doesn't work correctly thanks to a line in the enter function:
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
def enter(self, world, player):
super(Bathroom, self).enter(world, player)
But, when I use this, it does:
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
Are they not the same thing?
The full script I've written (not finished btw) is below. When I enter 'y' after being asked 'Do you want to leave', the program finishes when I use 'super' to inherit the enter function. If I don't, the program works:
while player and self.name != "corridor":
response = self._ask_question("Do you want to leave? (y/n) ", "y", "n")
if response == "y":
return world.corridor
elif response == "n" and self.enemy:
print("The", self.enemy, "kills you. You didn't even put up a\
fight")
return world.death
Full script:
import random
import time
# bad from sys import exit
class Character(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def __str__(self):
return str(self.health) + " health and " + str(self.attack) + " attack."
class Room(object):
def __init__(self, name):
self.name = name
self.enemy = self._getRandEnemy()
def enter(self, world, player):
print(player.name + ",", "you are in the", self.name + ". You have\
" + str(player))
if self.enemy: # you may have killed it
print("But, wait! There's a", self.enemy.name, "with " + str(\
self.enemy))
response = self._ask_question("Do you stay and fight?(y/n)\
", "n", "y")
if response == "n":
pass
if response == "y":
self.combat(player, self.enemy)
else:
print("No enemies here.")
# check if player has no health after potential fight
if player.health < 1:
return world.death
while player and self.name != "corridor":
response = self._ask_question("Do you want to leave? (y/n) ", "y", "n")
if response == "y":
return world.corridor
elif response == "n" and self.enemy:
print("The", self.enemy, "kills you. You didn't even put up a\
fight")
return world.death
def _getRandEnemy(self):
names = ["Troll", "Witch", "Ogre", "Jeremy Corbyn"]
return Character(random.choice(names), random.randint(4, 6),\
random.randint(2, 3))
def _ask_question(self, question, a, b):
response = None
while response not in(a, b):
response = input(question)
return response
def combat(self, player, enemy):
while player.health > 0 and enemy.health > 0:
time.sleep(1)
print("You attack and deal", player.attack, "damage")
enemy.health -= player.attack
if enemy.health >= 1:
print("The enemy has " + str(self.enemy))
time.sleep(1)
print("The", self.enemy.name, "attacks and deals you",\
self.enemy.attack, "\
damage.")
player.health -= enemy.attack
print("You have " + str(player))
if player.health < 1:
pass
if enemy.health < 1:
print("Ha! Got him!")
self.enemy = None
class Corridor(Room):
def __init__(self):
self.name = "corridor"
self.enemy = None
def enter(self, world, player):
super(Corridor, self).enter(world, player)
room = self._ask_question("Which room: bathroom, bedroom ",\
"bedroom", "bathroom", "Library", "study")
if room == "bedroom":
return world.bedroom
if room == "bathroom":
return world.bathroom
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
def enter(self, world, player):
super(Bathroom, self).enter(world, player)
class Bedroom(Room):
def __init__(self):
super(Bedroom, self).__init__("bedroom")
class Death(Room):
def __init__(self):
super(Death, self).__init__("death")
def enter(self, world, player):
time.sleep(1)
responses = ["Off to the man in sky. You are dead", "You died,\
no-one cried.", "Lolz. You're dead!"]
print(random.choice(responses))
return None
class World(object):
def __init__(self):
self.corridor = Corridor()
self.bathroom = Bathroom()
self.death = Death()
self.bedroom = Bedroom()
self.start = self.corridor
def play_game(world, player):
room = world.start
while room:
room = room.enter(world, player)
play_game(World(), Character("Bob", 12, 2))
I know I must be missing something obvious.
Thanks, Dave.
You forgot to return the result of the super().enter() call. You are swallowing the return value, so you never returned the new room. The following would be correct:
class Bathroom(Room):
def enter(self, world, player):
return super(Bathroom, self).enter(world, player)
Not that there is a point in defining a new Bathroom().enter() method if all you do is call the original version with super(). You may as well remove the whole enter() method (as I've done for the __init__ method, above).
I cannot figure it out how to end this loop :(
import random
class Enemy:
life = 300
print ('Player 1 your life is ' + str(life) + ' hp' )
def bonusdmg(self):
bondmg=random.randrange(40,51)
print('congratz u made ' + str(bondmg)+' bonus dmg')
self.life-=bondmg
def attack(self):
ad1=random.randrange(50,81)
print(str(ad1) + 'dmg')
print('ouch')
self.life -=ad1
def attack2(self):
ad2=random.randrange(60,90)
print(str(ad2) + 'dmg')
print('arghhh')
self.life -=ad2
def attack3(self):
ad3=random.randrange(100,111)
print(str(ad3) + 'dmg')
print('tsshaaah')
self.life -=ad3
def heal(self):
hp=random.randrange(40,51)
print ('No more potions')
self.life +=hp
print(str(hp) + ' hp have been restored')
def checkLife(self):
if self.life <=0:
print('Your enemy is dead')
else:
print(str(self.life) + "hp life left")
class Enemy2:
life = 300
print ('Player 2 your life is ' + str(life) + ' hp' )
def bonusdmg(self):
bondmg=random.randrange(40,51)
print('congratz u made ' + str(bondmg)+' bonus dmg')
self.life-=bondmg
def attack(self):
ad1=random.randrange(50,81)
print(str(ad1) + 'dmg')
print('ouch')
self.life -=ad1
def attack2(self):
ad2=random.randrange(60,90)
print(str(ad2) + 'dmg')
print('arghhh')
self.life -=ad2
def attack3(self):
ad3=random.randrange(100,111)
print(str(ad3) + 'dmg')
print('tsshaaah')
self.life -=ad3
def heal(self):
hp=random.randrange(40,51)
print ('No more potions')
self.life +=hp
print(str(hp) + ' hp have been restored')
def checkLife(self):
if self.life <=0:
print('Your enemy is dead')
else:
print(str(self.life) + "hp life left")
enemy2 = Enemy2()
enemy1 = Enemy()
while 1:
turn = 1
if turn ==1:
while 1:
print('Player 1 is your turn !')
bonus=str(random.randrange(1,6))
player_move=input('Player1 choose your attack !')
if player_move =='a':
enemy1.attack()
enemy1.checkLife()
turn +=1
break
if player_move =='s':
enemy1.attack2()
enemy1.checkLife()
turn +=1
break
if player_move == 'd':
enemy1.attack3()
enemy1.checkLife()
turn +=1
break
if enemy1.life <=0:
break
if bonus=='2':
enemy1.bonusdmg()
if turn ==2:
while 1:
print('Player 2 is your turn !')
bonus=str(random.randrange(1,6))
player_move=input('Player2 choose your attack !')
if player_move =='a':
enemy1.attack()
enemy1.checkLife()
turn -=1
break
if player_move =='s':
enemy1.attack2()
enemy1.checkLife()
turn -= 1
break
if player_move == 'd':
enemy1.attack3()
enemy1.checkLife()
turn -=1
break
if enemy1.life <=0:
break
if bonus=='2':
enemy1.bonusdmg()
You can try breaking the loop once a certain condition is satisfied. For example, try it like this:
# in while loop
if condition_is_true:
break
Otherwise, you'll need to specify a condition within the declaration of your while loop. I suggest this technique because it does not close your program. It can execute the code below your loop as well, if you have any.
while condition_is_true:
I cleaned up a lot of this, some notes at bottom.
import random
class Player:
def __init__(self, num):
self.num = num
self.life = 300
print('%s your life is %d hp' % (self, self.life))
self.enemy = None
def __str__(self):
return "Player %d" % self.num
def bonusdmg(self):
bondmg=random.randrange(40,51)
print('congratz u made %d bonus dmg' % bondmg)
self.deal_damage(bondmg)
def attack(self):
ad1=random.randrange(50,81)
print('You attack for %d dmg -- ouch' % ad1)
self.deal_damage(ad1)
def attack2(self):
ad2=random.randrange(60,90)
print('You attack for %d dmg -- arghhh' % ad2)
self.deal_damage(ad2)
def attack3(self):
ad3=random.randrange(100,111)
print('You attack for %d dmg -- tsshaaah' % ad3)
self.deal_damage(ad3)
def heal(self):
hp=random.randrange(40,51)
print ('No more potions')
self.life += hp
print('%d hp have been restored' % hp)
def checkEnemyLife(self):
if self.enemy.life <=0:
return "%s is dead" % self.enemy
else:
return "%s has %d hp left" % (self.enemy, self.enemy.life)
# New
def take_damage(self, amt):
print('%s takes %d dmg' % (self, amt))
self.life -= amt
# New
def deal_damage(self, amt):
self.enemy.take_damage(amt)
print(self.checkEnemyLife())
# New
def handle_action(self, player_move):
if player_move =='a': self.attack()
if player_move =='s': self.attack2()
if player_move == 'd': self.attack3()
bonus=str(random.randrange(1,6))
if bonus==2: # Fixed this
self.bonusdmg()
# New
def turn(self):
print("")
player_move = raw_input("%s it's your turn! Choose your attack! " % self)
self.handle_action(player_move)
# New
def won(self):
return (self.enemy.life <= 0)
player1 = Player(1)
player2 = Player(2)
player1.enemy = player2
player2.enemy = player1
# Enemy class
# life as attribute
# raw_input
# string formatting
turn = 1 # Moved this
run_game = True
while run_game:
if turn == 1:
player1.turn()
if player1.won():
print("Player 1 wins")
run_game = False
break
turn += 1
elif turn == 2:
player2.turn()
if player2.won():
print("Player 2 wins")
run_game = False
break
turn -= 1
Made both Enemy classes a single Player class, player1 and player2 are instances of the same class.
Gave each Player instance a reference to their enemy, so they don't deal damage to themselves anymore.
Created a bunch of methods that help stream line your main game loop
Improved printing using string formatting (%) operator.
Changed input to the safer raw_input
life is now an instance attribute instead of a class attribute
A of other, smaller changes
Although your code has many mistakes,I think the infinite loop you are referring is in the inner loop
turn = 1
if turn ==1:
while 1: #this cause a problem, how are you going to exit this loop?
#rest of the code
You never change turn = 2 therefore the if statement turn == 1 is always True. You need to find a place to make turn = 2 so the second player can move. This however will not solve all your issues.
I am new to programming in python and, I started writing a simple text based adventure game. I came across a problem when passing an object from one function to another. Here is my code:
import random
import time
num = random.randint(0,2)
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.__health = health
self.__strength = strength
self.__defense = defense
self.__name = name
self.__potion = potion
self.__xp = xp
self.__level = level
def getName(self):
return self.__name
def getHealth(self):
return self.__health
def getStrength(self):
return self.__strength
def getDefense(self):
return self.__defense
def getPotion(self):
return self.__potion
def getXP(self):
return self.__xp
def getLevel(self):
return self.__level
def setHealth(self):
self.__health = 10
def setLevel(self):
self.__level = 1
def subHealth(self, num):
self.__health -= num
def subPotion(self):
self.__potion -= 1
return self.__health
def addPotion(self, num1):
self.__potion += num1
def addHealth(self):
self.__health +=2
def addStrength(self):
self.__strength += 1
def addDefense(self):
self.__defense += 1
def addXP(self):
self.__xp += xp1
def addLevel(self):
self.__level += 1
self.__addHealth += 1
self.__defense += 1
self.__strength += 1
def battle(enemy, player1, name1):
player1 = player(name1, player1.getHealth(), player1.getStrength(), player1.getDefense(), player1.getPotion(), player1.getXP(), player1.getLevel())
enemy = player('Dongus', enemy.getHealth(), enemy.getStrength(), enemy.getDefense(), enemy.getPotion(), enemy.getXP(), enemy.getLevel())
s = 0
while s == 0:
time.sleep(1)
attack =int(input("Type 1 to attack, type 2 to use a potion."))
if attack == 1:
time.sleep(1)
print("Dongus's health is", enemy.subHealth(num))
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
elif attack == 2:
time.sleep(1)
print("You used a potion.")
player1.addHealth(), player1.subPotion()
if player1.getHealth() > 10:
player1.setHealth()
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
if enemy.getHealth()<=0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
time.sleep(1)
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
time.sleep(2)
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player('Dongus', 8, 4, 0, 0, 0, 0)
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player1.getDefense())
time.sleep(2)
print("Fight!")
pick = input("You found a health potion! Press 'p' to pick it up.")
p = 0
while p == 0:
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion(1)
p = 2
else:
print("You have no potions, you should probably pick this one up.")
player1.addPotion(1)
p = 2
battle(enemy, player1, name1)
if self.__getXP() == 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player.getDefense())
loot1 = int(input("Type ''1'' to loot the enemy chest."))
if loot1 == 1:
print("You recieved two potions!")
player1.__addPotion(2)
enemy.setHealth(10)
battle(enemy, player1, name1)
main()
Now the problem is when I run the game, I get to a point where I type "1" to attack the enemy, but it says, for some reason, that after attacking the enemy, the enemies health is at "None". This is the same case when the enemy attacks player1, it says player1's health is at "None". I assume that "None" is the default value in python 3.4.1, so my thinking is that the player1's object from def main() are not being transferred over to def battle() and I cannot see the reason why this is happening. I most likely am missing something here, or it is something I do not already know about Python that is causing the issue. Does anybody know what I can do to fix this, and why it is doing this?
BTW some of the terms I am using may be wrong, so please correct me if they are... I have only been coding for 2 weeks :p.
Thanks!!!
First, received not recieved
2nd yes, If you have a Python function that does not return a value, the result is None
# dummy will return "Positive" or None
def dummy(x):
if X > 0:
return "Positive"
So, you probably want to change
def subHealth(self, num):
self.__health -= num
to
def subHealth(self, num):
self.__health -= num
return self.__health
Your question re: the "player" classes from def main() are not being transferred over to def battle() does not really make sense to me.
But, I see that in the first 2 lines of battle, you are replacing the formal parameters player1 and enemy with local variables, this seems like odd usage in your program.