I have the following Code:
/**
* Calculates all correct Moves for Figure f which are possible
* @param f the Figure for which you want to check it's moves
* @return
*/
public ArrayList<Move> checkMoves(Figure f) {
ArrayList<Move> moves = this.expand(f.getLocation(), new ArrayList<Move>(), false, this.getPlayer(f.getOwner()));
// Fix the wrongly calculated moves
for(Move m : moves) {
moves = this.jumpFix(moves, m);
}
return moves;
}
/**
* Takes a look into all calculated moves and finds those which should be seen as one move, but are still
* considered to be more than one move (several jumps in one move)
*/
private ArrayList<Move> jumpFix(ArrayList<Move> moves, Move m) {
ArrayList<Move> consecutive = this.findConsecutiveMoves(moves, new ArrayList<Move>(), m);
if(consecutive.size() > 0) {
m.getTarget().setX(consecutive.get(consecutive.size() - 1).getTarget().getX());
m.getTarget().setY(consecutive.get(consecutive.size() - 1).getTarget().getY());
}
for(Move i : consecutive) {
moves.remove(i);
m.addStop(i.getTarget());
}
return moves;
}
/**
* Finds all consecutive moves to the given move m, that share their start and target cells
*/
public ArrayList<Move> findConsecutiveMoves(ArrayList<Move> moves, ArrayList<Move> deleteable, Move m) {
for(Move n : moves) {
if(n.getStart().equalTo(m.getTarget())) {
deleteable.add(n);
deleteable = this.findConsecutiveMoves(moves, deleteable, n);
}
}
return deleteable;
}
Explanation: - checkMoves calculates all possible Moves for given Figure f - After expand() calculated all possible moves, several of those "moves" might be sondered one move, if they are connected (Example: A Move is going from a to b. If we now have several Moves a -> b, b -> c, c -> d this would be the Move a -> d) - I need to remove all those little consecutive moves and set a -> b to a -> d - I am trying to iterate through the whole moves List and start findConsecutiveMoves for each m, checking if there are consecutive moves.
- I do get a StackOverflowError. I suppose my way of doing things is not good. How can i improve it?
- I fear I will get a java.util.ConcurrentModificationException in case the program finds consecutive moves, since I'm iterating over moves while changing it. How to avoid that?