A DOM-Based Snakes Game, Part I: The Main Script | WebReference

A DOM-Based Snakes Game, Part I: The Main Script


A DOM-Based Snakes Game, Part I (4)

The Main Script

Unlike the Sliding Puzzle from the previous column, the Snakes' board is constantly changing, even w/o a player intervention. Familiarize yourself with the game again. The snake is always on the move, even if the player is not engaged. Such a constant movement is achieved via the setInterval() intrinsic function. Here is the main script:

var divNode = document.createElement("DIV");
divNode.align = "center";
bodyNode.appendChild(divNode);
var squareNode = document.createElement("IMG");
var brNode = document.createElement("BR");
buildBoard();
loadPicture();
displayGreeting();
startGame();
setInterval("moveOne()", interval);

The main program gives you a high-level abstract of the game's architecture and flow. The first line creates the root of the subtree we will deal with in the game:

var divNode = document.createElement("DIV");

The createElement method is one of the DOM's dozen methods, explained earlier in Column 43. It creates an HTML tag element. In this case we create a DIV tag node. The DIV element serves here as a container for the Snakes' 299 tags. To position the game board in the center of the browser's window, we need to align the DIV accordingly:

divNode.align = "center";

Notice how we set the node properties. The name of the property is identical to the corresponding HTML attributes of the corresponding tag. We use the align property here, exactly as we would have used the ALIGN attribute of the DIV tag. The property should always be in lower case characters.

A DOM's subtree is not visible unless it is connected to the BODY node. Connecting our divNode node to the BODY node is simple:

bodyNode.appendChild(divNode);

The appendChild method accepts the child object as a parameter (divNode) and connects it to the method's father. As explained in Column 44, each new child is added at the end of the children list, childNodes. Our DIV container includes two types of elements: IMG and BR. We create one of each so we can clone them later:

var squareNode = document.createElement("IMG");
var brNode = document.createElement("BR");

The rest of the script is in a higher abstraction level. We first build the board:

buildBoard();

Then we load its images:

loadPicture();

We greet the player with game instructions:

displayGreeting();

We start the game by displaying the snake and its target:

startGame();

And finally we go into an infinite loop of equally-spaced-in-time steps. In each step we move the snake one grid square:

setInterval("moveOne()", interval);

In the next column we'll explain in detail each of this functions.

https://www.internet.com

Produced by Yehuda Shiran and Tomer Shiran

Created: August 16, 1999
Revised: August 16, 1999

URL: https://www.webreference.com/js/column46/main.html