Pages

Friday, 20 February 2009

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 againdo {# 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 screenClear-Host

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

# Run the loop, then check the resultdo { # 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 themif ($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