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.

 import flash.display.MovieClip;
 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; 
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{
 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;

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 = '';
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.


Micah Young 3 November 2012 at 12:52  

Nice one, keep up the good work

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP