Possible solution

Here’s a possible solution to the “Hangman” game in PHP:

function hangman($words) {
  // Select a random word from the array
  $word = $words[array_rand($words)];

  // Initialize the game state
  $letters = str_split($word);
  $underscores = array_fill(0, count($letters), '_');
  $incorrectGuesses = 0;
  $maxIncorrectGuesses = 6;

  // Loop until the player wins or loses
  while ($incorrectGuesses < $maxIncorrectGuesses && in_array('_', $underscores)) {
    // Display the current game state
    echo "Word: " . implode(' ', $underscores) . "\n";
    echo "Incorrect guesses: $incorrectGuesses/$maxIncorrectGuesses\n";

    // Prompt the player for a guess
    $guess = readline("Guess a letter: ");

    // Validate the guess
    if (strlen($guess) != 1 || !ctype_alpha($guess)) {
      echo "Invalid guess. Please enter a single letter.\n";
      continue;
    }

    // Check if the guess is correct
    $correctGuess = false;
    foreach ($letters as $i => $letter) {
      if ($letter == $guess) {
        $underscores[$i] = $letter;
        $correctGuess = true;
      }
    }

    if ($correctGuess) {
      echo "Correct!\n";
    } else {
      $incorrectGuesses++;
      echo "Incorrect.\n";
    }
  }
}

The function begins by selecting a random word from the array using the array_rand() function. It then initializes the game state, including an array of underscores to represent each letter of the word, a counter for the number of incorrect guesses, and a maximum number of incorrect guesses.

The function enters a loop that continues until the player either correctly guesses the word or the hangman figure is complete. On each iteration of the loop, the function displays the current game state, prompts the player for a guess, validates the guess, and updates the game state based on the guess. If the player makes an incorrect guess, the function increments the incorrect guess counter and displays a message.

After the loop, the function displays the final game state and checks if the player has won or lost. If the player has made fewer than the maximum number of incorrect guesses, the function displays a “You win!” message. Otherwise, the function displays a “You lose!” message with the correct word.

You can call the function with an array of words to play the game. For example:

$words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
hangman($words);

Note that this solution does not display a hangman figure, but you can modify the code to do so if you wish.

LEAVE A REPLY

Please enter your comment!
Please enter your name here