Quick Tip: Multi-Dimensional Vectors
Have you ever thought of creating or using multi-dimensional Vector in ActionScript? Yes, it is possible and the definition syntax comes pretty logical to me now ;-).
var list:Vector.<Vector.<int>> = new Vector.<Vector.<int>>();
…or shorter declaration:
var list:Vector.<Vector.<int>> = new <Vector.<int>>[];
now your vectors have two dimensions, I mean:
list[0][0]
thx for that !
Just dunno if this can help someone…
I used this code to construct a map of the walls in a game :
I just fill it randomly for this comment, and limit the map at 5 rows and ten columns…
To get the map, I just import the class and call:
var map:WallMap = new WallMap();
Here’s the simplified class for the example if the value == 1, a block is present, no block if the value is equal to zero :
in classes.WallMap.as :
package classes {
public class WallMap{
public var rows:int = 5;
public var cols:int = 10;
public var _map:Vector.<Vector.>;
public function WallMap() {
// create the bidimentional Vector object :
_map = createVector2D();
// fill the Vector2D randomly :
fillMap();
// list the Vector2D values :
trace(getMapToString())
}
/**
* Create the bidimentional Vector object
* @return Vector.<Vector.>
*/
public function createVector2D():Vector.<Vector.>{
var i:int;
var j:uint;
var vector2D:Vector.<Vector.> = new Vector.<Vector.>(rows,true);
for(i = 0; i < rows ; i++){
vector2D[i] = new Vector.(cols,true);
}
return vector2D;
}
/**
* Fill the Vector Vector.<Vector.> randomly
*/
public function fillMap(){
var i:uint;
var j:uint;
for(i = 0; i<rows ; i++){
for(j = 0; j<cols ; j++){
_map[i][j] = Math.floor(Math.random()*2)
}
}
}
/**
* List the Vector2D values.
* @return String
*/
public function getMapToString():String{
// Initialize the String as ""[Object Vector2D] = {"
var output:String = "[Object Vector2D] = {\n";
// Initialize i and j as uint variables
var i:uint;
var j:uint;
// Initialize tab as a single tabulation String
var tab:String = " ";
// Loop in the Vector and construct the String representation
for(i = 0; i<rows ; i++){
for(j = 0; j<cols ; j++){
if(j == 0){
output += tab;
}
output += ("[" + i + "][" + j + "]=" + _map[i][j]);
if(j < cols-1){
// add a comma if line is not ended
output += ", "
}
}
// add a line separator because line is finished.
output += "\n";
}
// Close the String for [Object Vector2D] as "}"
output += "}";
return output;
}
}
}