Question

I'm still learning to code in AS3, which seems pretty straight forward and similar to Java so I apologize if I have made a silly mistake somewhere.

As per the question Title, I am trying to create a 2D (nested) array of a MovieClip that I have already created so that they can be printed out on a grid as follows.

var NumCols:Number = 8;
var NumRows:Number = 8;
var ColWidth:Number =  (stage.stageWidth-8)/NumCols;
var ColHeight:Number = (stage.stageWidth-8)/NumRows;
var GemMatrix:Array = new Array( 8, 8 );
var n = 1;
var SW:Number = stage.stageWidth;
var SH:Number = stage.stageHeight;

private function GJ_GenerateBoard(event:MouseEvent):void {
// Initialization...
for (var j = 0; j < NumRows; ++j)
{
    GemMatrix[y] = [];
    for (var i = 0; i < NumCols; ++i)
    {
        trace(i,j);
        GemMatrix[i][j] = new Gem() as MovieClip;
        this.addChild(GemMatrix[i][j]);
        GemMatrix[i][j].x = i*ColWidth+ColWidth/2;
        GemMatrix[i][j].y = j*ColHeight+ColHeight/2;
    }
}

The error I am receiving is:

ReferenceError: Error #1056: Cannot create property 0 on Number.

This occurs on the line when I am trying to create a new Gem() instance.

Any help is greatly appreciated. Thanks!

Was it helpful?

Solution

var GemMatrix:Array = new Array( 8, 8 );

This is what's got you. This actually creates a 1D array that is [Number(8), Number(8)]. You don't need to define the length of an array in AS3, here's how I would set it up:

var GemMatrix:Array = [];

for (var i:int = 0; i < NumCols; i++){
    var $a:Array = [];
    for (var m:int = 0; m < NumRows; m++){
        var $gem:MovieClip = new Gem();
        $gem.x = i*ColWidth+ColWidth/2;
        $gem.y = j*ColHeight+ColHeight/2;
        addChild($gem);

        $a.push($gem);
    }
    GemMatrix.push($a);
}

Also, this line is strange: GemMatrix[y] = []; The only reason this isn't throwing an error is because y is a dynamic property from the class you're currently extending from that indicates its y position (most likely this.y = 0).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top