Thursday, 25 August 2011

Math game in Actionscript 3 – part 1

In this post you will learn how to create a Math game using Actionscript 3. This will be a simple game where you have to answer twenty math questions. At the end of the game, there will be a time to show how long it took to answer the questions.

Math game in Actionscript 3 – part 1

Step 1 – Initial set up

Open a new Actionscript 3 file and save it with the name ‘MathGame’. Change the stage dimensions to 300 x 400 pixels. Then open a new Actionscript 3 class file and save it with the name ‘MathGame’. Set the document class in the FLA to ‘MathGame’.


Step 2 – Create buttons

Select the Rectangle Primitive tool with a 6 pixel corner radius, and create 10 rectangles with the dimensions 52 x 52 pixels with 0xffffff colour on the stage. Then select the Text tool with static text and type the numbers 0 – 9 in the centre of the rectangles. I have used the Verdana font with 35pt and the colour 0x000000. The clear button is also created using the Rectangle primitive tool with a 6 pixel corner radius. The dimensions are 127 x 52 pixels.

Once all the buttons have been created, convert them into movie clips (F8). Give them the instance names: oneBtn, twoBtn, clearBtn etc.


Step 3 – Add text fields

Select the Text tool with dynamic text and create two text fields on the stage. Give the text fields instance names: output_txt and display_txt. The output text field will be used to display the 0 - 9 numbers the user presses, so the numeral character glyphs will need to be embedded. The display text field will be used to show the Math questions. The numeral character glyphs will also need to be embedded, along with a ‘+’ character sign. To make the two text fields unselectable, you need to select the ‘selectable’ button on the paragraphs panel.


Step 4 – Start and end screens

Firstly, create the start screen by selecting the Rectangle tool and create a rectangle shape the size of the stage dimensions. I have used 0xB5E5FE colour. Type the heading ’Math quiz’ using the Text tool with static text. Then create a start button, convert it to a movie clip and give it the instance name: ‘startBtn’. Select everything on the start screen and convert it into a movie clip and give it the instance name: ‘startScreen’. The end screen is similar to the start screen. Create a rectangle shape the size of the stage dimensions. Select the Text tool with static text and type the message: ‘Well done’. Now create a dynamic text field below this message and give it the instance name: time_txt. Then create a restart button, convert to a movie clip and give it the instance name: restartBtn.


Step 5– Code

In the MathGame class file add the following code. To begin add the necessary import statements and the variables.

package 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 import flash.utils.setTimeout;
 import flash.utils.getTimer;
 
 public class MathGame extends MovieClip 
 {
  private var buttonsArray:Array = new Array();
  private var num1Array:Array = new Array();
  private var num2Array:Array = new Array();
  private var answersArray:Array = new Array();
  private var count:uint = 0;
  private var numOfQuestions:uint = 20;
  private var numRange:uint = 20;
  private var startTime:uint;
  private var currentTime:uint; 
  
  public function MathGame() {
  
  }
 }
}

Inside the constructor add the following. This code adds the buttons instances into the buttonArray. A For loop is used to add the buttonClicked function and the mouse cursor to all the buttons. The endScreen movie clip is initially set to invisible. And the mouse click event is added to the start and restart buttons inside the startScreen and endScreen.

buttonsArray = new Array(oneBtn,twoBtn,threeBtn,fourBtn,
fiveBtn,sixBtn,sevenBtn,eightBtn, nineBtn, zeroBtn, clearBtn);
   
for(var i:uint = 0; i < buttonsArray.length; i++){
 buttonsArray[i].buttonMode = true;
 buttonsArray[i].addEventListener(MouseEvent.CLICK, buttonClicked);
}
   
endScreen.visible = false;
   
startScreen.startBtn.addEventListener(MouseEvent.CLICK, startGame);
endScreen.restartBtn.addEventListener(MouseEvent.CLICK, restartGame);

This startGame function sets the startScreen movie clip to invisible and call the init() function. The init() function sets the startTime which will return the milliseconds since the Flash movie started. The currentTime is set to 0. If the currentTime is subtracted from the startTime, you can calculate how long the game has been playing. The For loop is used to add 20 random numbers from 1 – 20 into two different arrays. A third array is used to calculate the result of array 1 and array 2. The Math question is displayed in the display_txt text field.

private function startGame(e:MouseEvent):void{
 startScreen.visible = false; 
 init();
}
  
private function init():void { 
startTime = getTimer();
currentTime = 0;
   
for(var j:uint = 0;  j < numOfQuestions; j++){
 num1Array.push( uint(Math.random() * numRange)+1 );
 num2Array.push( uint(Math.random() * numRange)+1 );

 answersArray.push( num1Array[j] + num2Array[j] );
}
 display_txt.text = num1Array[count] + ' + ' + num2Array[count];  
}

This function adds the appropriate number to the ‘output_txt’ text field using the appendText() method. The checkResult() function is also called after a 400 millisecond delay.

private function buttonClicked(e:MouseEvent):void{
switch(e.target){
 case zeroBtn: output_txt.appendText('0'); break;
 case oneBtn:   output_txt.appendText('1'); break;
 case twoBtn:  output_txt.appendText('2'); break;
 case threeBtn:  output_txt.appendText('3'); break;
 case fourBtn:  output_txt.appendText('4'); break;
 case fiveBtn:  output_txt.appendText('5'); break;
 case sixBtn:  output_txt.appendText('6'); break;
 case sevenBtn: output_txt.appendText('7'); break;
 case eightBtn:  output_txt.appendText('8'); break;
 case nineBtn:  output_txt.appendText('9'); break;
 case clearBtn:  output_txt.text ='';     break;
}
 setTimeout(checkResult,400);
}

This function checks if the correct answer is displayed. If the correct answer is displayed then the ‘output_txt’ text field is cleared; the count variable is incremented; and a new question is displayed in the ‘display_txt’ text field. When all the questions have been answered the ‘display_txt’ text field gets cleared; the endScreen is set to visible and the time taken to complete the quiz is displayed.

private function checkResult():void{
if(output_txt.text == answersArray[count]){
output_txt.text = '';
count++;
display_txt.text = num1Array[count] + ' + ' + num2Array[count];
}
   
if (count == numOfQuestions) {    
display_txt.text ='';
      
 endScreen.visible = true;
 currentTime = getTimer() - startTime; 
 var seconds:int = Math.floor(currentTime/1000);
 var minutes:int = Math.floor(seconds / 60);
 endScreen.time_txt.text = 'Time: ' + minutes + ':' + String((seconds % 60)+100).substr(1,2);
}
}

This function resets the count and currentTime to 0, and clears the arrays. The startScreen movie clip is also set to visible and the endScreen movie clip to invisible.

private function restartGame(e:MouseEvent):void{
count = 0;
num1Array = [];
num2Array = [];
answersArray = [];
currentTime = 0;
endScreen.visible = false;
startScreen.visible = true; 
}

Step 6 – Export movie

Export movie Ctrl + Enter. You should now have a Math game in Actionscript 3.



Why not take a look at the Blur guess game, or the Simple shooting game.

Saturday, 20 August 2011

Create a soundboard in Actionscript 3

This post is an update to the Soundboard tutorial in Actionscript 2. I created the soundboard back in 2008 when I was still using Flash 8. In that version I added the audio clips into the down state of the buttons. This increased the overall file size as all the sound clips were embedded in the swf. However, in this AS3 version I will load the sound clips in dynamically which will reduce the file size of the swf. You will of course need some sound files for this tutorial.


Create a soundboard in Actionscript 3

Step 1

Firstly, create a new folder called ‘Sounds’ to hold all your audio files. Then open up a new AS3 file and save it with the name ‘Soundboard’ in same directory level as the Sounds folder.


Step 2

On the stage create your buttons. You can use the primitive shape tools or you can import images. Once you have created all the buttons convert them into movie clips (F8) and give them appropriate instance names.


Step 3

On the timeline insert a new layer called ‘Actions’ then open up the Actions panels and enter the following code. You will need to change the values in the buttonsArray and the soundArray to the names of your files.

//Array for buttons instances.
var buttonsArray:Array = new Array();
buttonsArray[0] = butt1;
buttonsArray[1] = butt2;
buttonsArray[2] = butt3;
buttonsArray[3] = butt4;
buttonsArray[4] = butt5;
buttonsArray[5] = butt6;

//Array for the sound clip names.
var soundArray:Array = new Array();
soundArray[0] = 'sounds/sound1.mp3';
soundArray[1] = 'sounds/sound2.mp3';
soundArray[2] = 'sounds/sound3.mp3';
soundArray[3] = 'sounds/sound4.mp3';
soundArray[4] = 'sounds/sound5.mp3';


//This adds the mouse click event to the buttons. 
for(var i:uint = 0; i < buttonsArray.length; i++){
 buttonsArray[i].addEventListener(MouseEvent.CLICK, buttonClicked);
}

//This function stops any sound clip that is playing and
//plays the sound file thats clicked.
function buttonClicked(e:MouseEvent):void{ 
 SoundMixer.stopAll();
 
 for(var i:uint = 0; i < buttonsArray.length; i++){
  if(e.target == buttonsArray[i]){
   var s:Sound = new Sound();
   s.load(new URLRequest(soundArray[i]));
   s.play();
  }
 }
}

//This function adds a keyboard down event to the stage 
//to stop a sound when the space bar is pressed.
stage.addEventListener(KeyboardEvent.KEY_DOWN, spacebarClicked);

function spacebarClicked(e:KeyboardEvent):void{ 
 if(e.keyCode == 32) SoundMixer.stopAll();
}
Step 4

Export your movie Ctrl + Enter. You should now have a Soundboard in Actionscript 3.



Related posts
Playing sound files in Actionscript 3
Play external sound file in Actionscript 3
Toggle sound button in Actionscript 3

Thursday, 11 August 2011

HTML5 Canvas - loading images

Here are some examples of loading images to the HTML5 canvas. I have used the canvas template from this post. The first example loads a single image by creating a new Image object and adding the image onto the canvas once the image has loaded. The drawImage() method renders the image object onto the canvas. The method has three parameters: the first is the reference to the image, the second is the x coordinate position and the third is the y coordinate position.

//Loads single image
var img = new Image();
img.src = "assets/image-1.jpg";
img.onload = function(){
 context.drawImage(img,100,100);
}

The scaling of the image can be altered with the width and height parameters which are the fourth and fifth parameters of the drawImage() method. This example will load the image at 100 on the x and y axis, set the width to 80 and the height to 40.

//Scale image
var img = new Image();
img.src = "assets/image-2.jpg";
img.onload = function(){
 context.drawImage(img,100,100,80,40);
}

Multiple images can be loaded using a function. I have used the loadImages() function to load an array of images and to call a function when all the images have loaded. The images will appear in a 5 x 2 grid.

//Load multiple images 
var xpos = 100;
var ypos = 100;
var imgoffset = 70;
var cols = 5;
   
var imgArray = ["assets/image-1.jpg","assets/image-2.jpg","assets/image-3.jpg", "assets/image-4.jpg","assets/image-5.jpg","assets/image-6.jpg","assets/image-7.jpg","assets/image-8.jpg", "assets/image-9.jpg","assets/image-10.jpg"];
   
function loadImages(arr, callBack){
var count = 0;
 var img = [];
    
 for(var i in arr ){
  img[i] = new Image();
  img[i].src = arr[i];
  img[i].onload = function(){
   count++;
   if(count == arr.length){
    callBack(img);
   }
  }
 }
} 
   
  
function imageLoaded(img){
//creates a 5 x 2 grid
 for(var i in imgArray){
  var xoffsets = xpos +  imgoffset * (i%cols);
  var yoffsets = ypos +  imgoffset * Math.floor(i/cols);
  context.drawImage(img[i],  xoffsets, yoffsets );
 }
}
  

loadImages( imgArray, imageLoaded );

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP