Grid based games – Part 1: The basic grid

There are a lot of games based on different kinds of grids: Real Time Strategy (RTS) or round based Role Play Games (RPG) and Tower Defence (TD) games as well as Top-Down-Shooters and vertical scrolling Jump&Runs. One could use grids for tactical board games as well.
In the grid we are going to create, each tile consists of two parts, an Object() for the node and a MovieClip() for the graphic. The presented code is timeline and can thus be copied into the actions panel. This way it can be used for practicing purposes fast. For a game I would rather create and sort the code in classes.

Here is what we are going to create, a basic square grid with absolutely no interaction:

And here is the code, explanations will follow:

var nodeArray:Array = new Array();

var rows:int = 10;
var cols:int = 10;

var tileNumber = rows * cols;

var tileWidth:Number = 30;
var tileHeight:Number = 30;

var node:Object;

for ( var row = 0; row < rows; row++ )
{
	for ( var col = 0; col < cols; col++ )
	{
		node = new Object();
		node.v = col;
		node.u = row;
		nodeArray.push(node);
	}
}

var tile:MovieClip;

for ( var counter = 0; counter < tileNumber; counter++ )
{
	tile = new MovieClip();
	tile.x = nodeArray[counter].v * tileWidth + tileWidth;
	tile.y = nodeArray[counter].u * tileHeight + tileHeight;
	tile.graphics.beginFill(0x66ff66);
	tile.graphics.lineStyle(2,0x22ff22);
	tile.graphics.moveTo(-tileWidth*0.5, -tileHeight*0.5);
	tile.graphics.lineTo(tileWidth*0.5, -tileHeight*0.5);
	tile.graphics.lineTo(tileWidth*0.5, tileHeight*0.5);
	tile.graphics.lineTo(-tileWidth*0.5, tileHeight*0.5);
	tile.graphics.lineTo(-tileWidth*0.5, -tileHeight*0.5);
	tile.graphics.endFill();
	addChild(tile);
}

First a new Array for our nodes is created and the number of rows and columns is set. In the first loop all nodes are created and assigned their row and column number. This Object can hold a number of properties, those can also be received from a previously created map array but that will follow later. For now, in the second loop the MovieClip is created and on its graphics layer a rectangle is created.

Let's create some interaction and optimize some code in part 2.

This entry was posted in as3, flash, game development, grids, mochiads and tagged , , . Bookmark the permalink.

2 Responses to Grid based games – Part 1: The basic grid