I've been working on a console-based Hangman Game with PHP and have come across a somewhat big issue.
When the user guesses the correct word, it functions as needed. It reveals the letter and continues to ask the user to guess the next.
Now, the issue comes when the player gets it wrong. My intentions were when the user gets a letter wrong, the $playerErrors variable gets +1 value, and once $playerErrors has a value of 6, aka the player has made 6 wrong guesses, the program terminates. This is not what happens however, instead, if the word they're guessing has 5 letters for example, and they guessed 1 letter wrong, they will get +5 $playerErrors instead of just +1 $playerErrors.
So as a result of the player getting say 5 $playerErrors in one guess, the player will really only have 1 or 2 lives instead of 6.
Here is the code from the main section:
while ($playerErrors < 6) {
if (strpos($shwWord, '_') === false){
echo "You won! Congratulations!\n";
break;
}
$guess = readline('Guess a letter: ');
for ($g = 0; $g < count($secretArray); $g+=1) {
if ($guess === $secretArray[$g]){
$displayedLetters[$g] = $guess;
}
else{
$playerErrors += 1;
echo "Errors: " . $playerErrors;
echo "\n";
}
}
$shwWord = implode(' ', $displayedLetters);
echo "\n $shwWord \n\n";
}
if ($playerErrors >= 6) {
echo "you lost" . PHP_EOL;
}