Beginning Flash and ActionScript Game Programming Part 6: Basic Programming Concepts-Functions

In the previous section, we learned about loops and using loop, which allow us to perform multiple actions repeatedly and quickly.

In this section, we’ll look at creating functions, which allow us to create re-usable code, and seperate parts of code that do specific actions, in meaningful ways.

Function Structure

Functions are used for calling specific actions. For instance, if you wanted to damage a certain enemy, you could call the function to damage it, which might include taking away health, checking if the enemy is now dead, and spawning a reward for killing that enemy.

Functions are created using the keyword ‘function’, a space and the name of the function, a set of paranthesis with any parameters passed in that the function will need, and squigly brackets to contain what the function does.

It’s best to show by an example:

function ShowPlayerInfo():void
{
	trace("Player Name: "+"Timmy");
	trace("Player Age: "+"17");
	trace("Player Location: "+"Nevada");
}

ShowPlayerInfo();
trace("Again, player info is:");
ShowPlayerInfo();

//this will print out:
//Player Name: Timmy
//Player Age: 17
//Player Location: Nevada
//Again, player info is:
//Player Name: Timmy
//Player Age: 17
//Player Location: Nevada

The main thing you want to get from this code block is just how to setup and call a function.

On line 1, we first use the keyword ‘function’ to let the compiler know we’re creating a function, then whatever name we want to use for the function, a set of paranthesis, a colon and the type of object the function will return.

You use the keyword ‘void’ to say that nothing will be returned from the function- but you could return a Boolean value, say if you wanted to check if someone was old enough to get in a movie – returning a true or a false from the function.

Next, you use squiggly brackets, and put whatever you want the function to do inside of it. Here I just have it trace out 3 seperate lines.

Lastly, you just have to call the function, using the function name, and the paranthesis, which will “run” the function. Here I call it twice, to show that it repeats whatever is inside of it.

Passing in parameters

The real power of functions is being able to pass a parameter into it, and have it handle it differently.

For an example:

function IsOldEnough(name:String, age:int, alive:Boolean=true):void
{
	if(age>=18)
		trace(name+" is old enough to smoke");
	else
		trace(name +" is not old enough to smoke");
		
	if(!alive)
		trace("Looks like "+name+" has already smoked too much!");
}

IsOldEnough("Tim", 36);
IsOldEnough("Sue", 17);
IsOldEnough("Jim Bob", 68, false);

//this will output:
//Tim is old enough to smoke
//Sue is not old enough to smoke
//Jim Bob is old enough to smoke
//Looks like Jim Bob has already smoked too much!

On line 1, we again create the function using the keyword ‘function’, the name we want for our function, and then paranthesis.

But this time, we pass parameters to the function through the paranthesis. I say the first variable I’d want to pass in will be named ‘name’ inside the function, and be of type ‘String’.

Next, using a comma, I say I will also pass in a variable with the type of ‘int’ and name it age inside the function. Lastly I say I will pass in a value for “alive”, or type Boolean, but with a default value of “true”.

Putting a default value on a variable will make that variable “optional”, so that you are not required to have to pass a value in when you call the function.

Optional parameters can only be placed after all the required parameters, you cannot put an optional parameter before a required one.

By providing the parameters, we are specifying what type of variables we will be sending to the function to have access to, and what they will be refered to inside the function as.

So after the function parameters are passed in, we just have to specify what the function will do.
Here, we just check to see if the age is above or below 18, and print out something different for them, and then check if alive is set to false, and print out something for it as well.

Alive is set to true by default, so the first two function calls have the alive variable set to true, whereas the 3rd function call we pass in a value for alive as “false”.

Returning values from functions

Returning values from a function is something very valuable that functions can do. From finding an answer to a question, to returning a calculated value, it is an invaluable piece of functions.

For example:

function VolumeOfBox(length:Number, width:Number, height:Number):Number
{
  var volume:Number = length*width*height;
  return volume;
  
  //also could have used:
  //return length*width*height;
}
var volume1:Number=VolumeOfBox(8, 6, 2);
trace("volume 1 = "+volume1);
trace("volume 2 = "+VolumeOfBox(12, 4, 3));

//traces out:
//volume 1 = 96
//volume 2 = 144

In this example, we create a function to find the volume of a box (length*width*height), we create the parameters to be passed in, and we use “:Number” to say we will be returning a number value;

Inside the function, it is nothing unusual, we just create a variable called ‘volume’, and mutliple the parameters to find the volume.

Next, we just return the value of the volume, or alternatively we could just return the multiplication directly to save room.

Another example:

function GetScore(monster_type:int, score_multiplier:int, monster_dead:Boolean):int
{
	var score:int=0;
	if(monster_type==0)
		score= score_multiplier*10;
	else if(monster_type==1)
		score= score_multiplier*20;
	else if(monster_type==2)
		score= score_multiplier*30;
		
	if(monster_dead)
		score+=100;
	
	return score;
}

var total_score:int=0;

total_score = GetScore(0, 2, false); //so we're passing in 0 for the monster_type in the function, 2 as the score multiplier, and 'false' for the 'monster_dead' variable in the function.
trace("monster hit, new score = "+total_score);

total_score = GetScore(1, 5, false);
trace("monster hit, new score = "+total_score);

total_score = GetScore(2, 3, true);
trace("monster hit, new score = "+total_score);

//this will output
//monster hit, new score = 20
//monster hit, new score = 100
//monster hit, new score = 190

This is just another function setup to do something useful- in this case, finding out the score from a monster that was hit. You’re able to call complex functions with one line of code, which not only makes your code cleaner, it saves you a lot of time typing.

When to use functions?

At first you might have trouble deciding when to use functions, but basically it’s down to “when it makes sense”.
You don’t have to use them to have code working, but if there is some thing that you’ll need to do repeatedly, or if you want to sort your code out, and simply call a function to perform a complicated action, it would be a good place.

Basically, keep practicing – at first it might not be obvious, but as your code gets more complicated, you’ll quickly see where you can use a function to make a block of code re-usable.

Conclusion

In this section you learned the basics of functions, how to use them to save time and make your code more readable.

In the next section, we’ll finally start using classes, which is a core functionality of object oriented programming. When you use classes, you can create objects that have real world counterparts, and contain code to objects that need them.

Other Articles in this Series

2 thoughts on “Beginning Flash and ActionScript Game Programming Part 6: Basic Programming Concepts-Functions”

  1. Chris,

    I pasted in your VolumeOfBox example and I get “access of undefined property volume1” and “call to a possibly undefined method VolumeOfBox” at lines 51 and 52, any ideas?

Leave a Comment

Scroll to Top