Monday, 14 December 2009

Number guessing game in AS3

In this Flash tutorial you will learn how to create a number guessing game in Actionscript 3.0. A number guessing game is where you have to guess a randomly selected number. If you guess the number wrong you will be prompted to select another number and if you guess the correct number, an appropriate message will appear.

I will be creating this game in two parts. The first part will create the game interface which will consist of creating the buttons and text fields, as well as adding the main Actionscript code for the game. The second part of the game will deal with adding additional features to the game such as limiting the amount of guesses and displaying the number of guesses.

Some knowledge of basic buttons will be needed for this tutorial.


Number guessing game in AS3

Step 1 – Game title

Open a new Flash AS3 file. Then select the Text tool (T) with static text and type the following message shown below. I have also given my message a double knocked out effect which is optional.




Step 2 – Create dynamic text fields

Select the Text tool (T) with dynamic text and drag a rectangular text field below your message. Then choose the format option ‘Align Center’ and give your dynamic text the instance name: message_txt. If your dynamic text characters look uneven, you may need to embed the following character glyphs: Uppercase, lowercase, numerals and punctuation.




Step 3 – Create input text fields

This time select the Text tool (T) with input text and drag an input text field below the dynamic text field. Make sure your input text field has enough room for three characters. I have selected the option ‘Show border around text’ which displays a black border around the input text field as shown below. I have also set the paragraph behavior to 'single line' and changed the 'Max Char' to 3 which will stop the more than three characters appearing.



Now give your input text field the instance name: input_txt.


Step 4 – Create buttons

Create two buttons on the stage below the input text field. If you don’t know how to create buttons checkout the basic buttons tutorial. You can alternatively use two button components, or the built in button library. One of the buttons should have the name “Guess” and the other with the name “Play Again” like below.



Give the buttons the following instance name respectively: guess_btn and playagain_btn.

So, the game interface should now look like below:




Step 5 – Add code

On the timeline insert a new layer called ‘Actions’ then open up the Actions panel and enter the following code:

//Declares variables.
var beginMessage:String;
var randomNumber:uint;
var my_guess:uint;

function init():void {
//Initally disables the play again button, and enables the guess button.
playagain_btn.enabled =false;
guess_btn.enabled = true;

//Display a begining message in the message_txt dynamic text field.
beginMessage="Choose a number between 1 - 100.";
message_txt.text=beginMessage;

//Restrict the characters in the input_txt text field, so only the
//numbers 0 - 9 can be entered.
input_txt.restrict="0-9";

//Clears the input text field.
input_txt.text="";

//This stores a random number between 1 - 100 to the variable randomNumber.
randomNumber = Math.floor(Math.random() * 100 + 1);

//Adds an event listener to the guess button.
guess_btn.addEventListener(MouseEvent.CLICK, yourGuess);
}

function yourGuess(event:MouseEvent):void {
//This stores data from the input text field to the variable my_guess.
my_guess=uint(input_txt.text);

//This checks if the guessed number is greater than the random number.
if (my_guess > randomNumber) {
message_txt.text = "Your guess, " +  my_guess + " is too high.";
}
//This checks if the guessed number is lower than the random number.
else if (my_guess < randomNumber) {                        
message_txt.text = "Your guess, " +  my_guess + " is too low.";          
}    

//This displays a message when the correct number is guessed.   
else{         
message_txt.text = "Well done, the number is " + randomNumber + "."; 
winGame();         
}
}  


function winGame():void{        
//Disables the guess button and enables the play again button.          
guess_btn.enabled = false;          
playagain_btn.enabled = true;           

//Removes the listener from the guess button, and adds a listener to the          
//play again button.         
guess_btn.removeEventListener(MouseEvent.CLICK, yourGuess);          
playagain_btn.addEventListener(MouseEvent.CLICK, guessAgain);
}    

function guessAgain(event:MouseEvent):void{          

//Runs the init() method.          
init();
}   

//Runs the init() method.
init(); 
Step 6 – Test

Test your number guessing game Ctrl + Enter.
 
You should now have number guessing game in Actionscript 3.0. Checkout part 2. You can download the source files here.

16 comments:

Anonymous 16 December 2009 at 03:42  

You should deactivate the multiline option.

iliketo 16 December 2009 at 05:41  

@Anonymous

It doesn't make a difference.

Anonymous 20 December 2009 at 03:01  

Sure it does, because the number you typed in won't disappear and you could set an EventListener which reacts to a Return-Click, which does the same as the Guess-Click.

iliketo 20 December 2009 at 03:23  

@Anonymous

Your correct. I have updated the tutorial, so that only three characters can be entered in the input text field.

Mike Engz 18 February 2010 at 14:27  

i have done it but it dosnt work :S could i send it to someone and they have a look at it and tell me what was wrong with it please?

iliketo 19 February 2010 at 06:23  

I quite busy at the moment, you can alternatively download the source files here

Reymond 15 August 2010 at 02:56  

This bit of code it wrong:

//Restrict the characters in the message_txt text field, so only the
//numbers 0 - 9 can be entered.
message_txt.restrict="0-9";

//Clears the input text field.
input_txt.text="";

You would want to restrict the input_txt not the message_txt.

Or I think thats what you where trying to do.

iliketo 15 August 2010 at 06:11  

@Reymond

Good spot, code updated.

bleah 17 October 2010 at 16:38  

Hey there,

I just tried out the number guessing game...I noticed sometimes it doesn't count down the number of tries left, after a guess...

For example, if I guess 6, then 5...it stays with the same number of guesses left

iliketo 18 October 2010 at 10:11  

@bleach

It only counts the number of tries in part 2

Policeman655 9 January 2011 at 07:36  

I got these errors

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 3: The class or interface 'uint' could not be loaded.
var randomNumber:uint;

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 4: The class or interface 'uint' could not be loaded.
var my_guess:uint;

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 6: A type identifier is expected after the ':'.
function init():void {

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 29: The class or interface 'MouseEvent' could not be loaded.
function yourGuess(event:MouseEvent):void {

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 50: A type identifier is expected after the ':'.
function winGame():void{

**Error** Scene=Scene 1, layer=Actions, frame=1:Line 61: The class or interface 'MouseEvent' could not be loaded.
function guessAgain(event:MouseEvent):void{

Total ActionScript Errors: 6 Reported Errors: 6

iliketo 10 January 2011 at 11:31  

@Policeman655

It looks like your not using Actionscript 3.

JoeyyCyrus 20 January 2013 at 10:07  

how do I insert written text into the buttons to allow them to still be pressed. I try put a text box over the top but just stops me from pressing the button?? help

iliketo 20 January 2013 at 12:13  

@JoeyyCyrus

Please look at step 4.

Halem M Saad 28 December 2013 at 07:37  

is there a way to make the system count how many tries that user enter and show it at the end with the result?

iliketo 2 January 2014 at 04:25  

@Halem,

Yes, you can create a variable to hold the number of tries. The variable would be incremented inside the yourGuess function.

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP