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

1 Answer

0 votes
// 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. 

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function contains_seven(num) {
    return num.toString().includes("7");
}

function is_boom(num) {
    return num % 7 === 0 || contains_seven(num);
}

function ask(question) {
    return new Promise(resolve => rl.question(question, answer => resolve(answer.trim())));
}

function process_turn(expected, input) {
    const lower = input.toLowerCase();
    const shouldBoom = is_boom(expected);

    if (shouldBoom) {
        if (lower !== "boom") {
            console.log(`${input} (should be Boom)`);
            console.log("YOU LOSE!");
            return false;
        }
    } else {
        if (lower === "boom") {
            console.log(`Wrong move! It was ${expected}`);
            console.log("YOU LOSE!");
            return false;
        }

        const value = Number(input);
        if (!Number.isInteger(value) || value !== expected) {
            console.log(`Wrong move! It was ${expected}`);
            console.log("YOU LOSE!");
            return false;
        }
    }

    return true;
}

async function run_game() {
    const startInput = await ask("Enter a number from which you want to start the game (-1 to exit): ");

    const startNum = Number(startInput);
    if (!Number.isInteger(startNum) || startNum === -1) {
        rl.close();
        return;
    }

    let current = startNum;

    while (true) {
        const input = await ask("Enter a number (or Boom): ");

        if (input === "-1") {
            console.log("Game Over!");
            break;
        }

        if (!process_turn(current, input)) {
            break;
        }

        current++;
    }

    rl.close();
}

run_game();



/*
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 15 by avibootz
edited Mar 16 by avibootz
...