Reputation: 1973
I'm generating hexagonal shape grid as explained in Amit Patel's website redblobgames.com
I have tested the grid and everything , including the coordinates is correct.
Now I'd like to store the grid data into an array. I partially figured it out, however the main problem is that some columns start at index 1 instead of 0.
So I'd like to find a way how to place the hexes in same order but make all starting from 0.
The index has to be calculated off the [q,r, -q-r] square positions, so that I can then access the array using the same technique.
this is how I'm now generating the grid and storing the data:
for (var q = -this.grid_r; q <= this.grid_r; q++) {
var r1 = Math.max(-this.grid_r, -q - this.grid_r);
var r2 = Math.min(this.grid_r, -q + this.grid_r);
for (var r = r1; r <= r2; r++) {
row = r + this.grid_r ;
col = (q+Math.floor(r/2)) + this.grid_r;
if( ! this.hexes[ row ] ){
this.hexes[ row ] = [];
}
n_hex = new Hex( q, r, this.layout );
this.hexes[ row ][ col ] = n_hex;
}
}
This is how the array look like from the data perspective.
0 1 2 3 4 5 6
0 0 0 0 0
1 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0
I just want to avoid using any conditions in draw or update methods to check whether the column is empty or not.
draw: function( ctx ){
for( var r = 0, r_l = this.hexes.length; r < r_l; r++ ){
for( var c = 0, c_l = this.hexes.length; c < c_l; c++ ){
if( typeof( this.hexes[r][c]) !== "undefined" ){
this.hexes[r][c].draw( ctx );
}
}
}
},
Upvotes: 1
Views: 191
Reputation: 1335
Your outer loop is q
and your inner loop is r
. Your array indices need to follow the same structure, with this.hexes[col][row]
instead of this.hexes[row][col]
:
for (var q = -this.grid_r; q <= this.grid_r; q++) {
var r1 = Math.max(-this.grid_r, -q - this.grid_r);
var r2 = Math.min(this.grid_r, -q + this.grid_r);
for (var r = r1; r <= r2; r++) {
col = q + this.grid_r;
row = r - r1;
if (!this.hexes[col]) { this.hexes[col] = []; }
this.hexes[col][row] = new Hex(q, r, this.layout);
}
}
The col
will be q
minus where the q
loop starts (-this.grid_r
). The row
will be r
minus where the r
loop starts (r1
).
Upvotes: 1