Projects

Harry Potter Sorting Hat Quiz

Project Overview

This is a C++ implementation that sorts the user into a Hogwarts house depending on their responses to some questions. As I am still in the beginning of my journey I have not yet worked out how to get my webpage to run my C++ code. So even though I initially created this code on C++, I have rewritten (with the help of AI) the code to run using JavaScript so it can be completed here. If you want to see the complete C++ code then click here.

The concept of this quiz is from Harry Potter, if you want a preview of a house sorting please watch the video in the header.

Result

Method

The first thing that I needed to do was declare the variables for each house and all the possible answers.


    // Declare houses
    int gryffindor=0;
    int hufflepuff=0;
    int ravenclaw=0;
    int slytherin=0;

    //Declare answers
    int answer1;
    int answer2;
    int answer3;
    int answer4;
        

The next step in creating this quiz is to introduce the quiz to the user. Once they have been welcomed it was time to ask the first question and assign their answer to the answer1 variable.


    //User interaction
    std::cout << "The Sorting Hat Quiz!\n";
    //Question 1
    std::cout << "Q1) When I'm dead, I want people to remember me as:\n1) The Good\n2) The Great\n3) The Wise\n4) The Bold\nYour answer: ";
    std::cin >> answer1;
        

Each question followed the same process. Print the question and then asign their answer to the matching variable.

Now that the questions has been created, I had to write if conditionals that changes the score of each house depending on which answer the user gave. For this I used if, else if and else conditionals.


    //House score update
    if (answer1 == 1) {
        hufflepuff++;
    } else if (answer1 == 2) {
        slytherin++;
    } else if (answer1 == 3) {
        ravenclaw++;
    } else if (answer1 == 4) {
        gryffindor++;
    } else {
        std::cout << "Invalid input.\nYour answer: ";
        std::cin >> answer1;
    }
        

This process was repeated for each questions.

Finally, it was time to let the user know which house they were sorted into. To do this I used if conditionals to check which house had the highest score before printing the house to the console.


    //House reveal
    int max=0;
    std::string house;

    if (gryffindor > max) {  
        max = gryffindor;
        house = "Gryffindor"; 
    }

    if (hufflepuff > max) {
        max = hufflepuff;
        house = "Hufflepuff";
    }

    if (ravenclaw > max) {
        max = ravenclaw;
        house = "Ravenclaw";
    }

    if (slytherin > max) {
        max = slytherin;
        house = "Slytherin";
    }

    std::cout << house << "!\n";