Welcome to the 9th PHP Coding Puzzle !

Word Ladder Game

Game Description

Word Ladder is a word game in which two players try to transform one word into another by changing one letter at a time, with each intermediate step being a valid word. For example, to transform the word “CAT” into the word “DOG”, one possible word ladder is:

CAT -> COT -> DOT -> DOG

Players take turns making a move. On each move, a player can change one letter of the word to create a new valid word. The first player who successfully transforms the starting word into the ending word wins the game.

Requirements

Write a PHP function called wordLadder that allows two players to play a game of Word Ladder. The function should take two parameters: the starting word and the ending word.

The function should prompt the first player for their move (the new word to create), validate the move (the new word should be one letter different from the previous word and should be a valid English word), display the current state of the game, and switch to the second player if the move is valid.

The function should continue the game until one player successfully transforms the starting word into the ending word or no valid move can be made. The function should return the winning player (‘Player 1’ or ‘Player 2’) or ‘Tie’ if the game is a tie.

The function should use a dictionary file to validate words. You can download a dictionary file from http://www.gutenberg.org/ebooks/29765.

Example Usage

$result = wordLadder('CAT', 'DOG');
if ($result == 'Tie') {
  echo "It's a tie!\n";
} else {
  echo "$result wins!\n";
}

Example Output

Player 1's turn. Enter a word: COT
CAT -> COT
Player 2's turn. Enter a word: DOT
CAT -> COT -> DOT
Player 1's turn. Enter a word: DOG
Invalid move. Please try again.
Player 1's turn. Enter a word: FOT
Invalid move. Please try again.
Player 1's turn. Enter a word: COG
CAT -> COT -> COG
Player 1 wins!

The solution is already available in the next page 😉 Feel free to share with us your solution here in comments or Github.

LEAVE A REPLY

Please enter your comment!
Please enter your name here