How to write the 7 Boom game. If a number is divided by 7 or includes the digit 7, the user writes Boom in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>

// 7 Boom game. The user enters a number he wants to start the game, 
// (-1 to end the game, or lost), then the user enters numbers, from the number he entered
// If the current number is divisible by 7, or one of its digits is 7, 
// And the user did not write the word 'Boom', the user loses. 

// Function to check if the number contains the digit '7'
bool containsSeven(int num) {
    std::string s = std::to_string(num);
    
    return s.find('7') != std::string::npos;
}

// Function to check if the number is a "Boom" number
bool isBoom(int num) {
    return (num % 7 == 0 || containsSeven(num));
}

int main() {
    int currentNum;
    std::string userInput;

    std::cout << "Enter a number from which you want to start the game (-1 to exit): ";
    std::cin >> currentNum;

    if (currentNum == -1) return 0;

    while (true) {
        std::cout << "Enter a number (or Boom): ";
        std::cin >> userInput;

        // Exit condition
        if (userInput == "-1") {
            std::cout << "Game Over!" << std::endl;
            break;
        }

        // Logic Check
        bool shouldBeBoom = isBoom(currentNum);
        
        // Convert input to lowercase to handle "boom", "BOOM", or "Boom"
        std::string inputLower = userInput;
        for (char &c : inputLower) c = tolower(c); // Manual lower if needed, but 'Boom' is standard

        if (shouldBeBoom) {
            if (userInput != "Boom" && userInput != "boom") {
                std::cout << userInput << " (should be Boom)" << std::endl;
                std::cout << "YOU LOSE!" << std::endl;
                break;
            }
        } else {
            // If it shouldn't be boom, the user must provide the correct next number
            if (userInput == "Boom" || userInput == "boom" || stoi(userInput) != currentNum) {
                std::cout << "Wrong move! It was " << currentNum << std::endl;
                std::cout << "YOU LOSE!" << std::endl;
                break;
            }
        }

        currentNum++; // Move to the next number for the next round
    }

    return 0;
}


/*
run:

Enter a number from which you want to start the game (-1 to exit): 6
Enter a number (or Boom): 6
Enter a number (or Boom): Boom
Enter a number (or Boom): 8
Enter a number (or Boom): 9
Enter a number (or Boom): 10
Enter a number (or Boom): 11
Enter a number (or Boom): 12
Enter a number (or Boom): 13
Enter a number (or Boom): Boom
Enter a number (or Boom): 15
Enter a number (or Boom): 16
Enter a number (or Boom): Boom
Enter a number (or Boom): 18
Enter a number (or Boom): 19
Enter a number (or Boom): 20
Enter a number (or Boom): 21
21 (should be Boom)
YOU LOSE!

*/



 



answered Mar 14 by avibootz
...