I have two instances of a class that compete in a simulation where they try to shoot at each other. The class contains a position variable and a target variable. The second instance's target variable references the first instance's position object, and vice-versa.
I have a chicken-and-egg problem when creating the two instances, and when trying to bind the references after instantiating, they don't update properly
This is a simplified version of my code:
class Thing():
def __init__(self, position, target):
self.position = position
self.target = target
def move(self):
self.position += 10
## thing1 = Thing(position = 0, target = thing2.position) # Ideally this line would work...
thing1 = Thing(position = 0, target = 0)
thing2 = Thing(position = 100, target = thing1.position)
print(thing1.target)
thing1.target = thing2.position
print(thing1.target)
thing2.move()
print(thing1.target)
The output I get is 0,100,100, and the output I want is 0,100,110.
I think there are two parts to your question: How to I get my references to another object's position to stay synced up, and how do you initialize objects that reference each other in a cycle.
For the first part, I'd suggest a slightly simpler approach that the other answers: Don't reference the target position directly, target the Thing
. You can get the position via self.target.position
(or the equivalent) whenever you need it.
For the second part, you need some way to set up the reference cycle. The simplest approach is to start the way you have so far, initializing one object without a reference to its target, and then passing a reference to this first object to the second object. Then in another step, give a reference to the second object to the first. You're kind of doing this amid your print
calls where you do thing1.target = thing2.position
, but because you're referencing the position directly, you don't see updates.
I'd solve both problems like this:
class Thing():
def __init__(self, position, target=None): # target is now optional
self.position = position
self.target = target
def move(self):
self.position += 10
thing1 = Thing(0) # no target passed, so it defaults to None (for now)
thing2 = Thing(100, thing1) # initialize thing 2 to immediately target thing1
thing1.target = thing2 # update the target of thing1, now that thing2 exists
print(thing1.target.position) # get thing2's position via thing1's target reference
thing2.move()
print(thing1.target.position)