This is an implementation and demonstration of a toroidal array class. The array nodes are each linked to 4 other nodes, allowing traversal of the cursor from one “edge” of the array to the other. Use the arrow buttons or click within the grid to move the cursor.
var toroidal_grid = null;
jQuery(document).ready(function() {
toroidal_grid = new Grid(5, 5, "grid");
});
function Grid(width, height, element_id) {
this.width = width;
this.height = height;
//default position is the center of the grid
//(or close to it if the grid dimensions are even numbers)
this.position = parseInt((width * height) / 2);
this.goToNode = function(node) {
//get the node's position from the end of its ID string
this.updateGrid((node.id).split("-").pop());
};
//helper functions for setting up node links
this.findWestBoundary = function(i) {
if ((i % this.width) == 0) {
return i + this.width - 1;
} else {
return i - 1;
}
};
this.findSouthBoundary = function(i) {
if (i >= ((this.width * this.height) - this.width)) {
return i % this.width;
} else {
return i + this.width;
}
};
this.findNorthBoundary = function(i) {
if (i < this.width) {
return (this.width * this.height - (this.width - i));
} else {
return i - this.width;
}
};
this.findEastBoundary = function(i) {
if ((i % this.width) == (this.width - 1)) {
return i - this.width + 1;
} else {
return i + 1;
}
};
this.nodes = [];
var west, south, north, east;
for (var i=0; i<width*height; i++) {
//populate the node array
this.nodes.push(
new GridNode(
this.findWestBoundary(i),
this.findSouthBoundary(i),
this.findNorthBoundary(i),
this.findEastBoundary(i)
)
);
//create the grid elements
var node = document.createElement("div");
if (i == this.position) {
node.className = "grid-node grid-node-active";
} else {
node.className = "grid-node grid-node-inactive";
}
node.id = "grid-node-" + i;
node.onclick = function() {toroidal_grid.goToNode(this);};
jQuery("#" + element_id).append(node);
}
this.updateGrid = function(newPos) {
//remove the active class from the previous node and make it inactive
var node = jQuery("#grid-node-" + this.position);
node.addClass("grid-node-inactive").removeClass("grid-node-active");
//store the new position
this.position = newPos;
//remove the inactive class from the new node and make it active
node = jQuery("#grid-node-" + this.position);
node.addClass("grid-node-active").removeClass("grid-node-inactive");
};
//handlers for arrow buttons
this.moveWest = function() {
this.updateGrid(this.nodes[this.position].west);
};
this.moveSouth = function() {
this.updateGrid(this.nodes[this.position].south);
};
this.moveNorth = function() {
this.updateGrid(this.nodes[this.position].north);
};
this.moveEast = function() {
this.updateGrid(this.nodes[this.position].east);
};
}
function GridNode(west, south, north, east) {
this.west = west;
this.south = south;
this.north = north;
this.east = east;
}