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:

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:

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.

flash and php – Send/Receive Variables from Actionscript 3 & PHP

Below is a class that I made that can be used to send a group of variables to a php script on a server and receive the results. I use this all the time when working between flash and php in my projects!

// FlashPHP Class by Rick Nuthman
// 8.28.09
// Constructor receives 2 arguments:
// url:String - The url to the PHP file
// flashVars:Object - An object that contains variables to be sent to the url
//
// The class dispatches 1 event called "ready" once the php transaction is complete.
// listen for this event. Once it's received you can access returned variabled from receievedVars.

package com.frigidfish{

    import flash.net.URLVariables;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequestMethod;
    import flash.events.EventDispatcher;
    import flash.events.Event;

    public class FlashPHP extends EventDispatcher {
       
        // Public Properties
        public var receivedVars:URLVariables;      
       
        // Private Properties
        private var url:String;    
        private var flashVars:Object;
        private var request:URLRequest;
       
        private var completeEvent:Event              = new Event("ready");
        private var variables:URLVariables           = new URLVariables();
        private var loader:URLLoader                 = new URLLoader();

        public function FlashPHP(url:String, flashVars:Object) {
           
            this.flashVars                      = flashVars;
            this.url                            = url+"?r="+ new Date().getTime();
           
            parseVariables();
        }

        // Private Methods
        private function parseVariables() {
           
            for (var item in flashVars) {
               
                variables[item] = flashVars[item];             
            }
           
            sendVariables();
        }

        private function sendVariables() {
           
            request                                 = new URLRequest(url);
            request.method                          = URLRequestMethod.POST;
            request.data                            = variables;
           
            loader.dataFormat                       = URLLoaderDataFormat.VARIABLES;           
            loader.addEventListener(Event.COMPLETE, variablesAreLoaded);
            loader.load(request);
        }

        function variablesAreLoaded(event:Event) {
           
            receivedVars                            = new URLVariables(loader.data);
            dispatchEvent(completeEvent);          
        }
    }
}

Here is an example of how to implement it:

import com.frigidfish.FlashPHP;
var score:String = "100";
var playerName:String = "Bobby";
var phpData:*;

var playerObject:Object = new Object();
playerObject.score = score;
playerObject.playerName = playerName;

var flashPHP:FlashPHP = new FlashPHP("http://www.yoursite.com/yourphp.php", playerObject);
flashPHP.addEventListener("ready", processPHPVars);

function processPHPVars(event:Event){
// put the object that php sends back into a var (in this case phpData)

phpData = event.target.receivedVars;
trace(phpData.success);
}

Of course it will be necessary to know what to do with the data on the PHP side… here is a simple script that receives that variables and sends back a simple response var called ‘success’:

<?php
$teamName = $_POST['playerName'];
$score = $_POST['score'];
// Here you would put any processing functions...
//...

$success = "1";
//...
$returnVars = array();
$returnVars['success'] = $success;
$returnString = http_build_query($returnVars);
echo $returnString;
?>

Basically, this script does nothing with the variables that are collected, but as you can see, it just takes what is posted from flash and assigns it to php variables. Lastly, we create a new array to contain any vars that will be sent back to flash. This array is converted into a query string which is translated by FlashPHP into an object containing the variables by key names created in PHP.

I hope this makes sense, it’s actually quite easy to use! Don’t forget to wait for the FlashPHP “ready” event to trigger before attempting to access its receivedvars property. Feel free to ask any questions if anything doesn’t make sense 🙂

Download Example