Sunday, 21 August 2011

PHP Games - Hangman

Hangman is the favorite game for most of us. We used to play this game at school, college and everywhere else. All we need is two players. But when there is no one else to play, then you can make use of computer to play. It is a simple game you can create by yourself.


Hangman is essentially a word-guessing game. Given a word of a certain length, we have a limited number of letter guesses. If you guess a letter that appears in the word correctly, all occurrences of the letter are filled in. After a set number of wrong guesses (typically six), you've lost the game.

Using PHP, we can easily create this game. To put together a crude game of hangman, we need to start with a word list. For now, let's make it a simple array.

Creating a word list

$words = array (
"giants",
"triangle",
"particle",
"birdhouse",
"minimum",
"flood"
);


Using techniques covered earlier, we can move these words to an external word list text file and import them as we like.

Once we've got a list of words, we need to pick one out at random, display a blank for each letter, and start taking guesses. We need to keep track of right and wrong guesses from guess to guess. We'll do this cheaply by just serializing the guess arrays and passing them along with each guess. If we wanted to keep people from cheating by viewing the page source, we'd want to do something a little more secure.

Build up arrays to hold our letters, and our right/wrong guesses. For right guesses, we'll fill an array with the letters as keys and periods as values.

Building arrays to hold letters and guesses

$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z');
$right = array_fill_keys($letters, '.');
$wrong = array();


Now we need a little but of code to evaluate guesses and show the word as it progresses through the guessing game.

Evaluating guesses and displaying progress

if (stristr($word, $guess)) {
$show = '';
$right[$guess] = $guess;
$wordletters = str_split($word);
foreach ($wordletters as $letter) {
$show .= $right[$letter];
}

} else {
$show = '';
$wrong[$guess] = $guess;
if (count($wrong) == 6) {
$show = $word;
} else {
foreach ($wordletters as $letter) {
$show .= $right[$letter];
}
}
}

Download full script from here.