Skip to content

Instantly share code, notes, and snippets.

@barbarbar338
Created December 31, 2023 07:20
Show Gist options
  • Save barbarbar338/df80062bbdc3486c7eb098ac50adab00 to your computer and use it in GitHub Desktop.
Save barbarbar338/df80062bbdc3486c7eb098ac50adab00 to your computer and use it in GitHub Desktop.
A simple number guessing game in PowerShell
enum Difficulty {
EASY
MEDIUM
HARD
}
Function GetMaxNumberByDifficulty {
[CMDLetBinding()]
Param(
[Difficulty]$Difficulty
);
Switch($Difficulty) {
EASY {
Return 50;
};
MEDIUM {
Return 100;
};
HARD {
Return 200;
};
Default {
Throw "Invalid difficulty.";
};
};
};
Function GetRandomNumberByDifficulty {
[CMDLetBinding()]
Param(
[Difficulty]$Difficulty
);
$MaxNum = GetMaxNumberByDifficulty -Difficulty $Difficulty;
$Random = Get-Random -Minimum 1 -Maximum $MaxNum;
Return $Random;
};
$Guesses = 0;
$Guessed = $False;
[Difficulty]$Difficulty = Read-Host "Choose a difficulty (EASY, MEDIUM, HARD)";
Try {
$RandomNumber = GetRandomNumberByDifficulty -Difficulty $Difficulty;
} Catch {
Write-Host "Invalid difficulty.";
Exit;
};
$Max = GetMaxNumberByDifficulty -Difficulty $Difficulty;
While ($Guessed -Eq $False) {
$Guess = Read-Host "Guess a number between 1 and $($Max)";
$Guesses++;
Write-Host "You guessed ($Guess)";
If ($Guess -Eq $RandomNumber) {
$Guessed = $True;
} ElseIf ($Guess -Lt $RandomNumber) {
Write-Host "Your guess is too low.";
} ElseIf ($Guess -Gt $RandomNumber) {
Write-Host "Your guess is too high.";
};
};
Write-Host "You guessed the number ($RandomNumber) in ($Guesses) guesses.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment