Powershell Fun - Number Guessing Game



Source Code:
#--------------------------------------
# ||||||| Number Guessing Game ||||||||
#--------------------------------------
# Author: Wayne Hoggett
# Filename: game_number_guess.ps1
# Version 1.0
#--------------------------------------
# Play the game once, and then ask them if they would like to play again
do {
# Get a random number between 0 and 100
$random = New-Object System.Random
$answer = $random.next(0,101)
# Hold the number of guesses in the count variable and set it to 0
$count = 0

# Clear the screen
Clear-Host

# Display the title of the game
Write-Host "--------------------------------------------------------" -ForegroundColor Green
Write-Host "Number guessing game, guess the number between 1 and 100" -ForegroundColor Yellow
Write-Host "--------------------------------------------------------" -ForegroundColor Green


# Run the loop, then check the result
do {
# Get the guess from the user
$guess = (Read-Host "Enter your guess")

# If they answer correctly, exit the loop immediately
if ($answer -eq $guess)
{
break
}
elseif ($answer -gt $guess)
{
# Tell them the result
Write-Host "Number is higher than your guess"
# Increment the number of guesses
$count++
}
else {
# Tell them the result
Write-Host "Number is lower than your guess"
# Increment the number of guesses
$count++
}
} while ($answer -ne $guess)

# Once they have the correct answer, tell them
if ($answer -eq $guess)
{
Write-Host "Correct, the number was $answer. You guessed correctly in $count guesses"
# Ask them if they want to play again and store the answer in the $play variable
$play = (Read-Host "Would you like to play again?")
}
} while ($play -contains "y") # Notice the answer only needs to contain "y" so Yes or Y will both be valid answers

# If they say no, exit Powershell
if ($play -contains "n")
{
Stop-Process -Name "powershell"
}

Popular posts from this blog

Get local computer UUID/GUID using Windows Powershell

gPLink and gPOptions

PSLoggedOn Getting Started on Windows Server 2008 R2