Beginning Flash and ActionScript Game Programming Part 7: Basic Programming Concepts-Classes and Objects

In the previous section, we learned about functions, which allows us to create blocks of re-usable code that creates cleaner code, as well as saves time typing.

In this section, we’ll get into the ‘meat and potatoes’ of programming- creating classes and objects.

Setting Up FlashDevelop

Open FlashDevelop, Click Project->New Project, select “AS3 Project”, name it “part7″(or whatever you want, really), select a location to create the project, and click ‘OK’.

On the right side, in the window ‘Project’, double click on the ‘src’ folder, and double click on the file ‘Main.as’ below it. Now you have a base Actionscript 3.0 progam setup in FlashDevelop.

Creating a Class

Creating a class is simmilar to creating a function in structure, but each class is required to be in its own individual file.

To do this in FlashDevelop, on the right hand side of the screen, right click on the folder “src”, select “Add” then “New Class”.

All you need to do here right now is name your new class, so beside ‘Name’ change it to “Enemy” and click ‘OK’.

You should now have a file that looks like this:

Enemy.as

package  
{
	/**
	 * ...
	 * @author Chris Moeller
	 */
	public class Enemy 
	{
		
		public function Enemy() 
		{
			
		}
		
	}

}

What is nice here is that FlashDevelop sets up the “skeleton” of the file for you.

Line 1: This is the ‘package name’, which you can also think of as the folder name. Here, this file is just in the main ‘src’ file so it has no package name, but if you had created it in a folder called ‘BadGuys’, the this line would look like: ‘package BadGuys’.

Line 3-6: This is an automatically generated comment, which you can erase if you want to, or provide information about what this class will do.

Line 7: This is where you define the name of your class. This needs to to be the same name as the file.

Line 10: This is your class’s ‘Constructor’ function. A constructor is named the same as your class, and is called automatically whenever a new object of this class type is created.

Now that we have made our first class, lets make it do something!

Enemy.as

package  
{
	/**
	 * ...
	 * @author Chris Moeller
	 */
	public class Enemy 
	{
		public var name:String;		
		public var type:String;
		
		private var total_health:int;
		
		public static var total_enemies:int;
		
		public function Enemy(name:String, total_health:int, type:String) 
		{
			this.name = name;
			this.total_health = total_health;
			this.type = type;
			total_enemies++;
			
			trace("New enemy created, total is now: " + total_enemies +
			", name = "+name+", total_health = "+total_health+", of type = "+type);
		}
		
		public function TakeDamage(amount:int):void
		{
			if(total_health<=0)
			{
				trace(name+": Stop beating my corpse!");
				return;
			}
		
			total_health-=amount;
			if(total_health>0)
				trace(name+": ouch, you damaged me!(health:"+total_health+")");
			else
				trace(name+": Eck, you killed me!");
		}
		
	}

}

Line 9-14: We create a few variables that we want for each of our “Enemy” objects.
We’ll create a ‘name’ and a ‘type’ public variables (variables that can be seen outside of this class), a private ‘health’ variable, that can only be seen from inside this class, and a static variable, which is a variable that is stored for the entire class, instead of for each object created.

Line 16: Our constructor, which is automatically called when we create an object of this type. Here, all 3 variables are required to be passed in when creatng an object of this type- it must be given a ‘name’, an amount for ‘total_health’, and a ‘type’.

Line 18-20: These 3 lines are used to assign the passed in variables to our class’s variables. We use the keyword ‘this’ to refer to ‘this’ class’s variables. Since the variables being passed in have the same name as the ones for our class, we must use the keyword ‘this’ to refer to the variables for our class vs. the passed in ones.

Line 21: Just to show how a static variable works, everytime any object of this class type is created, we’ll add one to the count of total objects of this type. Remember, this is a variable that is assigned to the class itself, not each object that we will create with this class type.

Line 22: We’ll just trace out the total number of enemies when each object is created.

Line 27: This function we will call for each enemy whenever we want to damage them, for instance if the player hit them. We will pass in the amount of damage, and have the function decide how to handle it.

Line 29: We’ll first check if the total_health is less than or equal to zero, have the enemy tell them it’s aleady dead, and exit out of the function (using return; -which means we’re returning nothing, which causes us just to exit the function at that point instead of completing it like normal) instead of continuing with the function.

Line 35: Here the total health of the enemy will be taken away by the amount of damage being done.

Line 36-39: We’ll check if the health (after the damage has been done), is greater than zero (not dead), and print out the relative message.

Now you have created a class – but what does it do? Nothing yet! We need to create an object of this type of class to be able to do anything with it.

Objects

You have already created some objects, which are the basic variable types. When you use “var score:int=100” – you are creating an object with the type of ‘int’, and the value of “100”. You can create objects in the same way from any class you create.

In your “Main.as”, we will modify it to create a couple of objects of the ‘Enemy’ type, and do stuff to them.

Main.as

package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * ...
	 * @author Chris Moeller
	 */
	public class Main extends Sprite 
	{
	
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			//here you create 3 objects, of type enemy, and passing values into the constructor of the class file (your "Enemy" function in your enemy class file
			var enemy1:Enemy = new Enemy("The Evil Clown", 500, "Child Enemy");
			var enemy2:Enemy = new Enemy("A Graduate Student", 20, "Undergraduate Enemy");
			var enemy3:Enemy = new Enemy("A peanut", 2, "Kevin's Archnemesis");
			
			//here, we'll call the function "TakeDamage" from the class file 'Enemy' for each of the objects we created above
			enemy1.TakeDamage(15);
			enemy2.TakeDamage(15);
			enemy3.TakeDamage(15);
			
			
			//and just for fun, we'll damage our enemies a little more
			enemy1.TakeDamage(5);
			enemy2.TakeDamage(5);
			enemy3.TakeDamage(5);
			
			trace("The total number of enemies is " + Enemy.total_enemies);			
			
			//this will output in the Ouput window:
			//New enemy created, total is now: 1, name = The Evil Clown, total_health = 500, of type = Child Enemy
			//New enemy created, total is now: 2, name = A Graduate Student, total_health = 20, of type = Undergraduate Enemy
			//New enemy created, total is now: 3, name = A peanut, total_health = 2, of type = Kevin's Archnemesis
			//The Evil Clown: ouch, you damaged me!(health:485)
			//A Graduate Student: ouch, you damaged me!(health:5)
			//A peanut: Eck, you killed me!
			//The Evil Clown: ouch, you damaged me!(health:480)
			//A Graduate Student: Eck, you killed me!
			//A peanut: Stop beating my corpse!
			//The total number of enemies is 3
		}
		
	}
	
}

So looking at our Main.as, we now can see that it is just another specialized class, derived from the Sprite class.

Line 13: We now see that this is our constructor for the main class, called whenever the program starts automatically, which then calls the function ‘init’, when it is actually added to the stage/visible.

Line 24-26: Here, we create 3 different objects, enemy1, enemy2, enemy3, and pass in a name, the total health, and what type of enemy it is, into the constuctor.
So as you can see, they are 3 different objects, but all with the same class type of ‘Enemy’ – 3 different enemies with some stuff in common.

Line 28-34: Now we call each objects “TakeDamage” function, which will take away the amount of damage from the total health by the amount we pass in(15, then 5 in this case).

Line 36: This is just to show how to access a static class variable. You just refer to the class type “dot” the static variable name. Each object can have acess to it, but changing it will change it for all objects of that class type.

As you can see from the output, the static ‘total’ variable is increasing with each object created of the same type.

When we damage each enemy, they each respond differently, which depended on how much damage they are taking, and how much health they were created with.

Conclusion

In this section you learned the basics of making your own classes, and creating objects from a class.

In the next section, we’ll learn about more object oriented concepts that will help you – inheritance and polymorphism (which includes bragging rights to your friends 😉 )

Other Articles in this Series

Bookmark the permalink.

One Comment

  1. You are just amazing… and you collection of tutorial is wow.. i am proud and happy to start my gaming development journey with your tutorial. Thanks a lot to put some great effort.

Leave a Reply

Your email address will not be published. Required fields are marked *