Introduction
Hangman is a popular word guessing game where the player attempts to build a missing word by guessing one letter at a time. After a certain number of incorrect guesses, the game ends and the player loses. The game also ends if the player correctly identifies all the letters of the missing word.
Using the Code
The program consists of several classes. The class diagram is shown below:
The main thing from the program is holding the guessed letters in an array collection and manipulating against the randomly picked word. In addition, you need to count the missing letters. Let's see the code that verifies the user's guessed letter and builds the word.
public void Play()
{
guessed_FoundLetters = new List<string>();
for (int i = 0; i < PickedWord.WordLength; i++)
{
guessed_FoundLetters.Add(" _ ");
}
for (int i = 0; i < PickedWord.WordLength; i++)
{
string letter = PickedWord.Content.Substring(i, 1);
if (GuessedLetters.Count > 0)
{
foreach (string guessedLetter in this.GuessedLetters)
{
if (letter.Equals(guessedLetter.Trim().ToUpper()))
{
guessed_FoundLetters.RemoveAt(i);
guessed_FoundLetters.Insert(i, " " + letter + " ");
}
}
}
}
drawHangMan();
Console.WriteLine(buildString(guessed_FoundLetters, false));
Console.WriteLine();
}
The enumeration class is an indicator whether a user is winning or losing the game.
public enum GAMERESULT
{
WIN,
LOSE,
CONTINUE,
}
The program class is the one which takes all the actions from the user and runs the game. The method that actually plays the game is shown below:
private static void playGame()
{
Words words = new Words();
Word pickedWord = words.Pick;
PlayHangman playHangman = new PlayHangman();
playHangman.PickedWord = pickedWord;
for (int i = 0; i < pickedWord.WordLength; i++)
{
Console.Write(" _ ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
while (playHangman.Result() == GAMERESULT.CONTINUE)
{
Console.Write("Pick a letter --> ");
ConsoleKeyInfo guessedLetter = Console.ReadKey();
if (playHangman.AddGuessedLetters(guessedLetter.KeyChar))
playHangman.Play();
}
if (playHangman.Result() == GAMERESULT.LOSE)
{
Console.WriteLine("So sorry. You struck out.");
makeTextBlink("The mystery word was '" +
pickedWord.Content.ToUpper() + "'",500);
return;
}
else
{
makeTextBlink("You won !",500);
return;
}
}
Points of Interest
In this program, I learnt how to solve word guessing problems. I hope you enjoyed the Hangman game and the implementation.
History
- February 27, 2010: First version
- March 1, 2010: Article updated