Programming with ActionScript 3: Flashosophy Cram Session Part IV (Methods/Functions)

Introduction:

Like loops and arrays, functions are designed to make a programmer's life easier. Functions allow you to reuse code. Methods are just another way of saying function and vice versa.

Section 1: Calling a Basic Function

Example:

sayHello(); //this is call the function sayHello();

function sayHello():void //the colon void means there is no return type; more on this later.
{
  trace("Hello!"); //when this function is called, "Hello!" will be in the output
}

Easy enough right? Less talk, more examples!

Section 2: Functions That Return Values

Example:

var age = getAge(); //age will equal to whatever getAge() returns
trace(age); //you can also do trace(getAge()) instead of assigning it to a variable

function getAge():uint //this function returns an unit to the caller
{
  return 24; //this will return the number 24
}

You may place the function anywhere in the code. You can return other types too like Booleans, Strings, Numbers, Arrays, Objects, etc.

Section 3: Passing In Parameters Into A Function

Example:

var counter:uint = 0;
addToCounter(2); //you are passing in the number 2 into the function addToCounter

//this function has one paramete of t ype uint; it can be named whatever.
function addToCounter(in_num:uint)
{
   counter += in_num;
   trace(counter); //remember that you can put a trace anywhere.
}

You can call addToCounter mutiple times. Do it and investigate the output.

You can also add multiple parameters.

Example:

trace( doAddition(3,9); ) //parameters are separated by a comma

function addToCounter(in_first:int, in_second:int):int //returns int
{
   return (in_first + in_second); //you should get 12
}

Section 4: Scope Of A Function

Variables created inside a function cannot be seen outside of the function.

Example:

var tempNum:uint = 3;
calcNum();

function calcNum()
{
   var tempNum = 100; //this variable will be gone from memory as soon as you exit the method.
   trace(tempNum); //output 100
}
trace(tempNum); //outputs 3

Section 5: Putting It All Together

Let's make use of what we've learned so far with this example.

var pointArray:Array = new Array(5,4,3,2,1,1,2,3,4,5);
var myPoints:int = 0;
var cpuPoints:int = 0;
var loopLength = pointArray.length; //10
var myOutput:String = "My Points: ";
var cpuOutput:String ="CPU Points: ";

startProgram();

function startProgram()
{
 for(var i=0; i < loopLength; i++) //this will go 10 times, the length of the array
 {
   var tempRanNum = Math.random(); //generates a number from 0 to 1
    if(tempRanNum > .5) //if the random number is greater than .5, you get the points
   {
    updateMyPoints();
   }
   else //otherwise, cpu gets the points
    {
      updatecpuPoints();
    }
  } //end for loop

   printOutput();
}//end function

function updateMyPoints(){ //you can put the brace up here too.
   var popedScore:uint = pointArray.pop();
   myPoints += popedScore; //adds the value of the highest index in pointArray
   myOutput += popedScore + "\t"; //puts a tab between points for output
}

function updatecpuPoints(){
   var popedScore:uint = pointArray.pop();
   cpuPoints += popedScore; //adds the value of the highest index in pointArray
   cpuOutput += popedScore + "\t"; //puts a tab between points for output
}

function printOutput(){
  trace( myOutput + " Total: " + myPoints);
  trace( cpuOutput + " Total: " +cpuPoints);

  if(myPoints > cpuPoints) // braces are not required if only one statement will be executed
    trace("You win!!!") //only one statement
   else //braces are not requires if there is only 1 statement after an else statement
    trace("You lost!")
}

Sample Output (different when ran every time):
My Points: 5 4 3 2 4 Total: 18
CPU Points: 1 1 2 3 5 Total: 12
You win!!!

You've successfully created your first mini game!

This example is 50 lines of code. It would take over 500 lines of code if this was done without loops and methods.

Section 6: Exercise

Is this game like a heads or tails coin game because the probability is 50/50 for winning and losing? Does this mean if played many times, your score and the computer's score should be about the same? Would it also mean that the win/lose ratio would also be 50/50 on the long run?

Why not find out by modifying this mini game?
- Add the scores of 100 games and compare the output of your and the cpu's points
- Add the number of wins and loses
- Then do this for 1000 games

And of course don't manually count or add them with your eyes and brain; program it so that it calculates it for you.

Ending Summary

If you are able to complete the exercise in section 6, you are now ready to move on to learn about using your skills with Flash. The skills you have learned in these 4 cram sessions can be used in any high level programming language; not just action script 3.

You are no longer an absolute beginner to the programming world.

Published On: July 19, 2008

Previous Chapter: Flashosophy Cram Session Part III (Arrays and Loops)

 

(c) 2008 Flashosophy