|
|
Title | Use animation to show how the recursive solution to the Tower of Hanoi problem works in Visual Basic .NET |
Description | This example shows how to use animation to show how the recursive solution to the Tower of Hanoi problem works in Visual Basic .NET. |
Keywords | algorithms, recursion, Tower of Hanoi, games, puzzles, Visual Basic .NET, VB.NET |
Categories | Algorithms, Multimedia |
|
|
This example is similar to the example Use Stacks to recursively solve the Tower of Hanoi problem in Visual Basic .NET 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 Sub AnimateMovement(ByVal end_x As Integer, ByVal _
end_y As Integer)
Dim start_x As Integer = MovingDiskRect.X
Dim start_y As Integer = MovingDiskRect.Y
Const pixels_per_second As Integer = 400
Dim dx As Single = end_x - MovingDiskRect.X
Dim dy As Single = end_y - MovingDiskRect.Y
Dim dist As Single = CSng(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.
Dim seconds As Single = dist / pixels_per_second
Dim start_time As Date = Date.Now
' Start moving.
Do
' Redraw.
Me.Refresh()
' Wait a little while.
System.Threading.Thread.Sleep(10)
' See how much time has passed.
Dim elapsed As TimeSpan = DateTime.Now - start_time
If (elapsed.TotalSeconds > seconds) Then Exit Do
' Update the rectangle's position.
MovingDiskRect.X = CInt(start_x + _
elapsed.TotalSeconds * dx)
MovingDiskRect.Y = CInt(start_y + _
elapsed.TotalSeconds * dy)
Loop
MovingDiskRect.X = end_x
MovingDiskRect.Y = end_y
End Sub
|
|
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.
|
|
|
|
|
|
|
|
|