How to Create a Hanoi Tower Game in C++


What is Hanoi Tower game

The Hanoi Tower game is a classic puzzle game that has been around for centuries. It involves moving a stack of disks from one peg to another, with the constraint that a larger disk cannot be placed on top of a smaller disk. The game is named after the Hanoi Tower in Vietnam, where the game is said to have originated. In this article, we will learn how to create a Hanoi Tower game in C++.


Understanding the Hanoi Tower Game

Before we begin coding, it is important to understand the basic rules of the Hanoi Tower game. The game starts with a stack of disks on one peg, and the goal is to move the entire stack to another peg, following these rules:


   • Only one disk can be moved at a time.


   • A disk can only be placed on top of a larger disk or an empty peg


The game can be represented visually using three pegs, labeled A, B, and C, and a stack of disks of different sizes. The game starts with the disks on peg A, and the goal is to move them to peg C, using peg B as a temporary holding area.


Coding the Hanoi Tower Game

Now that we understand the basic rules of the Hanoi Tower game, we can start coding it in C++. The first step is to define the number of disks in the game. In this example, we will use three disks.



int n = 3;

Next, we will create a recursive function to move the disks from one peg to another. This function will take three arguments: the number of disks to move, the peg to move from, and the peg to move to.



void hanoi(int n, char from_peg, char to_peg, char aux_peg) {
    if (n == 0) {
        return;
    }
    hanoi(n - 1, from_peg, aux_peg, to_peg);
    cout << "Move disk " << n << " from peg " << from_peg << " to peg " << to_peg << endl;
    hanoi(n - 1, aux_peg, to_peg, from_peg);
}

In this function, we first check if there are no disks to move (i.e., n = 0). If this is the case, we simply return. If there are disks to move, we first move the top n-1 disks from the from_peg to the aux_peg using the to_peg as a temporary holding area. We then move the nth disk from the from_peg to the to_peg. Finally, we move the remaining n-1 disks from the aux_peg to the to_peg using the from_peg as a temporary holding area.


Finally, we call the hanoi() function with the initial values to start the game.



int main() {
    hanoi(n, 'A', 'C', 'B');
    return 0;
}

Output :



Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

Note that this is just one way to code the Hanoi Tower game in C++, and there are many other ways to approach the problem. You can also add additional features to the game such as a graphical user interface or a scoring system.


As you can see, the Hanoi Tower game is a great example of how a simple problem can be solved using recursion. The key to solving the problem is to break it down into smaller subproblems, and to think about the problem in a recursive way. By understanding the basic rules of the game and using recursion, we were able to create a simple Hanoi Tower game in C++.


Graphical interface:

A graphical user interface (GUI) can be added to the Hanoi Tower game to make it more visually appealing and user-friendly. There are many libraries available in C++ for creating a GUI, such as Qt, wxWidgets, and SDL. In this example, we will use the Qt library to create the GUI.


First, you need to download and install the Qt library. Once the library is installed, you can use the Qt Creator application to create a new project and design the GUI.


Here is an example of how the GUI of Hanoi Tower game can be designed using Qt:



#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // Create the graphics view
    QGraphicsView view;
    view.setRenderHint(QPainter::Antialiasing);
    view.setRenderHint(QPainter::SmoothPixmapTransform);
    view.setRenderHint(QPainter::TextAntialiasing);
    view.setRenderHint(QPainter::HighQualityAntialiasing);

    // Create the graphics scene
    QGraphicsScene scene;
    scene.setSceneRect(0, 0, 600, 400);
    view.setScene(&scene);

    // Create the pegs
    QGraphicsRectItem *pegA = scene.addRect(50, 150, 20, 200);
    QGraphicsRectItem *pegB = scene.addRect(250, 150, 20, 200);
    QGraphicsRectItem *pegC = scene.addRect(450, 150, 20, 200);

    // Create the disks
    QGraphicsRectItem *disk1 = scene.addRect(65, 250, 30, 40);
    QGraphicsRectItem *disk2 = scene.addRect(65, 210, 60, 40);
    QGraphicsRectItem *disk3 = scene.addRect(65, 170, 90, 40);

    // Create the labels
    QGraphicsTextItem *labelA = scene.addText("A");
    labelA->setPos(35, 350);
    QGraphicsTextItem *labelB = scene.addText("B");
    labelB->setPos(235, 350);
    QGraphicsTextItem *labelC = scene.addText("C");
    labelC->setPos(435, 350);

    // Show the view
    view.show();

    return app.exec();
}

This code will create a window with three pegs labeled A, B, and C, and three disks stacked on peg A. The pegs are represented by rectangles, and the disks are represented by smaller rectangles stacked on top of each other. The labels are created using QGraphicsTextItem, and their positions are set using the setPos() function.


You can now use the hanoi() function from the previous example and call it inside the QApplication event loop, to move the disks according to the rules of the game. You can also add additional features such as sound effects, animations, or a scoring system.


It's important to note that this is a basic example of how to create a GUI for the Hanoi Tower game using the Qt library, and there are many other ways to improve the design and functionality of the GUI. Additionally, you can also use other libraries such as wxWidgets or SDL to create the GUI. The important thing is to understand the basic principles of creating a GUI in C++ and how to integrate it with the logic of the Hanoi Tower game.


In conclusion, adding a graphical user interface to the Hanoi Tower game in C++ can greatly enhance the user experience and make the game more visually appealing. By using a library such as Qt, you can easily create a GUI that displays the game board and the movement of the disks. It's also worth mentioning that you can use other libraries such as wxWidgets or SDL to create the GUI and you can use the hanoi() function from the previous example and call it inside the QApplication event loop, to move the disks according to the rules of the game.


Extending the game with the scoreboard:

A scoreboard can be added to the Hanoi Tower game to keep track of the number of moves made by the player and to display the player's score. The scoreboard can be implemented in a number of ways, such as displaying the number of moves on the GUI or writing the score to a file.


Here's an example of how a scoreboard can be implemented using a simple counter and displayed on the GUI using a QGraphicsTextItem:



#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // Create the graphics view
    QGraphicsView view;
    view.setRenderHint(QPainter::Antialiasing);
    view.setRenderHint(QPainter::SmoothPixmapTransform);
    view.setRenderHint(QPainter::TextAntialiasing);
    view.setRenderHint(QPainter::HighQualityAntialiasing);

    // Create the graphics scene
    QGraphicsScene scene;
    scene.setSceneRect(0, 0, 600, 400);
    view.setScene(&scene);

    // Create the pegs
    QGraphicsRectItem *pegA = scene.addRect(50, 150, 20, 200);
    QGraphicsRectItem *pegB = scene.addRect(250, 150, 20, 200);
    QGraphicsRectItem *pegC = scene.addRect(450, 150, 20, 200);

    // Create the disks
    QGraphicsRectItem *disk1 = scene.addRect(65, 250, 30, 40);
    QGraphicsRectItem *disk2 = scene.addRect(65, 210, 60, 40);
    QGraphicsRectItem *disk3 = scene.addRect(65, 170, 90, 40);

    // Create the labels
    QGraphicsTextItem *labelA = scene.addText("A");
    labelA->setPos(35, 350);
    QGraphicsTextItem *labelB = scene.addText("B");
    labelB->setPos(235, 350);
    QGraphicsTextItem *labelC = scene.addText("C");
    labelC->setPos(435, 350);

    // Create the scoreboard
    int moveCounter = 0;
    QGraphicsTextItem *scoreboard = scene.addText("Moves: 0");
    scoreboard->setPos(10, 10);

    // Show the view
    view.show();

    //Move the disks
    hanoi(n, 'A', 'C', 'B', moveCounter, scoreboard);

    return app.exec();
}

void hanoi(int n, char from_peg, char to_peg, char aux_peg, int &moveCounter, QGraphicsTextItem *scoreboard) {
    if (n == 0) {
        return;
    }
    hanoi(n - 1, from_peg, aux_peg, to_peg, moveCounter, scoreboard);
    cout << "Move disk " << n << " from peg " << from_peg << " to peg " << to_peg << endl;
    moveCounter++;
    scoreboard->setPlainText(QString("Moves: %1").arg(moveCounter));
hanoi(n - 1, aux_peg, to_peg, from_peg, moveCounter, scoreboard);
}

In this example, a variable "moveCounter" is defined and initialized to 0 and a QGraphicsTextItem is created and positioned on the GUI to display the score. The hanoi() function is modified to take an additional argument, a reference to the moveCounter variable and a pointer to the scoreboard, as well as updating the scoreboard every time a move is made by incrementing the moveCounter variable and updating the text on the scoreboard with the new value.


This is just one way of implementing a scoreboard, you can also use other ways such as writing the score to a file or displaying it on a separate window. Additionally, you can also add other functionality such as displaying the time taken to complete the game, or providing different levels of difficulty to make the game more challenging.


In conclusion, adding a scoreboard to the Hanoi Tower game in C++ can provide an additional level of challenge and make the game more engaging for the player. The example code provided in this article is a basic implementation of a scoreboard that can be easily modified to suit your needs and to make the game more interesting.


Adding a leaderboard and storing it locally:

A leaderboard is a feature that allows players to compare their scores with other players. It can be implemented in a number of ways, such as storing the scores in a database or in a file. In this example, we will use a file to store the scores and create a function to read and display the leaderboard.


To start, we'll create a file to store the scores. In this example, we will use a text file called "leaderboard.txt". Each line of the file will contain a player's name and their score, separated by a comma.



void writeToLeaderboard(string name, int score) {
    ofstream leaderboardFile("leaderboard.txt", ios::app);
    leaderboardFile << name << "," << score << endl;
    leaderboardFile.close();
}

This function will take a player's name and score as arguments and write it to the leaderboard file. The "ios::app" flag is used to open the file in append mode, so that new scores will be added to the end of the file without overwriting the existing scores.


Next, we'll create a function to read the leaderboard file and display the top 10 scores.



void displayLeaderboard() {
    ifstream leaderboardFile("leaderboard.txt");
    string leaderboardData[10][2];
    int i = 0;
    while (getline(leaderboardFile, leaderboardData[i][0], ',') && i < 10) {
        getline(leaderboardFile, leaderboardData[i][1]);
        i++;
    }
    leaderboardFile.close();

    cout << "Name" << "\t\t" << "Score" << endl;
    for (int j = 0; j < i; j++) {
        cout << leaderboardData[j][0] << "\t\t" << leaderboardData[j][1] << endl;
    }
}

This function reads the leaderboard file and stores the player's name and score in a 2D array called leaderboardData. The while loop will read the file until it reaches the end of the file or until it has read 10 lines (or fewer if there are not 10 scores in the file yet). Then it will display the names and scores stored in the leaderboardData array.


In the game, you should call the writeToLeaderboard function when the game is over and pass the player's name and score as arguments, and also you can add a button to call the displayLeaderboard function to show the leaderboard.


It's worth noting that this is a basic example of how to create a leaderboard for the Hanoi Tower game in C++, and there are many other ways to implement a leaderboard feature. You could also use a database to store the scores, which would allow for more advanced functionality such as sorting the scores by different criteria, searching for specific scores, or displaying the scores in a graphical format.


In conclusion, adding a leaderboard feature to the Hanoi Tower game in C++ can provide an additional level of challenge and engagement for the players, allowing them to compare their scores with other players. The example code provided in this article is a basic implementation of a leaderboard that can be easily modified to suit your needs and to make the game more interesting.


Conslusion:


Now you can improve it with additional custom features like login page, storing the leaderboard in the database and sharing your scores over social networks, that way you can compete with your friends in that old,but gold puzzle game.
Happy coding!


Admin

Read next: