Use animation to show how the recursive solution to the Tower of Hanoi problem works in C#

This example is similar to the example Use Stacks to recursively solve the Tower of Hanoi problem in C# except it uses the following AnimateMovement method to show how disks move from one peg to another.
// Move the moving disk to this location.
private void AnimateMovement(int end_x, int end_y)
{
int start_x = MovingDiskRect.X;
int start_y = MovingDiskRect.Y;

const int pixels_per_second = 400;
float dx = end_x - MovingDiskRect.X;
float dy = end_y - MovingDiskRect.Y;
float dist = (float)Math.Sqrt(dx * dx + dy * dy);

// Calculate distance moved per second.
dx = pixels_per_second * dx / dist;
dy = pixels_per_second * dy / dist;

// See how long the total move will take.
float seconds = dist / pixels_per_second;
DateTime start_time = DateTime.Now;

// Start moving.
for (; ; )
{
// Redraw.
this.Refresh();

// Wait a little while.
System.Threading.Thread.Sleep(10);

// See how much time has passed.
TimeSpan elapsed = DateTime.Now - start_time;
if (elapsed.TotalSeconds > seconds) break;

// Update the rectangle's position.
MovingDiskRect.X = (int)(start_x + elapsed.TotalSeconds * dx);
MovingDiskRect.Y = (int)(start_y + elapsed.TotalSeconds * dy);
}

MovingDiskRect.X = end_x;
MovingDiskRect.Y = end_y;
}

The code calculates the number of pixels per second it should add to the moving rectangle's X and Y coordinates. It then enters a loop where it adds the needed number of pixels, depending on how much time has elapsed.

Download the example for additional details.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.