A DOM-Based Snakes Game, Part II: Loading the Game's Board | WebReference

A DOM-Based Snakes Game, Part II: Loading the Game's Board


A DOM-Based Snakes Game, Part II (3)

Loading the Game's Board

Now that the DOM is ready, we need to assign the right images to the right nodes. We first define the row loading function:

function loadRow(rowNum, gif) {
  for(var i = 0; i 

Notice how easy it is to assign an image file name to a DOM's node. You just use an HTML attribute of the relevant tag (IMG's SRC for example) as a property of the node (always in lower case):

divNode.childNodes[domIndex(i, rowNum)].src = gif;

Notice the domIndex() function above. It converts a 2-D position (row and column) to an index into a 1-D array of divNode's childNodes. Here is the function:

function domIndex(x, y) {
  return (y * maxColumnCount + x);
}

The loadColumn() function is very similar to the loadRow() function:

function loadColumn(colNum, gif) {
  for(var i = 0; i 

We build the rectangular board area by calling the loadRow() method, once per row:

function loadBoardCore() {
  for(var i = 0; i 

Finally, we build the game's DOM similarly to how we did it for the sliding puzzle. The board consists of maxRowCount of rows. We append a <BR> tag to the end of each row, and thus forcing the new lines:

function buildBoard() {
  for(var i = 0; i 

https://www.internet.com

Produced by Yehuda Shiran and Tomer Shiran

Created: August 30, 1999
Revised: August 30, 1999

URL: https://www.webreference.com/js/column47/load.html