Your belief that it is being reset is correct. Every variable has what is called a scope. This essentially determines where it is defined. Every time you enter that function it creates a new variable X, and then when it leaves that function it deletes it. In Python, the scope of a variable is determined by indentation (tab). So basically inside functions, loops, etc. One way to deal with this is to make the variable global (declare it at the top, the lowest indentation level), but this is bad practice since it can lead to name conflicts, especially with a name as common as X.
What you should do is make that variable a part of the class. This means the variable is a member of that class and thus can be used anywhere in that class as long as it has been created. In Terminal, this is in the AlgoStrategy class. To make a variable part of the class, you add self
to its definition, so it would become self.X
. If you aren’t familiar with classes I recommend reading more about them. Here is a little test to demonstrate.
This is effectively what you are doing now:
def not_persistent():
X = 0
# Do a bunch of stuff here
print (X)
X += 1
As you can see, it resets X every time the function is called, this happens every turn in the game.
In contrast, here is an example with the AlgoStrategy class where it will persist:
class AlgoSrategy(gamelib.AlgoCore):
def __init__(self):
# other inititalization stuff here
self.X = 0
def on_turn(self, turn_state):
game_state = gamelib.GameState(self.config, turn_state)
if not game_state.contains_stationary_unit([0,13]):
self.X += 1
# Do stuff with self.X
The key here is that you are declaring X as a member of the class AlgoStrategy
, which is why you use the .
to access it from self
. The idea is you could access X
from that class, and self
represents the current object of that class. So whenever you use X
inside the class, you must do self.X
and outside it would just be like accessing another objects member. So for an example of outside the class:
class TestClass:
def __init__(self):
self.X = 0
def increment(self):
self.X += 1
test = TestClass()
print (test.X)
test.increment()
print (test.X)