Possible solution :

Here’s a solution to the “Guess the Number” game in PHP:

function guessTheNumber($min, $max, $maxAttempts) {
  // Generate a random number between the specified range
  $number = rand($min, $max);

  // Initialize the number of attempts and a flag to indicate if the game is over
  $attempts = 0;
  $gameOver = false;

  // Loop until the game is over or the player runs out of attempts
  while (!$gameOver && $attempts < $maxAttempts) {
    // Prompt the player for a guess
    $guess = readline("Guess a number between $min and $max: ");

    // Validate the guess
    if (!is_numeric($guess) || $guess < $min || $guess > $max) {
      echo "Invalid guess. Please enter a number between $min and $max.\n";
      continue;
    }

    // Increment the number of attempts
    $attempts++;

    // Check if the guess is correct
    if ($guess == $number) {
      echo "You win!\n";
      $gameOver = true;
    } else if ($guess < $number) {
      echo "Too low. ";
    } else {
      echo "Too high. ";
    }

    // Display the number of attempts remaining
    $remainingAttempts = $maxAttempts - $attempts;
    if ($remainingAttempts > 0) {
      echo "You have $remainingAttempts attempt(s) remaining.\n";
    } else {
      echo "You have no attempts remaining.\n";
    }
  }

  // If the game is not over, the player has lost
  if (!$gameOver) {
    echo "You lose! The number was $number.\n";
  }
}

The function starts by generating a random number between the specified range using the rand() function. It then initializes the number of attempts and a flag to indicate if the game is over.

The function enters a loop that continues until the game is over or the player runs out of attempts. On each iteration of the loop, the function prompts the player for a guess, validates the guess, increments the number of attempts, checks if the guess is correct, and displays the number of attempts remaining. If the player runs out of attempts without guessing the number correctly, the game ends and the player loses.

If the game is not over after the loop, the player has lost and the function displays the correct number.

LEAVE A REPLY

Please enter your comment!
Please enter your name here