Placing DisplayObjects (eg. MovieClips and Sprites) in a grid can be cumbersome. You can keep a counter for the current column number and every time it reaches the maximum amount of columns reset it to zero and at the same time increase the row number. Then after a calculation you get the right coordinates.
By using the integer counter of the loop with the modulus and divider operands, you can make a much faster solution which, if you know what it does, is actually more maintainable and more legible than using two separate counters.
// this actionscript 3 code is tested in Flash IDE CS4
// but could be used in a separate class wrapped in a method.
var numColumns:int = 4; // number of columns
var numCells:int = 16; // number of cells in the grid
var margin:int = 16;
var cellSize:int = 64;
var cell:Sprite;
for(var i:int = 0; i < numCells; i++) {
cell = new Sprite();
// draw the rectangle for the cell
cell.graphics.beginFill(0xFF0000, 0.1);
cell.graphics.lineStyle(1, 0xFF00FF, 1);
cell.graphics.drawRect(0,0,cellSize, cellSize);
cell.graphics.endFill();
// column: gives a number from zero
// to numColumns minus one
var column:int = i % numColumns;
// column: returns the floored value
// of the iterator value divided by the numColumns;
var row:int = i / numColumns;
// place the cell on the grid with the given size
// and margins
cell.x = column * (cellSize + margin);
cell.y = row * (cellSize + margin);
// add the cell to the display list
addChild(cell);
}
+