Hangman using C# and .NET
By Mike Gold
Figure-1. Hangman Game
Source code: Hangman.zip 244 KB
Hangman Program Using C#
Hangman was created to illustrate several features of C# including GDI+, string manipulation, array processing, using properties, as well as simple creation of objects. As you can see from the diagram above, there are 5 main objects to the design. First there is a Form1 upon which everything is draw and also the key presses are captured. This form contains all the main objects which it uses to manage the game. The RandomWordManager that picks a random word to start the game, The LetterManager which manages the letters underneath the hangman and remembers which ones have been guessed, The WinLoseManager that handles determining if the player wins or loses and of course the HangDude who knows how to draw himself and remembers how many times the player missed a letter.
The UML design can be found here, Hangman UML Design which was reverse engineered in WithClass 2000.
Below are the two main routines for processing Hangman Events:
The first routine, OnKeyPress is overriden in the form to capture key presses and decides what to do after the user guesses a character.
protected override void OnKeyPress(KeyPressEventArgs e)
char j = e.KeyChar;
string bigJ = j.ToString().ToUpper();
j = bigJ.ToChar();
// determine if the game has already ended
if (TheWinLoseManager.YouLoseFlag || TheWinLoseManager.YouWinFlag )
if (j == 'N')
if (j == 'Y')
// restart the game
TheLetterManager = null;
TheLetterManager = new LetterManager(TheWordManager.Pick());
TheLetterManager.SetPosition (20, 150);
TheMan.NumberOfMisses = 0;
// check to see if we got a letter
if (TheLetterManager.GotALetter(j) == false)
TheWinLoseManager.YouLoseFlag = true;
TheWinLoseManager.YouWinFlag = true;
The next routine, OnPaint, is overriden to determine how to draw the current state of the letters and the hangman:
protected override void OnPaint(PaintEventArgs pe)
Graphics g = pe.Graphics ;
// draw the background
Rectangle rect = this.ClientRectangle;
LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red,
// draw the hangman
// draw the letters
if (TheWinLoseManager.YouLoseFlag == true)
else if (TheWinLoseManager.YouWinFlag == true)
The code is included so that you can compile it and play for fun!
About the Author: Mike Gold is President of Microgold Software Inc. and Creator of WithClass 2000 a UML Design Tool. In the last few years Mike has consulted for companies such as Merrill Lynch and Chase Manhattan Bank in New York. He is been active in developing Visual C++ Applications for 10 years and looks forward to the possibilities in C#. You can reach him at email@example.com.