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 7 years ago.
Improve this question
I wanted to decrease the players health but I was unsure if I was able to do this, sorry if this question is unclear but I am a new coder and am slowly get a grasp on how classes work. I think I need to make this more clear as I can.
class Health(object):
#health of player and enemy
#input of the both health so it is able to
#be a preset for more combat
def __init__(self, player, enemy):
self.player = player
self.enemy = enemy
class Attack_Type(object):
#making a attack type blueprint
#combat attacks can be modified
def melee(self, target):
#100% chance of landing hit
if target == player:
Health.player -= 1
return Health.player
elif target == enemy:
Health.enemy -= 1
return Health.enemy
test = Health(10,10)
enemy_melee = Attack_Type(Health.player)
My question is how do i access a variables value inside a class without making it global. Am i able to change the value of the class value within the class?
This Does Not change the players health because it can't access the players health but even when it does it does not return the value to the right place
I now to realise that it is much simpler to make the health a attribute, sorry everyone i do not fully understand how classes work! Thanks for all the help!
I hope this helps! :)
class Health:
def __init__(self): #Constructor initializing the variables.
self.player_health = 10
self.enemy_health = 10
class Combat:
#Attack function receives a health object called "hitter"
def attack(self, hitter):
hitter.player_health -= 1 #Health Object hitter's player_health reduced by one.
return hitter
bridge = Combat() #Combat Object
hitter = Health() #Health Object
bridge.attack(hitter) #hitter.player_health is now 9.
Here's one incarnation.
class Health:
def __init__(self):
self.player_health = 10
self.enemy_health = 10
class Combat:
def attack(self, health_obj):
health_obj += -1
return health_obj
bridge = Combat()
players = Health()
print(bridge.attack(players.player_health))
Related
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 11 months ago.
Improve this question
I'm a fairly new programmer and I started learning Python. I've given myself the task of programming a text-based RPG with a kind of round-based fighting like Pokémon or the older Final Fantasy games. Right now I'm working on the battle mechanics, but I ran into an error which I couldn't fix. When I call the 'battle' function in my main I always get the error: 'TypeError: 'int' object is not callable'. I'd be happy if you could help me with this one, like I said, I'm still very new to programming.
My error-Message:
Traceback (most recent call last): File "C:\Doku\Python310\Scripts\text_adventure.py", line 169, in <module>
battle(main.health, main.attack, main.defence, enemy.health, enemy.attack, enemy.defence, main, enemy) File "C:\Doku\Python310\Scripts\text_adventure.py", line 106, in battle
x = player.attack(enemy.health) TypeError: 'int' object is not callable
line 169
#call battle function with the stats of my main character and an enemy
battle(main.health, main.attack, main.defence, enemy.health, enemy.attack, enemy.defence, main, enemy)
line 103-112
#choose between attack and special attack - error occurs with both descisions the same way
while True:
desc = choose()
if desc == 'A' or desc == 'a':
x = player.attack(enemy)
y = player.check_battle()
break
elif desc == 'B' or desc == 'b':
player.specialmove(enemy)
player.check_battle()
break
my choose function:
#couldn't run it without it, don't know why
def choose():
desc = input()
return desc
my main (shortened)character class:
class Main:
#init
def __init__(self, Mhealth, Mattack, Mdefence):
self.health = Mhealth
self.attack = Mattack
self.defence = Mdefence
self.multiplier = 1.00
#attacks
def attack(self, enemy):
x = enemy.health - (self.attack-enemy.defence)
enemy.setHealth(x)
def specialmove(self, enemy):
enemy.health -= round((self.attack*1.5)-enemy.defence)
def movelist(self):
moves = ['A - Attack', 'B - Special']
return moves
my enemy class is built the same way
self.attack is an integer. You set it in __init__ part of the class. Rename either the attack function or this number.
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 2 years ago.
Improve this question
class Car:
def __init__(self,max_speed,speed_unit):
self.max_speed = max_speed
self.speed_unit = speed_unit
def car(self):
print('Car with the maximum speed of ',self.max_speed,' ',self.speed_unit)
class Boat:
def __init__(self,max_speed):
self.max_speed = max_speed
def boat(max_speed):
print('Boat with the maximum speed of ',self.max_speed,'knots')
I guess this is what you are trying to do.
Be sure to add parentheses () when you call a function.
class Car:
def __init__(self,max_speed,speed_unit):
self.max_speed = max_speed
self.speed_unit = speed_unit
def car(self):
print(f"Car with the maximum speed of {self.max_speed} {self.speed_unit}")
class Boat:
def __init__(self,max_speed):
self.max_speed = max_speed
def boat(self):
print(f'Boat with the maximum speed of {self.max_speed} knots')
if __name__ == "__main__":
car = Car(15, "km")
car.car()
boat = Boat(20)
boat.boat()
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm struggling to figure out how to organize things here.
I'm building a race game. There are players and race courses. Player have attributes like name, age, etc. Race courses also have a set of attributes, including difficulty. One thing I want to do is, when a player runs a course their energy level drops based on difficulty of the course. What I'm confused about is, because difficulty is an attribute of the course, and energy level is an attribute of the player, how can I affect the two?
Take the code for example...
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
Maybe I am going about this all wrong? Does course need to be a class?
Thanks for any input.
How can I affect the two?
This you can achieve by passing an object of type Course to the run function like so:
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self, course):
#use course.difficulty to reduce self.energy_level
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
player1.run(course1) # this will pass course1 to the run function and run will reduce the energy level according to the difficulty of course1
You can make course a member of the player class
class Player():
course = null;
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
self.course1 = Course("Advanced Track", 15)
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
#change self.energy based on self.course1.difficulty
Of course this is an oversimplification. You need to add methods to open new courses, and not hardcode this in the constructor.
I have recently started my end of the year project in computer science (self proposed, also my first year taking it so only have about 4 months of python experience) and decided I wanted to do a simple Pokemon simulator in it.
I've recently run into a roadblock: Let's say the user chooses Pikachu as their starter. I don't want the user to input their health, attack, speed, and moves. Is their a way to create a Pikachu class that already has that data in it?
I tried something like this:
class Pikachu(object):
def __init__(self):
self.data = []
def health(self):
self.health = 22
print self.health
def attack(self):
self.attack = 7
def speed(self):
self.speed = 6
Pikachu.health()
When I do this (in an attempt to check and see if the health is stored and will be returned on demand), it gives the error:
TypeError: unbound method health() must be called with Pikachu instance as first argument (got nothing instead)
I'm confused as to what the error means as well. Usually this would work and you wouldn't need an argument in the parentheses, but in this instance it doesn't.
Is there some different way to create a class and store data in it? Is there some way to just create an object or do something like this:
def Pikachu:
health = 22
attack = 7
speed = 6
it is because your variable names are the same as your method names. and also why don't you initialise everything in the constructor:
class Pikachu(object):
def __init__(self):
self.data = []
self.attack = 7
self.health = 22
self.speed = 6
def get_health(self):
return self.health
def get_attack(self):
return self.attack
def get_speed(self):
return self.speed
if __name__ == '__main__':
p = Pikachu()
print p.get_health()
I just started learning python and I am hoping you guys can help me comprehend things a little better. If you have ever played a pokemon game for the gameboy you'll understand more as to what I am trying to do. I started off with a text adventure where you do simple stuff, but now I am at the point of pokemon battling eachother. So this is what I am trying to achieve.
Pokemon battle starts
You attack target
Target loses HP and attacks back
First one to 0 hp loses
Of course all of this is printed out.
This is what I have for the battle so far, I am not sure how accurate I am right now. Just really looking to see how close I am to doing this correctly.
class Pokemon(object):
sName = "pidgy"
nAttack = 5
nHealth = 10
nEvasion = 1
def __init__(self, name, atk, hp, evd):
self.sName = name
self.nAttack = atk
self.nHealth = hp
self.nEvasion = evd
def fight(target, self):
target.nHealth - self.nAttack
def battle():
print "A wild appeared"
#pikachu = Pokemon("Pikafaggot", 18, 80, 21)
pidgy = Pokemon("Pidgy", 18, 80, 21)
pidgy.fight(pikachu)
#pikachu.fight(pidgy)
Full code here: http://pastebin.com/ikmRuE5z
I am also looking for advice on how to manage variables; I seem to be having a grocery list of variables at the top and I assume that is not good practice, where should they go?
If I was to have fight as a instance method (which I'm not sure I would), I would probably code it up something like this:
class Pokemon(object):
def __init__(self,name,hp,damage):
self.name = name #pokemon name
self.hp = hp #hit-points of this particular pokemon
self.damage = damage #amount of damage this pokemon does every attack
def fight(self,other):
if(self.hp > 0):
print("%s did %d damage to %s"%(self.name,self.damage,other.name))
print("%s has %d hp left"%(other.name,other.hp))
other.hp -= self.damage
return other.fight(self) #Now the other pokemon fights back!
else:
print("%s wins! (%d hp left)"%(other.name,other.hp))
return other,self #return a tuple (winner,loser)
pikachu=Pokemon('pikachu', 100, 10)
pidgy=Pokemon('pidgy', 200, 12)
winner,loser = pidgy.fight(pikachu)
Of course, this is somewhat boring since the amount of damage does not depend on type of pokemon and isn't randomized in any way ... but hopefully it illustrates the point.
As for your class structure:
class Foo(object):
attr1=1
attr2=2
def __init__(self,attr1,attr2):
self.attr1 = attr1
self.attr2 = attr2
It doesn't really make sense (to me) to declare the class attributes if you're guaranteed to overwrite them in __init__. Just use instance attributes and you should be fine (i.e.):
class Foo(object):
def __init__(self,attr1,attr2):
self.attr1 = attr1
self.attr2 = attr2v
You don't need the variables up the top. You just need them in the init() method.
The fight method should return a value:
def fight(self, target):
target.nHealth -= self.nAttack
return target
You probably want to also check if someone has lost the battle:
def checkWin(myPoke, target):
# Return 1 if myPoke wins, 0 if target wins, -1 if no winner yet.
winner = -1
if myPoke.nHealth == 0:
winner = 0
elif target.nHealth == 0:
winner = 1
return winner
Hope I helped.
I am only going to comment on a few obvious aspects, because a complete code review is beyond the scope of this site (try codereview.stackexchange.com)
Your fight() method isn't saving the results of the subtraction, so nothing is changed. You would need to do something like this:
def fight(target, self):
target.nHealth -= self.nAttack
# check if target is dead now?
I might even recommend not imposing a modification on your target directly. It may be better if you can call an attack(power) on your target, and let it determine how much damage is done. You can then check if the target is dead yet. Ultimately I would think you would have some "dice" object that would determine the outcomes for you.
As for globals... just stop using them. It is a bad habit to have them unless you really have a good reason. Have functions that return results to the caller, which you then make use of:
def func(foo):
return 'bar'
You can however have a module of constants. These are a bunch of values that don't change for the life of the application. They are merely variables that provide common values. You might create a constants.py and have stuff like:
UP = "up"
DOWN = "down"
DEAD = 0
...
... And in your other modules you do:
from constants import *