How to create an AS3 game grid

One of the things that you have to do a lot when developing grid based games in Actionscript 3 is obviously lay out the grid. This is confusing to a lot of people but in flash, it is really quite simple. I created a simple class just for this blog to demonstrate how this can be achieved.

Here is the Actionscript 3 class, and then an explanation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.frigidfish{
   
    import flash.display.Sprite;   
   
    public class Grid extends Sprite{
       
        public var rows:uint;
        public var cols:uint;
        public var cell:Array = new Array();
        public var plot:Array = new Array();
       
        public function Grid(displayObject:*,rows,cols, spacer){
           
            this.rows   = rows;
            this.cols   = cols;
           
            populateCells(displayObject,spacer);
            plotCells(cell);
           
        }
       
        private function populateCells(displayObject:*,spacer:int){
           
            var iterator:uint = 0;
            for(var c:uint = 0;c<cols;c++){
                for(var r:uint = 0;r<rows;r++){                                        
                    cell[iterator] = new displayObject;
                    cell[iterator].y = cell[iterator].height  * r + (spacer*r);
                    cell[iterator].x = cell[iterator].width * c + (spacer*c);
                    addChild(cell[iterator]);      
                    iterator++
                }
            }          
        }
       
        private function plotCells(cell:Array){        
           
            var iterator:uint = 0;
            for(var c:uint = 0;c<cols;c++){
                plot[c] = new Array;
                for(var r:uint = 0;r<rows;r++){                
                    plot[c][r] = cell[iterator];
                    iterator++                 
                }
            }          
        }
    }
}

Example usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import com.frigidfish.Grid;

var gameGrid:Grid = new Grid(Token,5,5,5);
addChild(gameGrid);


// There are 2 ways you can access the grid.
// by cell number (count 20 cells col by col):
gameGrid.cell[20].visible = false;

// or by plot info. if you count over 2 cols, and one
// row down, you'll see that this line makes the grid
// item invisible.
gameGrid.plot[2][1].visible = false;

Ok, so this is a very simple as3 class that can be built upon to do a lot of things. For example you could add a dynamic text field to your display object, and use the iterator in grid.as to add numbers to each cell.

You could use this as a starting point for a match type game or an array of other puzzle ideas. The point of this is just to help you understand how the grid is generated.

Let’s quickly go through the grid class:

The first thing we do is create 4 variables (lines 8-11).

rows and cols are passed to the constructor along with the class/display object that you want to instantiate and a spacer number. Note that in this class it is assumed that whatever you pass it as your display class must be displayable.

For this example, I just made a quick movieclip and called it Token, and selected ‘export for Actionscript’ in it’s properties.

Next is the constructor. As I said before, this requires 4 parameters:

your library item or class to display, rows (how many rows do you want) cols (how many columns do you want), space in pixels between display objects

the populateCells function does the meat of the work.

we create an iterator and start it at 0.
next we loop through each column.
for each column we add all of the rows:
1. create a new instance of the supplied display object and add it to the cell array
2. set the y position of the display object to it’s height x the number of the current row, + spacer
3. set the x position of the display object to it’s width x the number of the current column + spacer
4. Since this class extends Sprite, it is instantiated as a Sprite so we call just add the cell to it using the addChild() method
5. add 1 to the iterator and continue the loop.

notice that a key to making the spacer work properly is multiplying it by the row or the column. If you were to just ‘add’ spacer without multiplying by the row/col you would not achieve the desired result.

Next we execute the plotCells method. This creates an extra way to find the cell that you want. It sets up a 2 dimensional array and adds the cells to it so that you can access them by plotting coordinates.

first it creates an iterator and sets it to 0.
next we look through the length of the cols variable
now we create a new array and assign it to the plot array at the current column
for each number in cols, we iterate through all rows.
finally we assign each cell from our cell array to the proper plot coordinates.
add 1 to the iterator and process the next column.

So basically:
plot[0][0] = cell[0]
plot[0][1] = cell[1]
plot[0][1] = cell[2]


and so on. if you made a 5×5 grid, column 2, row 0 would be:
plot[2][0] = cell[10]

well, that’s it!
Hope you find this useful in your Flash Actionscript 3 projects.

Download this project as a working example here.

Share on FacebookShare on Google+Share on StumbleUponTweet about this on TwitterEmail this to someone

Facebook comments:

9 thoughts on “How to create an AS3 game grid”

  1. Hmm, I read the script. It’s clever.

    Maybe if you were to post an example, people would possibly follow the tutorial more often.

    I like the new CSS menu at the bottom right corner.
    Also, if you want, I can refer this website to some of my flash buddies ;D

  2. I agree that a good example is in order. I just wanted to get something out there so that people could get a general idea of how to lay out a basic grid.

    I’ve been really busy with a couple of huge deadlines but I will definitely be updating this with some better usage example soon. Feel free to invite your Flash buddies, that would be great!

  3. Awesome class, with your explaining it helped to remind me the process about grids. Good reference and clean source too. Maybe adding another array to each cell as a information holder. That way you could tell if it is a number of different things like moveable, destroyable, type of area, if a unit is in it etc.

  4. Wendinator: Thanks for your comment. I’m glad I could help! I agree that adding more data to each cell would be very useful. Maybe I’ll create a more advanced tutorial in here.. I just wanted to make sure that this particular post was as simple to understand as possible!

  5. it’s fine and it’s useful
    i like you aritcles very much,and i’d like to make friends with you.thks~
    my msn:[email protected]

  6. Thanks for this class! Am I the only person getting an “Incorrect number of arguments. Expected no more than 0.” error when trying to run the example? The class is being recognised correctly, but I’m not able to tell why it’s not recognising the arguments.

    1. Musicmaker1750 – I just checked the code to make sure it’s working and I couldn’t reproduce your bug so I went ahead and created a sample working project and attached it to the end of the post. (It’s the last sentence in the post with a link).

      Let me know if that doesn’t help you track down the error and I’ll see if I can help you out!

Leave a Reply