Saturday, 27 November 2010

Letter guessing game in AS3

This tutorial is a modification of the Number guessing game, but this time it uses letters from the Alphabet instead of numbers. This game accepts both uppercase and lowercase characters, so if the randomly generated letter is ‘p’ and you guess with an uppercase p it will still recognise that the correct letter has been guessed. Note that you need to have completed the Number guessing game tutorial before attempting this one.

Letter guessing game in AS3

Step 1

Open up the Number guessing game tutorial. Then open up the Actions panel and make the following changes below. Note that I have not included all the code from the previous tutorial.

//Declares variables.
var lettersArray: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"];

function init():void {
//Display a begining message in the message_txt dynamic text field.
beginMessage="Choose any letter in the Alphabet.";

//Restrict the characters in the message_txt text field, so only the 
//upper and lower case letter can be accepted.
input_txt.restrict="A-Z a-z";

//This stores a random letter from the letterArray to the variable randomLettter.
randomLetter = lettersArray[Math.floor(Math.random() * lettersArray.length)];

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

//If the correct guessed letter is either upper or lower case then go win message. 
if(my_guess == randomLetter.toUpperCase() || my_guess == randomLetter.toLowerCase()){
message_txt.text = "Well done, the letter is " + my_guess + ".";  
message_txt.text = "Your guess, " +  my_guess + " is incorrect.";

function guessMessage():void{
//Only decrement the numOfGuesses if the textfield contains characters. 
if(numOfGuesses != 0 && input_txt.length == 1){
guess_txt.text = numOfGuesses + numOfGuessesMessage;

if(numOfGuesses == 0){
message_txt.text = "The number was " + randomLetter + ".";  
guess_txt.text = "Unlucky, you never found the number.";

Step 2

Test your movie Ctrl + Enter.

You can download the source files here.


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP