Skip to content

Instantly share code, notes, and snippets.

@lucablackwell
Last active November 29, 2022 09:59
Show Gist options
  • Save lucablackwell/4ea31748a698877aa4ce71b5917e85f6 to your computer and use it in GitHub Desktop.
Save lucablackwell/4ea31748a698877aa4ce71b5917e85f6 to your computer and use it in GitHub Desktop.
<?php
# Guess the number, input range, returns higher or lower
# get the number of games
# loop for each game
# get the range
# assign random number from range
# loop while user guesses
# if (sanitised) guess is too high or too low, say
# if (sanitised) guess is correct, next game
function sanitise($limit, $default) {
$sanitised = false;
$input = readline('> ');
while (!$sanitised) {
# If there are letters
if (preg_match('/[a-z]/', $input)) {
echo "No letters.\n";
$input = readline('> ');
# If there are symbols
} elseif (preg_match('/[^\p{L}\d\s@#]/u', $input)) {
echo "No symbols.\n";
$input = readline('> ');
# If there is no input
} elseif ($input == null) {
if ($default) {
$input = $default;
$sanitised = true;
} else {
echo "Enter a number.\n";
$input = readline('> ');
}
} elseif (preg_match('/[0-9]/', $input)) {
if ($limit) {
if ($input < $limit) {
$sanitised = true;
} else {
echo "Lower than $limit.\n";
$input = readline('> ');
}
} else {
$sanitised = true;
}
}
}
return $input;
}
echo "Number of games (default 1):\n";
$games = sanitise(false, 1);
echo "Range to guess (default 10):\n";
$limit = sanitise(false, 10);
echo "Number $games limit $limit";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment