HangMan Optimized

 using System;

using System.IO;

using System.Linq;

using System.Collections.Generic;


namespace HangMan

{


  public class Program

  {

 public static void Main()

 {

   //Generating random word

   string[] words = { "chicken", "hen", "dog", "lion", "zebra", "crow", "parrot", "elephant" };

   Random random = new Random();

   int randomNumber = random.Next(1, words.Length);

   string selectedWord = words[randomNumber];

   string hiddenWord = "";

   for (int i = 0; i < selectedWord.Length; i++)

   {

  hiddenWord += "*";

   }

   Console.WriteLine("Word : {0}", hiddenWord);

   //Finish



   //Guessing the hidden word

   bool contains = false;

   while (hiddenWord.Contains("*"))

   {

  Console.Write("Guess the letter >>");

  char letter = char.Parse(Console.ReadLine());


  for (int i = 0; i < selectedWord.Length; i++)

  {

    if (selectedWord[i] == letter)

    {

   hiddenWord = hiddenWord.Remove(i, 1);

   hiddenWord = hiddenWord.Insert(i, letter.ToString());

   contains = true;

    }

  }

  if (contains == true)

  {

    Console.ForegroundColor = ConsoleColor.Green;

    Console.WriteLine("Found");

  }

  else

  {

    Console.ForegroundColor = ConsoleColor.Red;

    Console.WriteLine("Not Found");

  }

  Console.ResetColor();

  Console.WriteLine(hiddenWord);

  contains = false;

   }


   //you won

   Console.WriteLine("You won the word is {0}", selectedWord);

 }

  }

}

Comments

Popular Posts