Operation of the Application Implementing the Game „Towers of Hanoi“ with Voice Accompaniment

The core of the application’s operation is a recursive method that moves a tower from one stick to another. Let’s assume that a tower consisting of n disks needs to be moved from stick 1 to stick 3. At first glance, the implementation of such a method seems complicated. However, we can use the following approach:

  1. Move the sub-tower consisting of the top n – 1 disks from stick 1 to stick 2,
  2. Move the remaining bottom disk from stick 1 to stick 3,
  3. Move the sub-tower temporarily placed on stick 2 to stick 3.

To move the sub-tower with n – 1 disks, we use the same approach, this time moving a sub-tower with n – 2 disks and the bottom disk.

            Below is the code for the method:

private async Task Go(ushort aFromTower, ushort aToTower, ushort aTemporaryTower, ushort aDisks)

{

    while (!mUserMakesGo)

    {

        await Task.Delay(33);

    } // while

    if (aDisks > 1)

    {

        await Go(aFromTower, aTemporaryTower, aToTower, (ushort)(aDisks – 1));

        await Go(aFromTower, aToTower, aTemporaryTower, 1);

        await Go(aTemporaryTower, aToTower, aFromTower, (ushort)(aDisks – 1));

    }

    else

    {

        mUserMakesGo = false;

        ushort disk = mComputerTowers[aFromTower].RemoveDisk();

        mComputerTowers[aFromTower].Draw();

        mComputerTowers[aToTower].AddDisk(disk);

        mComputerMoves++;

        mSpeechText.Add($“The computer moved disk {disk} from tower {aFromTower + 1} to tower {aToTower + 1}.“);

        if (mComputerTowers[2].DisksNumber == mDisks)

        {

            if (mUserTowers[2].DisksNumber == mDisks)

            {

                mSpeechText.Add(„Draw“);

                await MessageDialog(„Game Over“, „Draw.“);

            }

            else

            {

                mSpeechText.Add(„The computer is the winner!“);

                await MessageDialog(„Game Over“, „The computer is the winner.“);

            }

            Application.Current.Exit();

        }

    }

} // Go

The voice accompaniment and visualization of the user’s and computer’s towers are implemented by the respective classes.

wpChatIcon
wpChatIcon
WordPress Appliance - Powered by TurnKey Linux