Possible Solution
Here’s an implementation of the wordLadder
function in PHP:
function wordLadder($start, $end) {
// Load the dictionary file into an array
$words = file('dictionary.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Make sure the start and end words are valid
if (!in_array($start, $words) || !in_array($end, $words)) {
die('Invalid start or end word');
}
// Initialize the game state
$currentPlayer = 1;
$currentWord = $start;
$previousWord = '';
$maxMoves = 2 * strlen($start); // Maximum number of moves before tie
$moveCount = 0;
// Loop until the game is over
while ($currentWord != $end && $moveCount < $maxMoves) {
// Prompt the current player for their move
echo "Player $currentPlayer's turn. Enter a word: ";
$newWord = strtolower(trim(fgets(STDIN)));
// Validate the move
if (strlen($newWord) != strlen($currentWord) || $newWord == $currentWord || !in_array($newWord, $words)) {
echo "Invalid move. Please try again.\n";
continue;
}
// Check if the move is one letter different from the previous word
if ($previousWord != '' && !isOneLetterDifferent($previousWord, $newWord)) {
echo "Invalid move. The new word should be one letter different from the previous word.\n";
continue;
}
// Update the game state
$previousWord = $currentWord;
$currentWord = $newWord;
$currentPlayer = $currentPlayer == 1 ? 2 : 1;
$moveCount++;
// Display the current state of the game
echo join(' -> ', [$start, $currentWord]) . "\n";
}
// Check if the game is a tie or if there is a winner
if ($currentWord == $end) {
return "Player $currentPlayer";
} else {
return 'Tie';
}
}
function isOneLetterDifferent($word1, $word2) {
$diff = 0;
for ($i = 0; $i < strlen($word1); $i++) {
if ($word1[$i] != $word2[$i]) {
$diff++;
}
}
return $diff == 1;
}
To play the game, call the wordLadder
function with the starting word and ending word as arguments:
$result = wordLadder('CAT', 'DOG');
if ($result == 'Tie') {
echo "It's a tie!\n";
} else {
echo "$result wins!\n";
}
This will prompt the players to take turns entering new words until one player successfully transforms the starting word into the ending word or the maximum number of moves is reached. The function will return the winning player or ‘Tie’ if the game is a tie.