Simple Hangman game in C#
Below is a simple implementation of the Hangman game in C#. This code assumes a console-based interaction.
using System; class HangmanGame { private static readonly string[] WORDS = { "csharp", "programming", "code", "hangman", "computer" }; private const int MAX_TRIES = 6; static void Main() { Random random = new Random(); string secretWord = WORDS[random.Next(WORDS.Length)]; char[] guessedLetters = new char[secretWord.Length]; int tries = 0; while (true) { DisplayHangman(tries); DisplayGuessedWord(guessedLetters); Console.WriteLine("Enter a letter: "); char guess = Console.ReadKey().KeyChar; if (IsLetterAlreadyGuessed(guess, guessedLetters)) { Console.WriteLine("You've already guessed that letter. Try again."); continue; } if (secretWord.Contains(guess)) { UpdateGuessedLetters(secretWord, guessedLetters, guess); } else { tries++; } if (IsWordGuessed(guessedLetters)) { Console.WriteLine($"Congratulations! You guessed the word: {secretWord}"); break; } if (tries == MAX_TRIES) { DisplayHangman(MAX_TRIES); Console.WriteLine($"Sorry, you ran out of tries. The correct word was: {secretWord}"); break; } } } private static void DisplayHangman(int tries) { // Add hangman drawing logic based on the number of tries // You can customize the ASCII art for the hangman as needed. } private static void DisplayGuessedWord(char[] guessedLetters) { Console.Write("Current word: "); foreach (char letter in guessedLetters) { if (letter == '\0') { Console.Write("_ "); } else { Console.Write($"{letter} "); } } Console.WriteLine(); } private static bool IsLetterAlreadyGuessed(char guess, char[] guessedLetters) { foreach (char letter in guessedLetters) { if (letter == guess) { return true; } } return false; } private static void UpdateGuessedLetters(string secretWord, char[] guessedLetters, char guess) { for (int i = 0; i < secretWord.Length; i++) { if (secretWord[i] == guess) { guessedLetters[i] = guess; } } } private static bool IsWordGuessed(char[] guessedLetters) { foreach (char letter in guessedLetters) { if (letter == '\0') { return false; } } return true; } }