Monday, December 3, 2012

Drawing a Chessboard:Associative Arrays



The use of associative arrays in JavaScript allows to add some object-oriented capabilities in a classical procedural programming. Here is a small explanation through our classical Drawing a Chessboard example.


In this implementation, we plan to pre-calculate all the 64 cells of the chessboard. Thus, it will be defined by four attributes (or properties): its X- and Y-coordinates, its size, and its color (black or white).

1- What is an associative array?

To define each cell, we can use a specific type of array: The Associative Array which contains pairs of (key, value). For example, the cell (0,1) is defined as:

  var cell = {"x": 0, "y": 1, "size": 256 / 8, "color":0}  ;

Note: Curved brackets { and } are used to define this type of array.

To access the various elements of this list, use square brackets like a usual array as follows...

  IJ.log(cell["x"]); // → 0

or use a more object-oriented (and equivalent) way like ...

IJ.log(cell.x); // → 0

The cell can be defined as an empty array and then filled with new pairs (key,value)...

var cell = {}; // Initialize

cell["x"] = 0;
cell["y"] = 1;
cell["color"] = 0;

2- Drawing a chessboard

The array of 64 ( = 8 x 8 ) cells can be initialized as an array of associative arrays like...

var cells = [
{'x': 0, 'y': 0, 'color':255},
{'x': 1, 'y': 0, 'color':0},
....
{'x': 7, 'y': 7, 'color':0},
];

However, it is better to create the array in a loop as follows

var cells = []; // an array of cells
var count = 0;
for (var y=0; y<8; y++) {
  for (var x=0; x<8; x++) {
    var cell={}; // new associative array: one cell
    cell.x=x;
    cell.y=y;
    cell.color = ( (x+y)%2==0 ) ? 255 : 0;
    cells[count++]=cell;
  }
}
Note: The line 'cell.x = x;' is equivalent to 'cell["x"]=x;'.

The main loop  becomes ...

for (var i in cells) {
  ip.fill(cells[i].x*csize, cells[i].y*csize, csize, csize);
}



Further Reading

Drawing a Chessboard Series [TOC]
Programming in ImageJ [Link]

No comments:

Post a Comment