Question

I have solved an 8 puzzle using a BFS algorithm and stored the needed moves into an array and then converted those numbers into either 0 to say the blank space needs to move up or 1 down or 2 left or 3 right. I have no idea how i would animate the 8 squares solving the puzzle with my corresponding moves from the BFS. i know to use the Timer and how to do animation in general just not how to sequentially animate the correct square at the correct time. They always need to move 80 pixels in any given direction. if someone could point me in the right direction i would be grateful.

Was it helpful?

Solution

I don't get how you can write something to solve this puzzle, but then not know how to maintain a simple counter to animate a value.

Let's say you have a frequency F which is moves per second, and time T which is the number of seconds since the animation began.

The idea, then, is that move M begins at T*F*M and has a duration of 1 (or less, if you want pauses between moves).

Now, you just need an interpolation function to blend the values. Linear interpolation (LERP) is easiest, but you might want a spline function to accelerate/decelerate at the end points. However you do it, the function simply takes a beginning point, an end point, and a relative position t which is between 0 and 1.

double blend( double from, double to, double t )
{
    // linear interp:
    return from * (t-1.0) + to * t;
}

So, you just calculate t by computing the fractional part fmod(T*F*M, 1.0). If you have a duration of less than 1, you do not change the 1.0 in that fmod call. You simply clamp it to your duration D and then divide by D.

OTHER TIPS

When I need to do something like this, I use a variable to keep the remaining time of the animation of the movement. And to know wich piece you want to move to a side, I recommend you to use a stack with a struct like this:

struct commands{
    int piece;
    int direction;
    struct commands next;
    };

First of all, you stack all the commands you need to solve the puzzle, then, when animating, you reset the variable keeping the remaining time to 80 and inside a time function:

void move_piece(int a){
    //Move the piece 1 pixel to the side you want
    switch(stack->direction){
        //Move the piece to x+1
        case 0:
            piece[stack->piece].x++;
            break;
        //Move the piece to y+1
        case 1:
            piece[stack->piece].y++;
            break;
        case 2:...
        ...
        }
    time--;
    if(time==0){
        //The piece is in it's place
        //Go to the next piece
        time=80;
        }
    glutTimerFunc(20, move_piece, 0); //Change 20 to change the speed of the animation
    }

It's just an example of how you could do it. I don't know how you'r storing the piece's position, in the example I suppose that was in a struct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top