Skip to content
Advertisement

Values don’t change as they should because of recursion depth

I am making checkers. I encountered quite a big problem. The code below describes cells king can move on. 1 cell is 100×100. He starts from (550, 50). This picture describes current_battlefield:

enter image description here

And this dict describes what moves AI will take

JavaScript

The king is a purple checker and he has to eat right now. So, about the actual problem. If you look carefully to the king_attack_moves you will get that code doesn’t find a way from cell with center at (250,750) to cells (550,450) and (650,350).

I got that the problem is enemy_positions. It doesn’t clear itself after each branch. But it doesn’t have to, because later I will use it, so it shold not be corrupted. This is the reason why I made temp_enemy_pos. But I stuck with it now.

I have been working for 1.5 days already and I still can’t understand the reason why temp_enemy_pos doesn’t go back to initial value, while it should be because of different recursion depths. So, what temp_enemy_pos actually should be

JavaScript

and what it is

JavaScript

I am sorry for all these troubles. Unfortunately, I’m a newbie so I cannot express it shorter. I hope, that at least I was able to make this understandable

Code:

JavaScript

Advertisement

Answer

This is a classic kind of bug. The problem is that you pass enemy_positions. Which means that the object is shared between the recursive call and the previous. So what happens in the recursive call is seen in the parent.

You either need to .copy() it, or else you need to manually fix it back to being the previous on the way out of the call. Of the two, .copy() is much more expensive but also simpler and more reliable.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement