Vous êtes sur la page 1sur 53

Create an Awesome Hangman Game in

Flash Using ActionScript 3.0 by Carlos


Yanez

Tutorial DetailsProgram: Flash Professional, PhotoshopDifficulty: IntermediateEstimated Completion Time: 2h


Download Source FilesView Demo
Tweet
Developing a game is must-have skill if you are a Flash Developer, it makes use of many different ActionScript
methods and properties, plus you will have plenty of fun in the process! In this tutorial, I will show you how to create
an advanced Hangman game using ActionScript 3.0. Lets play!

Step 1: Brief Overview


During this Premium tutorial Ill demonstrate the game development process from the Graphical User Interface design
using Flash Tools and a little bit Photoshop, to the code part using the power of ActionScript 3.

Step 2: Graphical User Interface


These are the elements of the graphical user interface we will create:

Step 3: Logo
Create a new Flash File and set its dimensions to 320480 px.

Select the Text Tool (T), and choose a cartoon style font, I used GoodDog 86 pt.

Write "Hangman+" and break apart (Cmd+B) the text to add a gradient color.

Select the graphics and open the Color Panel, choose Linear Gradient and use these colors: #FBA31E, #FECB56.

Use the Gradient Transform Tool to rotate the gradient and get a color as shown in the image.

Repeat this process in the "+" using these colors: #831000, #A91101.

Convert the whole lot to a MovieClip and add a Drop Shadow Filter with the following values:

You will end up with something like this:

Step 4: Background
Lets create the Background.
Open Photoshop and create a new file (320480).

Select the Gradient Tool (T) and add a brown (#4E4236, #382F26) radial background starting from the center to one
of the edges.

Now its time to add a Noise filter to get a textured background.


From the menu go to Filter > Noise > Add Noise and use these values:

Save your image as png-24 using the "Save for Web & Devices" option in the File menu.
Your background should look like this:

Step 5: Main Screen Buttons


Go back to Flash, import (Cmd+R) your background and center it.
Use the Arrange > Send to back option from the contextual menu (right click) to send the background to the bottom
and show your previously created logo.

Select the Rectangle Primitive Tool and create a 20050 px rectangle with the same yellow gradient as before
(#FBA31E, #FECB56).

Go to Rectangle Options in the Properties Panel and set the corner radius to 8.00.

Convert the drawing to MovieClip and add the following filter:

Select the Text Tool, create a new Static Text and write "New Game". I used this format: Myriad Pro Semibold, 24 pt,
#831000.

To create a letter press effect, duplicate (Cmd+D) the textfield and move it a pixel down, Change the text color to
#FDDA8A.

Convert it to MovieClip and center it in the stage. Set its instance name to "newGame".
Repeat this process with two more buttons; Options and About. Remember to change the instance names.

Convert what you have so far to a MovieClip, name it "menuScreen" and place it temporarily away from the stage.

Step 6: Game Graphics


This is the interface of the actual game, where you interact with the keyboard to guess the hidden word.

As you can see we use the same background, so duplicate it and center it in the stage.

Step 7: NoteBook
Select the Rectangle Primitive Tool, change the corner radius to 10 and draw a 260250 px rectangle. Add a radial
background (#FBEE84, #FDF9B2).

To make the lines, l use the Rectangle Tool and draw a 2601 px rectangle with a color of #C6C970.

Duplicate the line (Cmd+D) and place it 10 pixels down, repeat this until you get something like the following image:

For the side lines, create a 1250 px, #99832E rectangle and and place it 20 pixels from the edge, duplicate it and
place the new one 2 pixels from the original.

Convert this to MovieClip, duplicate it, send it to back and place it 5 px lower. Use the same button filter.

Now well give the notebook a title; this text will change according to the category selected in the Options.
Select the Text Tool, create a 23625 px Dynamic TextField and write some text as a guide. The format is Marker
Felt 18 pt, #663622.
Use the letterpres technique we used before to add some detail. The instance names are "categoryText", and
"categoryLP" for the letterpress field.

Step 8: Hangman
To draw the hangman well cheat a little, since Flash doesnt have brushes or anything similar well use a Font to
draw crayon style.
I used characters from the font LeviCrayola to draw this:

Convert each part to a MovieClip and set their instance names like this: head, body, leftArm, rightArm, leftLeg,
rightLeg.
Place the Hangman parts in the center of the notebook and continue to the next step.

Step 9: Keyboard
The user input will be handled by a keyboard in the stage that will compart the key pressed to the hidden screen.
Select the Rectangle Primitive Tool and draw a 2638 px rectangle with the previously yellow background, add a
corner radius of 5.

Convert it to MovieClip and add the button filter.


Add the corresponding letter and use the letterpress technique to create a better looking button. Format is Myriad Pro
Semibold, 23 pt, Black.

Convert the 2 elements to a MovieClip and name it as the Letter it represents in UpperCase.
Repeat this step with all the letters, remember to set the correct instance name.
We will also create a MovieClip that will appear on top of the key when its pressed using the same rectangle created
for the key
Copy and paste the rectangle and change it color to white, alpha 30%, mark the "Export for ActionScript" box and
name it "Inactive".

A sound will also be played when a key is pressed.


You can find all types of sounds including buttons at AudioJungle, when you find a sound you like, import it (Cmd+R)
and in the Library Panel, right click it and select "properties", mark the "Export for ActionScript" box and write
ButtonSound as the class.

Step 10: Back Key


The back key will clear the game data and take the user to the Menu Screen.
Create a key using the same steps as the keyboard, convert it to MovieClip and name it "back".

Step 11: Options


The Options View is shown when the user clicks in the Options button in the MenuScreen. It displays information
some options for the game.
It should be easier to create this view since we already have all the graphics and backgrounds.

The Category option, as the name says, describes the type of words that will be displayed when playing. You can use
unlimited number of categories, well see that later in the code.
The Victory option is the number of words that you need to correctly guess to declare the game as won.
The Lives option is the number of wrong answers you can make before you lose the game.

Step 12: TextFields


This view has a 6 TextFields, the left ones are Static and formatted in the following way: Marker Felt Thin, 19 pt,
#673723.

The right ones are Dynamic and fomatted like this: Helvetica Regular, 15 pt, #673723. (add instances in image)

Step 13: Back Button


The back button will take the user to the Menu Screen.
Create a Static TextField with the same format as the ones above, and change the size to 16 pt.

Convert it to Button, name it "back".

Step 14: More Button


The More button will change the values of the options.
Create a white 1616 px circle using the Oval Tool (O).

Create another circle, this time 1212, #673723 and center it.

Create a 2px wide 5px tall rectangle and duplicate it, rotate the -45 degrees and break it apart (Cmd+B) to make
them intersect, remove the unwated area to make an arrow, and center it.

Convert it to MovieClip and add the following filter:

Duplicate and place the buttons as shown in Step 11 and name them: "catButton", "vicButton" and "livesButton".
Convert all to a MovieClip, mark the "Export for ActionScript" checkbox and name it "OptionsView". You can delete
the symbol from the stage now.

Step 15: About


The About view shows information about the creator, company and version of the application.

Scale the Hangman logo to 12130.6 px and center it.


Create and center a Static TextField with this format: Helvetica Neue Regular, 15 pt, #EFEFEF, and add the text
shown in the image.
Convert it all to a MovieClip, mark the "Export for ActionScript" checkbox and name it "AboutView". You can delete
the symbol from the stage now.

Step 16: Alert


Were going to display a message when you win or lose, for that we will use this Alert view.

Create a 320240 px rectangle and use this radial gradient: #000000 alpha 0, #000000 alpha 50.

Next, create a 260100 px white rectangle with 20 px corner radius and place it in the middle of the black
background.

Duplicate the rectangle and make it 25696 px, #FCB73A alpha 90.

Create a 24023 px Dynamic TextField and name it "title". Press the "Align Center" Button in the Paragraph panel
and use the letterpress technique, this time moving the duplicated textfield up. The format is Helvetica Bold 19 pt,
white.

Use another Dynamic TextField with this format: Helvetica Regular 15 pt, white. Place it in the center and use the
Align Center option.
Name it "content" and add some text to the fields as a guide.

Convert all to a MovieClip, mark the "Export for ActionScript" checkbox and name it "AlertView".

Step 17: Setting the Interface


Place the MenuScreen in the stage again and center it. It should be on top of the game graphics.

Step 18: ActionScript Time!


Its time for ActionScript. Create a new ActionScript File and save it as Main.as in the classes folder.

Step 19: Package


package classes
{

The package keyword allows you to organize your code into groups that can be imported by other scripts. Its
recommended to name them starting with a lowercase letter and use intercaps for subsequent words, for example:
myClasses.
If you dont want to group your files in a package or you have only one class you can use it right from your source
folder, but the idea is to be organized.

Step 20: Import Necesary Classes


These are the required classes. For a more detailed description about every class, please refer to the Flash Help
(F1).

import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.events.Event;
/* Import classes for animations */
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

Step 21: Declaring and Extending the


Class
The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods,
properties and functions, that way we can use them in our class.

public class HangmanPlus extends Sprite


{

In this example, the HangmanPlus class inherits all the methods and properties of the Sprite Class.

Step 22: Variables


There are a lot of variables in this game, this is because a lot of things can vary. Youll find everything explained in
the comments.

/* categories, the loader funtion will load a text file using the names in
this array
if you want to add a category, just add the text file to the directory
where Hangman+.swf is
and the name of the file to the array */
private var categories:Array = new Array("Fruits","Animals", "Sports");
private var category:int = 0;// This variable will be changed in the Options,
when the user click the More Button 1 is added, then used in the array to
choose the correct category
private var correctLetters:int = 0;//The correct letters guessed, it will be
compared to the letters array length to check if word is complete
private var tries:int = 6;//The number of tries, (head, body, two arms, two
legs)
private var btnSnd:ButtonSound = new ButtonSound();// The sound that will
play when a keyboard button is pressed
private var inactive:Inactive;//The clip that we will use to block the keys
already pressed
private var icontainer:Array = new Array();//An array to store the inactive
clips for effective removal

private var keys:int = 0;//A variable to count the keys that are already
inactive, this var indicates the number of "icontainer" to remove
private var index:int;//Stores the value of the String.search method, used to
search for the key pressed in the word hidden
private var buttons:Array;//The array of buttons names, used to add all the
listeners easily
private var txtLoader = new URLLoader();//This will load the text file
specified
private var allWords:String;//A string with all the words contained in the
text file
private var allWordsArray:Array = new Array();//Containes the allWords var,
separated by word
private var currentWords:String;//The current word(s) to be guessed
private var fmt:TextFormat = new TextFormat();//TextFormat
private var us:Underscore;//The underscore clip
private var usContainer:Sprite;//A container for the underscores
private var letters:Array;//The letters of the current word
private var tf:TextField;//TextField
private var tfCont:Sprite;//Contains the textfields
private var tfs:Array = new Array();Stores the textfields, used to remove
them
private var tween:Tween;//Tween, for animation
private var spaces:int = 0;//Stores the spaces in the current word(s)
private var arrayIndex:int;//Stores the words that have not been used
private var options:OptionsView;// The options view clip
private var about:AboutView;
private var alert:AlertView;
private var correct:int = 0;//The correct words counter
private var fails:int = 0;//Fails counter
private var victory:int = 3;//Default victorys to win
private var lives:int = 3;//Default lives
private var alertIsOnStage:Boolean = false;//True if AlertView is in stage

Step 23: Constructor


The constructor is a function that runs when an object is created from a class. This code is the first to execute when
you make an instance of an object, or runs using the Document Class.

public function HangmanPlus():void

{
/* Have to declare the new Array in the constructor in order to detect
that the (array) elements are MovieClips in Stage*/
buttons = new Array(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q,
R, S, T, U, V, W, X, Y, Z);
/* Menu Screen buttons */
menuScreen.newGame.addEventListener(MouseEvent.MOUSE_UP, init);
menuScreen.about.addEventListener(MouseEvent.MOUSE_UP, showAboutView);
menuScreen.options.addEventListener(MouseEvent.MOUSE_UP,
showOptionsView);
/* Create textfields for word */
fmt.color = 0x282425;
fmt.font = "Avenir 85 Heavy";
fmt.size = 18;
hideParts();//Hides the hangman parts
}

Step 24: Start Function


This function is executed when the user clicks the New Game button.

private function init(e:MouseEvent):void


{
addButtonListeners(buttons);//Adds the listeners to the keyboard
back.addEventListener(MouseEvent.MOUSE_UP, opBackHandler);//Adds the
listener to the back button
loadTxt(categories[category] + ".txt");//Loads the Text File from the
array, the function is created later
categoryText.text = categories[category];//Sets the category text
value, this is shown in the top of the notebook graphic
categoryLP.text = categories[category];

tween = new Tween(menuScreen,"y",Strong.easeOut,menuScreen.y, menuScreen.height / 2,0.8,true);//Creates a tween animating the MenuView up


correct = 0;//Resets the correct and failed guesses
fails = 0;
}

Step 25: Restart Function


This function restarts some variables and settings to load a new word, no matter if the word was guessed or not. Its
called when the word animation ends.

private function restart(e:TweenEvent):void


{
/* Restarts some initial vars */
hideParts();
correctLetters = 0;
addButtonListeners(buttons);
tries = 6;
spaces = 0;
tfs = new Array();
removeChild(tfCont);//Removes the textfields of the word
for (var j:int = 0; j < keys; j++)
{
removeChild(icontainer[j]);//Removes the button inactive
clips, according to the keys pressed
}
removeChild(usContainer);//Removes the underscores
/* Removes last word from array to avoid duplicates */
arrayIndex = allWordsArray.indexOf(currentWords);
allWordsArray.splice(arrayIndex, 1);

/* Load another word from array */


currentWords = allWordsArray[Math.floor(Math.random() *
allWordsArray.length)];
letters = currentWords.split("");//Split letters to compare everyone
to space
createUnderscores(currentWords);
createTextfields();
keys = 0;
icontainer = new Array();
}

Step 26: Load File


Loads a TextFile. This function is executed in Step 24.

private function loadTxt(file:String):void


{
txtLoader.load(new URLRequest(file));
txtLoader.addEventListener(Event.COMPLETE, parseTxt);//Adds a listener
to parse the text
}

Step 27: Parse Text


Parses the text to create the necesary underscores and textfields.

private function parseTxt(e:Event):void


{
allWords = e.target.data;//Gets the data of the txtLoader
allWordsArray = allWords.split(",");//Splits the words, the words in
the text file MUST be UpperCase and comma separated
currentWords = allWordsArray[Math.floor(Math.random() *
allWordsArray.length)];//Sets a random word(s) to the currentWords variable

letters = currentWords.split("");//Split letters to compare everyone


to space
createUnderscores(currentWords);
createTextfields();
}

Step 28: Back Button Actions


The Back button removes unnecesary data, restarts variables and sends the user to the Menu Screen.

private function opBackHandler(e:MouseEvent):void


{
/* Remove alert if it's in stage */
if(alertIsOnStage)
{
removeChild(alert);
alertIsOnStage = false;
}
tween = new
Tween(menuScreen,"y",Strong.easeOut,menuScreen.y,stage.stageHeight /
2,1,true);//Animate back the Menu View
back.removeEventListener(MouseEvent.MOUSE_UP, opBackHandler); //Remove
the listener from the button
removeButtonListeners(buttons);//Remove the keyboard listeners
hideParts();//hides hangman parts
/* Restart variables, see restart function */
correctLetters = 0;
tries = 6;
spaces = 0;
tfs = new Array();
removeChild(tfCont);

for (var j:int = 0; j < keys; j++)


{
removeChild(icontainer[j]);
}
removeChild(usContainer);
keys = 0;
icontainer = new Array();
}

Step 29: Underscores


This function creates the underscores according to the letters and spaces in the chosen word(s).

private function createUnderscores(words:String):void


{
usContainer = new Sprite();
for (var i:int = 0; i < words.length; i++)
{
us = new Underscore();
us.x = (us.width + 3) * i;
if (letters[i] == " ")
{
spaces++;
}
else
{
usContainer.addChild(us);
}
}
usContainer.x = (stage.stageWidth / 2) - (usContainer.width / 2) +
(us.width / 2);
usContainer.y = (stage.stageHeight / 2) + 10;

addChild(usContainer);
}

Step 30: TextFields


The createTextfields() function creates the necesary TextFields to display a single letter of the word(s) in each one.

private function createTextfields():void


{
tfCont = new Sprite();
for (var i:int = 0; i < letters.length; i++)
{
tf = new TextField();
tf.width = 20;
tf.height = 30;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.selectable = false;
tf.defaultTextFormat = fmt;
tf.x = (us.width + 3) * i;
tfs.push(tf);
tfCont.addChild(tf);
}
tfCont.x = (stage.stageWidth / 2) - (usContainer.width / 2) - 3;
tfCont.y = (stage.stageHeight / 2) - 10;
addChild(tfCont);
}

Step 31: Hide Parts Function


Lets hide the parts of the hangman.

private function hideParts():void


{
body.visible = false;
head.visible = false;
leftArm.visible = false;
leftLeg.visible = false;
rightArm.visible = false;
rightLeg.visible = false;
}

Step 32: Keyboard Actions


This is a core function. It will search if the letter pressed is in the current word to guess, disable the key, play a key
sound, add the key to stage in case it exists, check if the word is complete or if the chances are over.

private function onKeyPress(e:MouseEvent):void


{
/* Get and Disable key */
inactive = new Inactive();
inactive.x = e.target.parent.x;//Added "parent" because flash
recognizes the MC inside as "name"
inactive.y = e.target.parent.y;
addChild(inactive);
icontainer.push(inactive);
keys++;
/* Plays sound */
btnSnd.play();
/* Check if letter is on word */
index = currentWords.search(new String(e.target.parent.name));
if (index != -1)
{
/* Letter is on word */

for (var i:int = 0; i < letters.length; i++)


{
if (new String(e.target.parent.name) == letters[i])
{
tfs[i].text = new String(e.target.parent.name);
correctLetters++;
}
}
if (correctLetters + spaces == letters.length)//If word is
complete
{
win();
removeButtonListeners(buttons);
}
}
else
{
tries--;
switch (tries)//Shows the parts of the hangman
{
case 6 :
trace(6);
break;
case 5 :
head.visible = true;
break;
case 4 :
body.visible = true;
break;
case 3 :
leftArm.visible = true;
break;
case 2 :
rightArm.visible = true;
break;
case 1 :
leftLeg.visible = true;
break;
case 0 :

rightLeg.visible = true;
for (var j:int = 0; j < letters.length;
j++)//Shows the missing letters
{
if (tfs[j].length == 0)
{
tfs[j].textColor = 0xFF0000;
tfs[j].text = letters[j];
}
}
removeButtonListeners(buttons);
fail();
break;
default :
trace("Error");
}
}
}

Step 33: Keyboard Listeners


This code adds the keyboard listeners.

private function addButtonListeners(array:Array):void


{
for (var i:int = 0; i < array.length; i++)
{
array[i].addEventListener(MouseEvent.MOUSE_UP, onKeyPress);
}
}

And this removes the listeners.

private function removeButtonListeners(array:Array):void


{
for (var i:int = 0; i < array.length; i++)
{

array[i].removeEventListener(MouseEvent.MOUSE_UP, onKeyPress);
}
}

Step 34: Correct Word Function


This is the function that will execute when the user correctly guesses a word(s).

private function win():void


{
/* Check for victory */
correct++;
if(correct == victory)
{
alert = new AlertView();
alert.alertDialog.title.text = "You Win";
alert.alertDialog.titleLP.text = "You Win";
alert.alertDialog.content.text = "Click this dialog to
close.";
addChild(alert);
alertIsOnStage = true;
tween = new Tween(alert.alertDialog, "scaleX", Strong.easeOut,
0.5, 1, 0.5, true);//Shows the Alert View
alert.addEventListener(MouseEvent.MOUSE_UP, opBackHandler);
}
else
{
tween = new
Tween(tfCont,"x",Strong.easeIn,tfCont.x,stage.stageWidth +
tfCont.width,0.5,true);//Animates the word and sets a new one
tween.addEventListener(TweenEvent.MOTION_FINISH, restart);
}
}

Step 35: Wrong Word Function


This is the function that will execute when the user fails to correctly guess the word(s).

private function fail():void


{
/* Check for failure */
fails++;
if(fails == lives)
{
alert = new AlertView();
alert.alertDialog.title.text = "You Lose";
alert.alertDialog.titleLP.text = "You Lose";
alert.alertDialog.content.text = "Click this dialog to
close.";
addChild(alert);
alertIsOnStage = true;
tween = new Tween(alert.alertDialog, "scaleX", Strong.easeOut,
0.5, 1, 0.5, true);
alert.addEventListener(MouseEvent.MOUSE_UP, opBackHandler);
}
else
{
tween = new
Tween(tfCont,"x",Strong.easeIn,tfCont.x,stage.stageWidth +
tfCont.width,1,true);
tween.addEventListener(TweenEvent.MOTION_FINISH, restart);
}
}

Step 36: Options View


This function will handle the Options View animations.

private function showOptionsView(e:MouseEvent):void


{
options = new OptionsView();
addChild(options);
/* These are the values of the options, taken from the variables */
options.category.text = categories[category];
options.victory.text = String(victory);
options.lives.text = String(lives);
tween = new Tween(options, "x", Strong.easeOut, options.width, 0, 0.5,
true);//This makes the options view appear from right to left
/* Button listeners */
options.back.addEventListener(MouseEvent.MOUSE_UP, hideOptionsView);
options.catButton.addEventListener(MouseEvent.MOUSE_UP,
changeCategory);
options.vicButton.addEventListener(MouseEvent.MOUSE_UP,
changeVictory);
options.livesButton.addEventListener(MouseEvent.MOUSE_UP,
changeLives);
}
/* This function hides the OptionsView using an animation */
private function hideOptionsView(e:MouseEvent):void
{
options.removeEventListener(MouseEvent.MOUSE_UP, hideOptionsView);
tween = new Tween(options, "x", Strong.easeOut, 0, options.width, 0.5,
true);
tween.addEventListener(TweenEvent.MOTION_FINISH, removeOptionsView);
}

private function removeOptionsView(e:TweenEvent):void


{
/* Removes the child */
removeChild(options);
}

Step 37: Category Function


This function changes the category, taking the value from the categories array.

private function changeCategory(e:MouseEvent):void


{
category++;
if(category >= categories.length)
{
category = 0;
}
options.category.text = categories[category];
}

Step 38: Victory and Lives


Handles the victory and lives counter, the user can have up to 10 victories and 10 lives.

private function changeVictory(e:MouseEvent):void


{
victory++;
if(victory > 10)
{
victory = 1;
}

options.victory.text = String(victory);//Sets the value to the


textfield
}
private function changeLives(e:MouseEvent):void
{
lives++;
if(lives > 10)
{
lives = 1;
}
options.lives.text = String(lives);//Sets the value to the textfield
}

Step 39: About View


These functions show and hide the About View using a Tween animation.

private function showAboutView(e:MouseEvent):void


{
about = new AboutView();
addChild(about);
tween = new Tween(about, "x", Strong.easeOut, -about.width, 0, 0.5,
true);
about.addEventListener(MouseEvent.MOUSE_UP, hideAboutView);
}
private function hideAboutView(e:MouseEvent):void
{
about.removeEventListener(MouseEvent.MOUSE_UP, hideAboutView);
tween = new Tween(about, "x", Strong.easeOut, 0, -about.width, 0.5,
true);

tween.addEventListener(TweenEvent.MOTION_FINISH, removeAboutView);
}
private function removeAboutView(e:TweenEvent):void
{
removeChild(about);
}

Step 40: Document Class


Go back to the Fla and in the Properties Panel, Class textfield add "classes.Main". This will link the Main class as the
Document Class.
Now test your Hangman+ Game!

Conclusion
You have created a fully featured Hangman game in ActionScript 3; add your own categories and enjoy!
I hope you liked this Premium tutorial, thanks for reading!

Vous aimerez peut-être aussi