Skip to content

Instantly share code, notes, and snippets.

@Soben
Last active August 22, 2023 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Soben/cb42878aef10d7ea3e8e12d77da09b5c to your computer and use it in GitHub Desktop.
Save Soben/cb42878aef10d7ea3e8e12d77da09b5c to your computer and use it in GitHub Desktop.
Cassidoo | Guessing Game

Solution to Cassidoo's Week of Aug 21, 2023 Challenge

Make a "guessing game" where there is a target number, and as the user makes guesses, the output returns higher or lower until the user is correct.

I haven't messed with PHP's CLI handling of user input in a while, so I decided to stay focused on my language of 'choice'.

Went a little above the basic request, allowing users to override the min/max range. Available commands

$ php guessing-game.php
$ php guessing-game.php help
$ php guessing-game.php [min] [max]
$ php guessing-game.php [max]

Technically also works in shell more directly as well... provided you make sure it's executable, have php located at /usr/bin/php, and likely more situations not directly encountered today while writing this out.

$ ./guessing-game.php
$ ./guessing-game.php help
$ ./guessing-game.php [min] [max]
$ ./guessing-game.php [max]

Defaults to a random number between 1 and 100, limited to positive integers.

#!/usr/bin/php
<?php
$input = fopen("php://stdin", "r");
$min = 1;
$max = 100;
if (isset($argv[1]) && $argv[1] == "help") {
echo "A quick guessing game build in PHP!" . PHP_EOL . PHP_EOL;
echo "Acceptable ways to run this game:" . PHP_EOL;
echo "\t$ php guessing-game.php [min] [max]" . PHP_EOL;
echo "\t$ php guessing-game.php [max]" . PHP_EOL;
echo "\t$ php guessing-game.php help" . PHP_EOL;
echo "\t$ php guessing-game.php" . PHP_EOL;
exit;
}
if ($range = array_slice($argv, 1)) {
if (count($range) >= 2) {
$min = (int)$range[0];
$max = (int)$range[1];
} else {
$max = (int)$range[0];
}
if (abs($min) != $min || abs($max) != $max || $max <= 0 || $min <= 0) {
echo "Please only enter positive, non-zero integers. Min: {$min} Max: {$max} provided" . PHP_EOL;
exit;
}
if ($max <= $min) {
echo "Invalid guessing range! Min: {$min} with Max: {$max} provided." . PHP_EOL;
exit;
}
}
$firstRun = true;
$numberToGuess = rand($min, $max);
$currentGuess = null;
echo "Guess the number!" . PHP_EOL;
$guessCount = 0;
while ($firstRun || $numberToGuess != $currentGuess) {
$currentGuess = readline("> ");
$guessCount++;
$firstRun = false;
if ($currentGuess != abs((int)$currentGuess) || $currentGuess == 0) {
echo "Enter a positive, whole number between {$min} and {$max}" . PHP_EOL;
} else if ($currentGuess < $numberToGuess) {
echo "higher" . PHP_EOL;
} else if ($currentGuess > $numberToGuess) {
echo "lower" . PHP_EOL;
}
}
echo "Correct! You won in {$guessCount} guesses!" . PHP_EOL;
echo "Let's play again!" . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment