I am trying to develop the hangman game in PowerShell. All goes well in my script but there is an logical error in the game. I want to put the check, that when user enter the same word twice. It simple gives error ! For example : The Word "Football". If user enter Letter 'F' more then 1 times it should give error message. Here is my code :
$random = Get-Random -Minimum 0 -Maximum 5;
$names="America","Iran","Poland","Cat","PowerShell ";
$arrname= $names[$random];
$arrname.ToCharArray();
$ntp="0","1";
$arrlen = $arrname.Length;
clear;
Write-Host "---------Guess the word--------------";
Write-Host "Length is : " $arrname.Length;
$life=3;
do{
Write-Host "Lifes Remain " $life;
$rnd= Read-Host "Guess the word ";
if($flag2 -le 1)
{
$flag=0;
}
else
{
$life--;
}
for($i=0;$i -lt $arrname.Length; $i++)
{
if($rnd -eq $arrname[$i] )
{
$flag =1;
$arrlen --;
}
}
if($flag -eq 0 )
{
$life--;
}
if($arrlen -eq 0)
{
Write-Host $arrname;
Write-Host " ************ You WIN ********************";
break;
}
if($life -eq 0)
{
Write-Host " ------------- You LOST ------------"
break;
}
$p++;
}
while(1);
Here you go, this should get you well on your way, to keep track of the letters add them to an array $guesses=@()
then check if they have already used a letter using contains the letter $guesses -contains $guessLetter
$random = Get-Random -Minimum 0 -Maximum 5;
$names="America","Iran","Poland","Cat","PowerShell";
$targetWord = $names[$random];
[Char[]]$wordProgress = "_" * $targetWord.Length
clear;
Write-Host "---------Guess the word--------------";
$life=3;
$guesses=@()
do
{
do
{
Write-Host "[$($targetWord.Length)] $wordProgress";
Write-Host "Lifes Remain " $life
$guessLetter = Read-Host "Guess a letter:"
if ($guesses -contains $guessLetter)
{
"Try another letter!"
}
} while ($guesses -contains $guessLetter)
$guesses+=$guessLetter
$guesses -join ','
$foundLetter = $false
for($i=0;$i -lt $targetWord.Length; $i++)
{
if($guessLetter -like $targetWord[$i] )
{
$wordProgress[$i] = $guessLetter
$foundLetter=$true
}
}
if(!$foundLetter)
{
$life--;
}
if($($wordProgress -join '') -like $targetWord)
{
Write-Host $targetWord;
Write-Host " ************ You WIN ********************";
break;
}
}
while($life -gt 0)
if ($life -eq 0)
{
Write-Host " ------------- You LOST ------------"
}