Tutorial: Create a Tower Defense Game in AS3


Written By MrSun at 8:01 am - Saturday, February 28th, 2009
Categories: Flash

Step 1: Setting Up a Level

The tower defense genre is one that has become extremely popular over the years. Although they can become quite complicated to develop, they are almost always very fun to play. I am here to walk you through the creation of one of these games. Let us begin, shall we?

In this section of the tutorial, we’re going to set up the roads and stuff onto the stage. However, the first thing we need to do is create a blank flash document with a black background with the frames per second set at 24.

Now, we have to create two classes. In order to do this, simply create two external ActionScript files by selecting File -> New -> ActionScript File, twice. The first class we’ll create is one for an empty block that towers can be placed in. Add the following code to it:

package{
	//importing required classes for this to work
	import flash.display.MovieClip;
	import flash.events.*;
	public class EmptyBlock extends MovieClip{//defining the class as EmptyBlock
		private var _root:MovieClip;//creating a _root variable to access root easily
		
		public function EmptyBlock(){//this function will always run once EmptyBlock is called
			this.addEventListener(Event.ADDED, beginClass);//create a function that will run once
			this.addEventListener(Event.ENTER_FRAME, eFrameEvents);//create a enterFrame function
		}
		private function beginClass(e:Event):void{
			_root = MovieClip(root);//setting the _root as the root level
			
			this.buttonMode = true;//make this act like a button
			this.addEventListener(MouseEvent.MOUSE_OVER, thisMouseOver);//adding function for mouseOver
			this.addEventListener(MouseEvent.MOUSE_OUT, thisMouseOut);//adding function for mouseOut
			this.addEventListener(MouseEvent.CLICK, thisClick);//adding function for clicking
		}
		private function eFrameEvents(e:Event):void{
			if(_root.gameOver){//remove this and listeners if game is over
				this.removeEventListener(Event.ENTER_FRAME, eFrameEvents);
				this.removeEventListener(MouseEvent.MOUSE_OVER, thisMouseOver);
				this.removeEventListener(MouseEvent.MOUSE_OUT, thisMouseOut);
				this.removeEventListener(MouseEvent.CLICK, thisClick);
				MovieClip(this.parent).removeChild(this);
			}
		}
		private function thisMouseOver(e:MouseEvent):void{
			//changing the background so the user know's it's clickable
			this.graphics.drawRect(0,0,25,25);
			this.graphics.endFill();
		}
		private function thisMouseOut(e:MouseEvent):void{
			//changing the background back
			this.graphics.beginFill(0x333333);
			this.graphics.drawRect(0,0,25,25);
			this.graphics.endFill();
		}
		private function thisClick(e:MouseEvent):void{
			//we'll add code that'll make a turret be made later
		}
	}
}

I’ve commented the code extensively if you need any explanation. Now, save this file as “EmptyBlock.as” in the same folder as your source .fla file. Now, take the second external ActionScript file. We will turn this into a special block which will act as a marker for the road. There are going to be 6 types of this special block, the four different directional notifiers, and the start and finish block. They won’t look any different than any other block, but they will be very important later. Add this code to that second class:

package{
	//imports
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	public class DirectBlock extends MovieClip{//we'll call it a DirectBlock
		private var _root:MovieClip;//again, defining a _root
		private var directType:String;//what kind of special block is this
		
		//this time, we have to accept some values to make it easier to place, like the type and coordinates
		public function DirectBlock(type:String,xVal:int,yVal:int){
			directType = type;//set the directType so that all other functions can use it
			//add the required event listeners
			this.addEventListener(Event.ADDED, beginClass);
			this.addEventListener(Event.ENTER_FRAME, eFrame);
			
			//setting the coordinates
			this.x = xVal;
			this.y = yVal;
		}
		private function beginClass(e:Event):void{
			_root = MovieClip(root);//setting the _root again
			
			//making this into a 25x25 square
			this.graphics.beginFill(0x111111);
			this.graphics.drawRect(0,0,25,25);
			this.graphics.endFill();
		}
		private function eFrame(e:Event):void{
			if(_root.gameOver == true){//destroy this if the game's over
				this.removeEventListener(Event.ENTER_FRAME, eFrame);
				MovieClip(this.parent).removeChild(this);
			}
			//we'll add more code to this later
		}
	}
}

This will just set up the blocks. Now, we must return back to the main .fla file. Create a new layer to place actions in, and add the following code:

stop();

//setting vars to step in for turns and special blocks
var S:String = 'START';
var F:String = 'FINISH';
var U:String = 'UP';
var R:String = 'RIGHT';
var D:String = 'DOWN';
var L:String = 'LEFT';

var startDir:String;//the direction the enemies go when they enter
var finDir:String;//the direction the enemies go when they exit
var startCoord:int;//the coordinates of the beginning of the road
var lvlArray:Array = new Array();//this array will hold the formatting of the roads

lvlArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,R,1,1,D,0,0,R,1,1,D,0,0,R,1,1,D,0,0,
			0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
			0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
			S,D,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,R,1,F,
			0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
			0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
			0,R,1,1,U,0,0,R,1,1,U,0,0,R,1,1,U,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			];

//the names of these variables explain what they do
var currentLvl:int = 1;
var gameOver:Boolean = false;

function startGame():void{//we'll run this function every time a new level begins
	//right now we don't have any code
}

var roadHolder:Sprite = new Sprite();//create an object that will hold all parts of the road
addChild(roadHolder);//add it to the stage
function makeRoad():void{
	var row:int = 0;//the current row we're working on
	var block;//this will act as the block that we're placing down
	for(var i:int=0;i

Now, if you test out your game, you'll see nice little road set up for you. However, we need to keep that empty space in the bottom so we can add stats and other cool stuff.

Well, that concludes this first part of the tutorial. Next time we'll make it so you can add turrets!

Final Product

Source Files (Zipped)

37 Comments

Canakar:

you explained on what to do but NOT HOW this is a good yet bad tutorial


Mr Sun:

Explain to me what you mean when you say “how”. You can’t teach a person “how” to code, you can only teach them what to do and hope that they can learn.


hiren:

yes,that’s true that you can not teach person “how to code”,but you can explain code in more detail….
I’m not comparing you with anybody but if you will see the tutorial at asgamer.com ,it’s really cool, students like me can easily understand that….
Btw your work is wonderful and i appreciate it…………
thanks for your tutorial and keep it up……


hiren:

For example in this tutorial lvlArray and its use in code is difficult to understand ,it would be great if u can explain them or u can give link for explanation of that stuff

thank you


Ollie:

Yeah, hiren is right, if I hadn’t read other tutorials including arrays I would be confused as hell!

Anyway, except that there could be *slightly* more explanation, it is an amazing tutorial.

Keep up the good work 😀


Andrew:

So I created the main flash file, and the 2 AS files Empty/DirectBlock.as files, when I go to test them, I get an error
1013: The private attribute may be used only on class property definitions. It is referencing the code of –private function eFrame(e:Event):void{–
Any ideas as to why this is happening?


Jim:

(line 31, DirectBlock.as) 1013: The private attribute may be used only on class property definitions.


Jim:

Andrew, I can see you are having the same problem,unfortunately this problem extends beyond what I understand. Have you found the problem?


skylerfd:

Can you make a tower defense tutorial for AS2? I have flash 8, but I really want to make a TD game. Email me if you decide to do so.


Ty:

To Jim and Andrew, if you copied the code exactly, on line 29 of your DirectBlock.as there will be a } that shouldn’t be there. Deleting it will solve your problem.


anonymous:

hey mrsun. thanks for all your help. as an experienced programmer, i find your tutorials a good starting step in learning flash actionscripts. and i like how you seperated as3 and as2. keep up the good work and produce more tutorials please.


Gavyn:

private function beginClass(e:Event):void{
_root = MovieClip(root);//setting the _root again

//making this into a 25×25 square
this.graphics.beginFill(0x111111);
this.graphics.drawRect(0,0,25,25);
this.graphics.endFill();

} <—**** ERROR REMOVE THIS TO MAKE WORK ****
}

I don’t care much for these other QQ’rs how want you to teach them what an array is. TD games are not for beginner coders and even this one allow isn’t a very complex TD. On that not I like the tutorial so far… being I am at the end of the first page, but I did have to debug the code also. Your source files are correct, but your examples posted here are bugged.

Nice Start, lets see what we can make of this.


Name:

Make a video tutorial with audio, good tutorial but i dont have eyes cant read it.


Anonymous:

If you don’t have eyes then what the hell are you doing making visual programs?


BackroomWebDesign:

2 classes, DirectBlock and EmptyBlock, are defined.

In the main timeline (the .fla file), an array is defined containing level information.

Then a loop is entered, which generates blocks (either a DirectBlock or a EmptyBlock) based on the value at each position in the array. The loop also generates coordinates.

QUIZ :

1) Where is the code that causes the color of a non-path block to change?

2) Modify the level so that the path is a straight line.

3) What type of object is roadHolder?

//should help the new ppl at this
///This is an outstanding set of tutorials mr sun


Rick:

I found this tutorial incredibly useful for my project. I’m not sure what the others are talking about with needing more information. I’ve successfully used this tutorial to help me finish one of my projects which is developed in C++… it’s nice, generic enough to transcend other languages, and nicely structured.

Keep up the awesome work 🙂


Redfin:

Fantastic tutorials! Keep up the great work!


Ramon Fritsch:

Oh man, that’s great! thank you!


blobo:

mine says there is “a call to an undifined emptyblock” and “a call to an undifined directblock” how do you fix that?


Allaw:

Look like a mix of as2 and as3 maybe you should consider using MovieClip(parent) more than _root? and still other few buildup functions with as2


paddy:

Hi, great stuff. I have used the source and reconstructed a version using entirely .as files because I have just started using FlashDevelop and I can’t figure out how to use .fla files.

look here http://www.eldwick.org.uk/?q=node/62


Anonymous:

the code doesent work


Zach:

Hey is their any way I can make the path so that it directs the enemies Up and down? Like the first goes up the second goes down. Etc.? If anyone could help with this thanks.


All Tutorials » 5 flash game tutorial:

[…] Create a Tower Defense Game in AS3 :: Read more […]


Bob:

I go to test the game.. and in the code on the main screen, i get an error saying this is wrong:

block = new DirectBlock(lvlArray[i],(i-row*22)*25,row*25);


Andre:

how do you change the background to a graphic so that the gray background can be a picture


Anthony:

So i am currently trying to rework the tower defense tutorial setup here so i can learn the code and whatnot, but i cant get my little guys to turn left, guess they just arnt ambi-turners, but is there any reason why this is happening in the code, if you could email some help it be much appreciated


NicktheMan:

so iam trying to learn how to make flash games and i know nothing about it! q1 In order to make a new”layer to put actions in” do i click insert layer then right click the first frame and go to actions? q2 i keep getting a compiler error”1180 call to a possibilty undefined method DirectBlock” i think i missed a block or something.

please can u help?


Jacob:

To blobo: make sure that your .fla file and both .as files are saved in the same place.

Also, in the thisMouseOver function in the EmptyBlock code above, “this.graphics.beginFill(0x006600);” is left out. It’s in the source code, though.


sean:

i get the errors
1180: Call to a possibly undefined method DirectBlock.
and
1180: Call to a possibly undefined method EmptyBlock.
help?


Flash Game Development Tutorials & FLA Files:

[…] How to Create a Tower Defense Game in AS3 […]


Skezh:

To match your demonstration, I had to add a line to your code in EmptyBlock.as, at line 31 (if copypasting the script), in thisMouseOver funnction:
this.graphics.beginFill(0x006633);
Without it, the empty blocks with mouse over them won`t be highlighted.

Thanks for a great tutorial.


Sebasss:

People stop complaning about the guy not telling you how to do it. This is not for beginners. This is just to understand how to make a TD game and how it works. If you dont understand a line, google it. Damn.

I am trying to make a Java game based on this and this will help me understand the mechanics of a TD game. Thank you.


Anonymous:

I get the error:

1084: Syntax error: expecting rightbrace before end of program.


Tanner:

i don’t understand….
you add 2 action script files but you have 3 things of code…..
please explain….


colePark:

Amazing tutorial, this code is hard to wrap your brain around, using the block loop as a system for pathing, but not for tower placement, Thank you for this awesome tut, it’s inspired me to try hard 😀


«
»