I have written a JavaScript program that generates a solution to a NxN sliding tile puzzle. It finds a correct solution but when it comes to animating between the different puzzle instances to get to the solution things get messy. At first (3-4 steps) the tiles moves like they should but then some tiles start moving diagonally and above other tiles. The solution is finally reached but the inbetween animations goes wrong. Here is the code for my animation loop:
var steps = solution.length;
for (i=0; i<steps; i++) {
next = solution.pop();
// ANIMATE TILE
var delay = speed*i;
// sp is an array where the position (y, x) of the free spot is
var spA = current.spacePos;
var spB = next.spacePos;
var movingTile = current.box[spB[0]][spB[1]];
var leftOffset = size*(spA[1]-spB[1]);
var topOffset = size*(spA[0]-spB[0]);
var thisTile = $('#tile'+movingTile);
thisTile.delay(delay).animate({
opacity: 1.0,
top: "+=" + topOffset,
left: "+=" + leftOffset
}, speed);
// Update for next round
current = next;
};
If you want the timing of the next animation to exactly coincide with the finish of the previous animation (which you do), then you cannot use a
delay()to schedule the next animation. Instead, you HAVE to use the completion function from one animation to trigger the next animation. Only then will the timing be perfect, even after hundreds of consecutive animations.You could do that something like this: