Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.7 kB
1
Indexable
<?php
session_start();

// Define the maximum stage (you can increase this to add more levels)
$max_stage = 5;

// Set the target range for each stage
$stage_ranges = [
    1 => 10,  // Stage 1: Guess between 1-10
    2 => 20,  // Stage 2: Guess between 1-20
    3 => 30,  // Stage 3: Guess between 1-30
    4 => 50,  // Stage 4: Guess between 1-50
    5 => 100  // Stage 5: Guess between 1-100
];

// Initialize the current stage if not set
if (!isset($_SESSION['current_stage'])) {
    $_SESSION['current_stage'] = 1;
}

// Initialize the target number for the current stage
if (!isset($_SESSION['target_number'])) {
    $range = $stage_ranges[$_SESSION['current_stage']];
    $_SESSION['target_number'] = rand(1, $range);
}

// Initialize guess count if not set
if (!isset($_SESSION['guess_count'])) {
    $_SESSION['guess_count'] = 0;
}

// Check if a guess has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $guess = intval($_POST['guess']);
    $_SESSION['guess_count']++;

    // Check the guess against the target number
    if ($guess < $_SESSION['target_number']) {
        $message = "Too low!";
    } elseif ($guess > $_SESSION['target_number']) {
        $message = "Too high!";
    } else {
        $message = "Correct! You've passed stage " . $_SESSION['current_stage'] . " in " . $_SESSION['guess_count'] . " tries.";

        // Move to the next stage
        $_SESSION['current_stage']++;

        if ($_SESSION['current_stage'] > $max_stage) {
            // Game completed
            $message .= " Congratulations, you've completed all stages!";
            session_destroy();  // Reset the game
        } else {
            // Prepare the next stage
            $range = $stage_ranges[$_SESSION['current_stage']];
            $_SESSION['target_number'] = rand(1, $range);
            $_SESSION['guess_count'] = 0;
            $message .= " Now, try stage " . $_SESSION['current_stage'] . ".";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Number Guessing Game with Stages</title>
</head>
<body>
    <h1>Number Guessing Game</h1>

    <p>Stage <?php echo $_SESSION['current_stage']; ?>: Guess the number between 1 and <?php echo $stage_ranges[$_SESSION['current_stage']]; ?>.</p>

    <?php
    if (isset($message)) {
        echo "<p>$message</p>";
    }
    ?>

    <form method="post" action="">
        <label for="guess">Enter your guess: </label>
        <input type="number" id="guess" name="guess" min="1" max="<?php echo $stage_ranges[$_SESSION['current_stage']]; ?>" required>
        <input type="submit" value="Submit Guess">
    </form>
</body>
</html>
Leave a Comment