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

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. 

function contains_seven(int $num): bool {
    return strpos((string)$num, '7') !== false;
}

function is_boom(int $num): bool {
    return ($num % 7 === 0) || contains_seven($num);
}

function get_user_input(): string {
    echo "Enter a number (or Boom): ";
    return trim(fgets(STDIN));
}

function process_turn(int $expected, string $input): bool {
    $lower = strtolower($input);
    $shouldBoom = is_boom($expected);

    if ($shouldBoom) {
        if ($lower !== "boom") {
            echo "$input (should be Boom)\n";
            echo "YOU LOSE!\n";
            return false;
        }
    } else {
        if ($lower === "boom") {
            echo "Wrong move! It was $expected\n";
            echo "YOU LOSE!\n";
            return false;
        }

        if (!ctype_digit($input) || (int)$input !== $expected) {
            echo "Wrong move! It was $expected\n";
            echo "YOU LOSE!\n";
            return false;
        }
    }

    return true;
}

function run_game(): void {
    echo "Enter a number from which you want to start the game (-1 to exit): ";
    $startInput = trim(fgets(STDIN));

    if (!ctype_digit(ltrim($startInput, '-'))) {
        return;
    }

    $current = (int)$startInput;
    if ($current === -1) {
        return;
    }

    while (true) {
        $input = get_user_input();

        if ($input === "-1") {
            echo "Game Over!\n";
            break;
        }

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

        $current++;
    }
}

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
...