Sunday, 15 August 2010

Number guessing game in AS3 part 2

This is part 2 of the Number guessing game in Actionscript 3 where I will be limiting the number of guesses in the game. A message will display the number guesses left. If the correct answer is guessed, or the number of guesses is used up then an appropriate message will be displayed. Be sure you have completed the previous tutorial before attempting this one as additional code will be added.


Number guessing game in AS3 part 2

Step 1

Open up the Number guessing game in AS3.
Select the Text tool with dynamic text and create another text field below message field and give it the instance name: guess_txt.













Step 2

On the timeline select the Actions layer and open up the Actions panel and enter the following code.

**Note that I have not included the code from the previous tutorial.
//Declare variables
var numOfGuesses:uint ;
var numOfGuessesMessage:String;

function init():void {
    //Displays a message showing the total number of guessing remaining 
    numOfGuesses = 10;
    numOfGuessesMessage = " Guesses remaining";
    guess_txt.text = numOfGuesses + numOfGuessesMessage;
}

function yourGuess(event:MouseEvent):void {
    guessMessage();
}

function guessMessage():void{
    //Only decrement the numOfGuesses if the text field contains characters. 
    if(input_txt.length > 1 && numOfGuesses != 0){
        numOfGuesses--;
        guess_txt.text = numOfGuesses + numOfGuessesMessage;
    }
    
//If there is no guesses left then a message appears, and you can restart the game  
    if(numOfGuesses == 0){
        message_txt.text = "The number was " + randomNumber + ".";  
        guess_txt.text = "Unlucky, you never found the number.";
        endGame();
    }
    
}

**I have change the name of the winGame() function to endGame(), so you will need to update all instances of this name.


Step 3

Test your movie Clip Ctrl + Enter.

4 comments:

switch 15 January 2011 at 05:29  

first part works just fine, but after adding part-2 i receive this error:
Scene 1, Layer 'Actions', Frame 1, Line 41 1021: Duplicate function definition.
Scene 1, Layer 'Actions', Frame 1, Line 64 1021: Duplicate function definition.
I tried to delete something but still not working. Can you fix it or tell me what to do?

iliketo 15 January 2011 at 10:12  

@Switch

I haven't include all the code from the previous tutorial.

It looks like you have a function with the same name.

johnzach 16 January 2011 at 08:14  

i have two init ()void fuctions... what should i do??

iliketo 16 January 2011 at 14:41  

@johnzach

Like I mentioned in the above comment. I have not included all the code from the previous tutorial.

You will need to look at the previous tutorial and compare what is missing and what has been added.

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP