Newest Articles

Flash Media Player
XML Driven Pie Chart
Base Defender
Hangman Game
8 Ball Pool

Popular Articles

Catapult Game
True Fullscreen Flash Mode
Mp3 Player with XML Playlist
FLV Player
Album Slide

Random Articles

Catapult Game
LED Text Scroller
RSS feed scroller
Focus in on an Image
Infinitely Zooming Image


Shapes the Game
Link to SwfSpot
Swf Spot

Contact me on Google+

rss feed

Hangman Game

Hangman Game
AddThis Social Bookmark Button
Description: Learn how to make the classic letter guessing game
Author: John Bezanis
Added: October 1st 2008
Version: Flash 8

Hangman is a popular game which can be coded using a few symbols and a short amount of code. The object of the game is to reveal a word by guessing the letters of the word one by one. The player loses by guessing 5 incorrect letters. A random answer is selected at the start of each game

Start by creating the movie clip that holds the graphics for the hangman. Set the name to missgraphic and the Linkage Identifier to missgraphic. Select Export for Actionscript.

On the first frame, draw the frame and hang a noose from it. In the actions section, add stop(); For frames 2-7, add one piece to the hangman. Return to the main stage. Delete the symbol from the stage, keeping it in the library.

Next we are going to create the buttons which contain the letters for the player to guess. Draw a square with rounded corners. Copy and paste the rectangle. Change the color to white and Modify->Shape->Expand Fill. Set the inset to 5px. Add a text box with type dynamic text. Set the Var to displayletter. Return to the main stage and delete the movieclip from the stage. In the library, select the movieclip, right click Export for Actionscript and set the Linkage Identifier to displayletter.

Next comes the blocks that hold the display of the answer. Start by drawing a 14x2 rectangle. Convert it to a movieclip named letterholder. Move the rectangle to the middle horizontally. Create a dynamic text box. Set the instance name to letter and Var to displayletter. Move back to the main stage and delete the movie clip. In the library, set letterholder's linkage identifier to letterholder and select Export for Actionscript.

The last symbol is the playagain button. Write the text and convert it to a button named playagain. I like to draw a transparent box on a layer below the text to make it easier to click. On frame 2, insert a new keyframe and set the color of the text a bit lighter than the up frame. Return to the main stage and delete the button from the stage. Set the button to Export for Actionscript and set the linkage identifier to playagain.

Now that all of the graphics are done, we can start writing the code. All of the code is located on the main stage. Start by creating an array that stores all of the answers and attaching the missgraphic to the stage.
  1. //Array containing all of the answers
  2. gameanswers = ['Frosted Flakes', 'Cheerios', 'Honey Combs', 'Lucky Charms', 'Honey Bunches of Oats', 'Apple Jacks', 'Rice Krispies', 'Fruit Loops', 'Count Chocula', 'Boo Berry'];
  3. //Attach the missgraphic
  4. this.attachMovie('missgraphic','missgraphic',this.getNextHighestDepth(), {_x:175,_y:10});
The first function we'll write is one to make a new game
  1. //Function that begins a new game
  2. function newGame() {
  3.   //select a random answer from the array
  4.   answer = gameanswers[Math.floor(Math.random()*gameanswers.length)];
  5.   //Add all 26 letter buttons to the stage
  6.   for (curindex=0; curindex<26; curindex++) {
  7.     //Use the character code for each letter to attach the letter
  8.     attachMovie('guessletter', 'guess'+String.fromCharCode(curindex+65), this.getNextHighestDepth());
  9.     //set the x position according to its position in the alphabet
  10.     eval('guess'+String.fromCharCode(curindex+65))._x = (curindex%13-6.5)*(eval('guess'+String.fromCharCode(curindex+65))._width+3)+Stage.width/2;
  11.     //set the y position according to its position in the alphabet
  12.     eval('guess'+String.fromCharCode(curindex+65))._y = Stage.height-(2-Math.floor(curindex/13))*(eval('guess'+String.fromCharCode(curindex+65))._height+3);
  13.     //set the character display to the current letter in the loop
  14.     eval('guess'+String.fromCharCode(curindex+65)).displayletter = String.fromCharCode(curindex+65);
  15.     //When the player clicks the button, call the pressLetter function with the letter set
  16.     eval('guess'+String.fromCharCode(curindex+65)).onPress = function() {
  17.       //process the letter
  18.       pressLetter(this.displayletter);
  19.       //remove the button from the stage
  20.       removeMovieClip(this);
  21.     };
  22.   }
  23.   //Determine how many characters are going to be printed on each line.
  24.   //Keep the letters of words from being split onto different lines
  25.   //start the row count at 0
  26.   curline = 0;
  27.   //the start position in the answer is 0
  28.   linestart = 0;
  29.   //store the length of each line into an array
  30.   var linelengths:Array = new Array();
  31.   //traverse all of the characters in the answer
  32.   for (linepos=0; linepos<length(answer); linepos++) {
  33.     //Maximum length of each formatted line
  34.     blanklinelength = 25;
  35.     //check if the linelength is smaller than the max line length or the first word on the line is longer than the max
  36.     if ((linepos-linestart)<blanklinelength || linelengths[curline] == undefined) {
  37.       //if the current character is a space, set a marker so we know how long the line should be
  38.       //it may be updated if another word fits within the current line
  39.       if (answer.charAt(linepos) == ' ') {
  40.         //update the length of the current line
  41.         linelengths[curline] = linepos-linestart+1;
  42.       }
  43.       //else the line has reached its limit, so move to the next line and start at the end of the last word 
  44.     } else {
  45.       //store where to start the next line
  46.       linestart = linestart+linelengths[curline];
  47.       //move to that position
  48.       linepos = linestart;
  49.       //move to the next line
  50.       curline++;
  51.     }
  52.   }
  53.   //set the length of the last line
  54.   linelengths[curline] = length(answer)-linestart;
  55.   //Now we are going to add the blank holders to the stage
  56.   //start at the first row
  57.   currow = 0;
  58.   //set the position to 0
  59.   curpos = 0;
  60.   //Loop through the answer and add the blank holders to the stage
  61.   for (curindex=0; curindex<length(answer); curindex++) {
  62.     //If the current position is a space, do not create a blank holder
  63.     if (answer.charAt(curindex) != ' ') {
  64.       //add the letter holder
  65.       attachMovie('letterholder', 'holder'+curindex, this.getNextHighestDepth());
  66.       //set the x position relative to its position on the line and the number of characters on the line
  67.       eval('holder'+curindex)._x = Stage.width/2+((curpos-(linelengths[currow]/2))*20);
  68.       //set the y position according to the currow
  69.       eval('holder'+curindex)._y = 280+(currow-(linelengths.length/2))*20;
  70.       //if the current character is not A-Z, display it
  71.       if (!hiddenCharacter(answer.charAt(curindex))) {
  72.         //display the character, since it is a special character
  73.         eval('holder'+curindex).displayletter = answer.charAt(curindex);
  74.       }
  75.     }
  76.     //If we are at the end of a row, go to the next row
  77.     if (++curpos>=linelengths[currow]) {
  78.       //move to the next row
  79.       currow++;
  80.       //reset the position to the left
  81.       curpos = 0;
  82.     }
  83.   }
  84. }
The next function is used for filling in characters that aren't A-Z.
  1. //This function checks if the input character is an A-Z character
  2. function hiddenCharacter(curchar) {
  3.   //Set of characters that aren't revealed
  4.   hiddenchars = 'abcdefghijklmnopqrstuvwxyz';
  5.   //Loop through the character set
  6.   for (charindex=0; charindex<length(hiddenchars); charindex++) {
  7.     //If the input character is in the list, hide it
  8.     if (curchar.toLowerCase() == hiddenchars.charAt(charindex)) {
  9.       return true;
  10.     }
  11.   }
  12.   //character is not A-Z, so display it
  13.   return false;
  14. }
This function is called when the player guesses a letter
  1. //function called each time a letter button is pressed
  2. function pressLetter(pressedletter) {
  3.   //check if the pressed letter is in the answer
  4.   if (!inAnswer(pressedletter)) {
  5.     //update the graphic to the next image
  6.     missgraphic.gotoAndStop(missgraphic._currentframe+1);
  7.     //check if the last frame has been reached
  8.     if (missgraphic._currentframe == missgraphic._totalframes) {
  9.       //game lost. remove all of the remaining buttons
  10.       for (curindex=0; curindex<26; curindex++) {
  11.         //if the letter button exists, remove it
  12.         if (eval('guess'+String.fromCharCode(curindex+65))) {
  13.           //delete the button. 65 is the ascii character A
  14.           removeMovieClip('guess'+String.fromCharCode(curindex+65));
  15.         }
  16.       }
  17.       //the game has been lost, so fill in all of the blank spaces with the answers in red
  18.       for (curindex=0; curindex<length(answer); curindex++) {
  19.         //if there is a space or the letter has been guessed already do nothing
  20.         if (answer.charAt(curindex) != ' ' && eval('holder'+curindex).displayletter == undefined) {
  21.           //the letter has not been guesed, so reveal it and make it red
  22.           eval('holder'+curindex).displayletter = answer.charAt(curindex);
  23.           eval('holder'+curindex).letter.textColor = '0xFF0000';
  24.         }
  25.       }
  26.       //Display the button to start a new game
  27.       showPlayAgainButton();
  28.     }
  29.   }
  30. }
This function checks to see if a guessed letter is in the answer.
  1. function inAnswer(pressedletter) {
  2.   //initialize goodletter to false.
  3.   //we are going to loop through the answer to see if the guessed letter is in the answer
  4.   goodletter = false;
  5.   //check if there are any letters in the answer that haven't been guessed yet
  6.   blankspace = 0;
  7.   //loop through the answer
  8.   for (curindex=0; curindex<length(answer); curindex++) {
  9.     //check if the guessed letter is the character in the current position of the answer
  10.     if (answer.charAt(curindex).toLowerCase() == pressedletter.toLowerCase()) {
  11.       //display the character
  12.       eval('holder'+curindex).displayletter = answer.charAt(curindex);
  13.       //setting goodletter to true prevents the image from going to the next frame
  14.       goodletter = true;
  15.       //if the character at the current position hasn't been guessed, reveal it
  16.     } else if (answer.charAt(curindex) != ' ' && eval('holder'+curindex).displayletter == undefined) {
  17.       //there is at least one letter that hasn't been guessed
  18.       blankspace = 1;
  19.     }
  20.   }
  21.   //if every letter has been guessed, the player wins
  22.   if (!blankspace) {
  23.     //remove all of the guess buttons
  24.     for (curindex=0; curindex<26; curindex++) {
  25.       //if the button at the current position exists, remove it
  26.       if (eval('guess'+String.fromCharCode(curindex+65))) {
  27.         removeMovieClip('guess'+String.fromCharCode(curindex+65));
  28.       }
  29.     }
  30.     //loop through all of the characters and set their color to green
  31.     for (curindex=0; curindex<length(answer); curindex++) {
  32.       //if the current character isn't a space, set its color to green
  33.       if (answer.charAt(curindex) != ' ') {
  34.         eval('holder'+curindex).letter.textColor = '0x00FF00';
  35.       }
  36.     }
  37.     //show the play again button
  38.     showPlayAgainButton();
  39.   }
  40.   //return whether or not the guessed letter exists in the answer
  41.   return (goodletter);
  42. }
This function attaches the playagain button. When pressed, a new game begins.
  1. //Show the button to play again
  2. function showPlayAgainButton() {
  3.   //attach the button
  4.   attachMovie('playagain', 'playagain', this.getNextHighestDepth());
  5.   //move it to the middle of the screen
  6.   playagain._x = Stage.width/2;
  7.   //move it towards the bottom
  8.   playagain._y = 370;
  9.   //Add a listener for when the button is pressed. When pressed, start a new game
  10.   playagain.onPress = function() {
  11.     //Reset the hangman graphic to the first frame
  12.     missgraphic.gotoAndStop(1);
  13.     //loop through all of the letter holders of the answer on the screen and delete them
  14.     for (curindex=0; curindex<length(answer); curindex++) {
  15.       //if the current position in the answer isn't a blank, remove it
  16.       if (answer.charAt(curindex) != ' ') {
  17.         removeMovieClip('holder'+curindex);
  18.       }
  19.     }
  20.     //start a new game
  21.     newGame();
  22.     //delete this button
  23.     removeMovieClip('playagain');
  24.   };
  25. }
Finally, we start the game when the applet loads.
  1. newGame();
That's it! Compile the game and test it out. The source file is available below for download:

Download Source File
Download Demo SWF
Comments Currently Disabled