I am creating a little game where you need to move troops on a map. To detect if a movement can be done I must verify if there is a way between 2 squares.
So, recursively I start from one square and take the four squares (above, below, left and right) and following conditions I repeat the test recursively since I get only dead-ends or the destination square. All the squares must be under the control of the player.
There is my recursive code implement in my class Case :
public boolean isContiguJoueur(Case case_origine, Case case_destination, Case[] cases) {
boolean haut_true=false, droite_true=false, bas_true=false, gauche_true=false;
// Above
if(this.haut!=null) {
if(haut.joueur==this.joueur && this.haut!=case_origine) {
if(this.haut==case_destination) {
return true;
}
haut_true=haut.isContiguJoueur(this,case_destination, cases);
}
}
// ...
// Same code than Above, only variables names change
// ...
return haut_true||droite_true||bas_true||gauche_true;
}
- The class name for a square : Case
- The map data : Case[] cases
- The player id : joueur
- The case above : haut
That code work very well on little map (~ 50 to 100 squares). But i got this on bigger ones :
08-25 11:26:31.912: E/AndroidRuntime(5497): FATAL EXCEPTION: main
08-25 11:26:31.912: E/AndroidRuntime(5497): java.lang.StackOverflowError
08-25 11:26:31.912: E/AndroidRuntime(5497): at mypackage.isContiguJoueur(Case.java:xxx)
... x 100
Sorry for my bad english and thanks for future help ! 🙂
Edit : I forgot. To avoid mass useless recursive tests I already did this :
if(this.droite!=null && !haut_true) {
// ...
if(this.bas!=null && !haut_true && !droite_true) {
// ...
if(this.gauche!=null && !haut_true && !droite_true && !bas_true) {
// ...
Your problem is that your paths are exponential with the number of squares on the board. The stack overflow error implies you are recursing too many times: each recursion takes up stack space, and you are running out of it (Chaque recursion utilise l’espace sur le pile, et il y’en a trop, alors il n y a plus d’espace – et c’est une dépassement de pile).
You could do this iteratively, (sans recursion) and not run into this problem. But bear in mind the number of possible paths still remains very large, and this can be CPU consuming.
Hope This Helps,
TG