Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Hangman
- {
- internal class Program
- {
- static string word;
- static char[] guess;
- static int lives;
- static char input;
- static void Main(string[] args)
- {
- update();
- }
- static void start()
- {
- Console.Clear();
- word = pickWord();
- fillBlank();
- lives = 5;
- }
- static void update()
- {
- start();
- while (lives > 0)
- {
- printWord();
- promptPlayer();
- input = getInput();
- checkInput(input);
- checkGameOver();
- }
- }
- static string pickWord()
- {
- string[] words = new string[]
- {
- "hydrophobia", "bacteria", "car","dog","electricity","humanity","compound"
- };
- Random rnd = new Random();
- int index = rnd.Next(0, words.Length);
- return words[index];
- }
- static void fillBlank()
- {
- guess = new char[word.Length];
- for (int i = 0; i < word.Length; i++)
- {
- guess[i] = '_';
- }
- }
- static void printWord()
- {
- Console.WriteLine("Guess the word: ");
- for (int i = 0; i < guess.Length; i++)
- {
- Console.Write(guess[i] + " ");
- }
- Console.WriteLine();
- }
- static void promptPlayer()
- {
- Console.Write("Enter a letter: ");
- if (lives < 5) { Console.WriteLine($"\nYou have {lives} lives left"); }
- }
- static char getInput()
- {
- char input = char.Parse(Console.ReadLine());
- return input;
- }
- static void checkInput(char input)
- {
- bool correct = false;
- for (int i = 0; i < word.Length; i++)
- {
- if (word[i] == input)
- {
- guess[i] = input;
- correct = true;
- Console.Clear();
- }
- }
- if (!correct)
- {
- lives--;
- Console.Clear();
- }
- }
- static void checkGameOver()
- {
- if (lives == 0)
- {
- Console.WriteLine("Game over!\n");
- }
- else if (!guess.Contains('_'))
- {
- Console.WriteLine("You win!\n");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment