Simple Head or tail game with PowerShell. To understand the basic concept of do while, if else condition in PowerShell, i created simple command line game – Head2Tails with Powershell.
Head2Tail is single player powershell game against computer. Objective of the game is to score points against computer by predicting heads or tails from toss of the coin.
Head2Tails acts as an example for ‘if else’ & ‘do while’ looping and Get-random command. Get-random provides random value from set of predefined values.
$value = 10,20,30,40,50
Get-Random -InputObject $value
mode 300
$Welcome = “`n || HOLA AMIGO ! ||`n || Come ON let’s PLAY !! || `n”
$RULE = “SIMPLE RULE : Coin will be tossed and you must predict – HEAD or TAILS”
cls
Write-Host $Welcome -ForegroundColor Green #-BackgroundColor cyan;
Write-Host “<<$RULE>>” -ForegroundColor darkmagenta -BackgroundColor yellow
$count=$YOU=$computer = 0
do{$count++
write-host “Round $count” -foregroundcolor Yellow -backgroundcolor red
do{
$play=Read-host “`n Which side do you want – HEADS(H) or TAILS(T) ? `n `n (Enter H/T) ”
$keyBoardObject = New-Object -ComObject WScript.Shell
#$CAPS = [System.Windows.Forms.Control]::IsKeyLocked(‘CapsLock’)
#if ( $CAPS -eq $false ) {$keyBoardObject.SendKeys(“{CAPSLOCK}”)}
}while ($play -ne ‘h’-and $play -ne “t”)
if($play -eq ‘H’)
{ $ask = ‘HEADS’;write-host ” `n YOU selected $ask “}
else {
$ask = ‘TAILS’;write-host “`n YOU selected $ask ” }
Start-Sleep -s 1 ;write-host “`n >>>>TOSSssingg..<<<< `n” ; Start-Sleep -s 1
$H2T = ‘HEADS’,’TAILS’
$Result = Get-Random -InputObject $H2T
write-host ” And the Result is ….. ” -NONEWLINE ; Start-Sleep -s 1.5
write-host “$result” -Foregroundcolor Red -BackgroundColor yellow;Start-Sleep -s 1
if (Compare-Object $result $ask)
{Write-host ” `n “COMPUTER WON” ” -ForegroundColor Red -NONEWLINE; WRITE-hOST ” Better Luck next round”
$computer++}
else {write-host ” `n YOU WON , Great!!” -ForegroundColor Green
$YOU++}
WRITE-HOST “`n SCORE:” -nonewline ; write-host ” YOU = $YOU “-foregroundcolor green -NONEWLINE ; WRITE-HOST “\\ “-NONEWLINE ; WRITE-HOST “COMPUTER = $COMPUTER” -foregroundcolor red
$end = Read-host “`n PRESS ANY KEY to proceed next round or press ‘0’ to EXIT ”
}while ($end -ne 0)
Tired of scripting in PowerShell? Have a break and try Head2Tails.