Believe it or not, but the last 13 or so posts have all been leading up to this one. Generating random numbers, capturing user input, using colors on the command-line, pluralizing words, and then some are all being utilized in this simple number guessing game.

The script itself generates a random number between 1 and 100, asks the user to guess, advises them if they are too high or too low then tells them how many guesses it took them to guess the number:


$number  = rand(1, 100);
$guesses = 0;
$won	 = false;
$handle  = fopen('php://stdin', 'r');

echo "\nI'm thinking of a number between 1 and 100...\nCan you guess the number?\n\n";

while (!$won)
	echo 'What is your guess? ';

	$guess = trim(fgets($handle));

	if (preg_match('/\d/', $guess))
		if ($guess > $number)
			echo "\033[0;31mToo high...\033[0m\n";
		elseif ($guess < $number)
			echo "\033[0;31mToo low...\033[0m\n";
		elseif ($guess == $number)
			echo "\033[0;32m\nYou guessed it!\033[0m\n";
			printf('It took you %d ' . ngettext('guess', 'guesses', $guesses) . "!\n",  $guesses);


To run the script, just execute it from the command-line:

php -f number-guess.php

Substitute number-guess.php for whatever you named the script and guess away!

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: