This tutorial will teach what nested arrays are and how to use them. You should know what Arrays are before reading this.
What ARE nested arrays?
Nested arrays are an array contained by an array. Now you're probably wondering what the hell that means so i'll show it visually
normal array (_root.myarray (3))
0,0,0
nested array(_root.myarray (3)(3))
0,0,0
0,0,0
0,0,0
As you can see a nested array is simply an array repeated times the amount contained in the second (or third, or fourth....) length indication
Whats so great about that?
Well, as you can see above the nested array creates a grid. This can be very useful in tile-based games such as battleship or even chess because you you can access any point on the grid by using _root.myarray[i][j].
For example, saying:
trace(_root.myarray[0][2])
would trace this point
0,0,0
0,0,0
0,0,0
(remember: 0=1, 1=2, 2=3...... because 0 comes first in the sequence and not 1)
So how the HELL do i make a nested array?
here is the basic script to make a nested array (this was the only way i could find that worked. if theres a better way then post it.)
_root.meow= new Array(6);
_root.lol= new Array(6);
for(i=0; i<6; i++){
_root.lol[i] = i
}
for(i=0; i<6; i++){
_root.meow[i]= _root.lol
}
trace(_root.meow[0]);
trace(_root.meow[4][5]);
it would output
0,1,2,3,4,5
5
i'll explain each section.
_root.meow= new Array(6);
_root.lol= new Array(6);
You create 2 new arrays with a lenth of 6 each.
for(i=0; i<6; i++){
_root.lol[i] = i
}
Here you fill one array with 0,1,2,3,4,5
for(i=0; i<6; i++){
_root.meow[i]= _root.lol
}
here you fill each slot in your 2nd array with your first array your array now looks like....
0,1,2,3,4,5
0,1,2,3,4,5
0,1,2,3,4,5
0,1,2,3,4,5
0,1,2,3,4,5
0,1,2,3,4,5
trace(_root.meow[0]);
this traces the whole first line
trace(_root.meow[4][5]);
This finds and traces the 6th number on the 5th line (remember the evil 0=1 stuff or you shall fail ..... horribly)
Alright, now how do i use this in a practical way?
Lets take a look at battleship as an example. After you have nested your arrays you can set certain squares as squares that currently have a ship. For example
for(i=2; i<5; i++){
_root.TheArray[i][2] = ship1;
}
This would make [2][2], [3][2], [4][2], and [5][2] have ship1
Then you could have something like
if(hit){
if(WhatsHit == ship1){
trace("You hit ship1! It is sinking!");
}
}
You could also use it as a backround creater. you could assign values to differnt backround pictures. Like...
If(_root.myarray == 1){
//put the proper backround in the proper spot
elseif((_root.myarray == 2){
//put a differnt backround in that spot
}
or something like that.
Feel free to add to this if you have something to add. Comments appreciated.