Maybe this is a silly question, and there is probably a better way of doing it, but I’m looking for a way in python, to make sure my functions don’t run multiple times per turn.
So an example, I have 3 functions, mid_defense, left_defense, and right_defense. The issue is the algo calls these based on the amount of “attacks” on that side, so I’ll check the enemy path, based on the previous turn spawn locations, up to 5 previous turns, if there are no spawns in those 5 turns, it’s checks all possible paths, and finds the shortest, obviously this isn’t ideal because there are paths that are the same lengths, I’ve not had time to try and optimize that further. From that it decides to do mid, left or right defense, based on the number of attacks to that side. However, there are obviously some algo’s that deploy info units at different locations, so some can sneak through.
What I would like to do is once it deploys the main defense, I’d like it to check, what side had the next largest amounts of attack, so if mid is deployed, and there is still a certain number of cores left, to move left or right, obviously all of the deploy functions would need to have this, however that could lead to infinite loop, which I would like to avoid, so I’d like a way to mark if a function has been run previously. So each defense function would check to see if it has previously run, then if all of the firewall slots it uses are full, then check which has the second most attacks, and deploy that function. If it’s already been run I would like it to just stop there. so code might look something like this.
def deploy_right_defense(self, game_state): if deploy_right_defense.has_been_called == True: return deploy_right_defense.has_been_called = True if game_state.get_resource(game_state.CORES) > 15 and all_empty_pos < 1: left_attacks = self.get_left_attacks(game_state) mid_attacks = self.get_mid_attacks(game_state) if len(left_attacks) > len(mid_attacks): self.deploy_left_defense(game_state) elif len(left_attacks) < len(mid_attacks): self.deploy_mid_defense(game_state)
I found some stackoverflow posts about this one of the methods looked like this.
def self_aware_function(a, b):
self_aware_function.has_been_called = True
return a + b
if __name__ == '__main__': self_aware_function.has_been_called = False for i in range(2): if self_aware_function.has_been_called: print('function already called') else: print('function not called') self_aware_function(1, 2)
I was having some issues implementing this, however, I think that’s because I’m doing something wrong, the other ways I found that might work is mock or trace, so I guess I’m wondering if anyone else has done something like this and which way would be the most effective?
Sorry for the long winded first forum post.