I am attempting to insert enemies to my game, this one is called punching_bag
, and I have made another object that is inside of punching_bag
that is under the DangerZone
class.
I want the DangerZone
class to be next to the punching_bag
. Hence the punching_bag.x - 64
. But I am running into problems, because punching_bag.x
doesn't exist yet I can not refer to it
Enemy
Class
class Enemy:
def __init__(self, sprite, x, y, health, attack):
self.sprite = sprite
self.x = x
self.y = y
self.health = health
self.attack = attack
DangerZone
Class
class DangerZone:
def __init__(self, sprite, x, y, damage):
self.sprite = sprite
self.x = x
self.y = y
self.damage = damage
punching_bag
Object
punch_bag = Enemy(sprite junk, 640, 0, 10,
DangerZone(sprite junk, punch_bag.x - 64, punch_bag.y, 1)
)
CodePudding user response:
You are correct. You are attempting to reference an attribute of an object that doesn't yet exist. But when it does exist, you know its x
attribute is going to have the value 640
, and y
will have 0
, right? So why not just do:
punch_bag = Enemy(sprite junk, 640, 0, 10,
DangerZone(sprite junk, 640 - 64, 0, 1)
)
You could wrap this in a factory function that took an x
and y
to be clearer what those values are and to make sure that the two uses of each provide the same value. So maybe:
class Enemy:
def __init__(self, sprite, x, y, health, attack):
self.sprite = sprite
self.x = x
self.y = y
self.health = health
self.attack = attack
@staticmethod
def create_with_danger_zone(sprite_junk, x, y, health, attack):
return Enemy(sprite_junk, x, y, health,
DangerZone(sprite_junk, x - 64, y, 1))
punch_bag = Enemy.create_with_danger_zone(sprite_junk, 640, 0, 10)