Netscape 6, Part VII: Object-Oriented DOCJSLIB 3.1: Programming Tic-Tac-Toe - Doc JavaScript | WebReference

Netscape 6, Part VII: Object-Oriented DOCJSLIB 3.1: Programming Tic-Tac-Toe - Doc JavaScript


Netscape 6, Part VII: Object-Oriented DOCJSLIB 3.1

Programming Tic-Tac-Toe

We have explained in detail the programming of Tic-Tac-Toe in Column 27, Introducing DOCJSLIB, A Cross-Browser JavaScript Library, and in Column 76, Netscape 6, Part V: DOCJSLIB 1.1. We focus here on the usage of DOCJSLIB 3.1. The main body of the application calls myBrowserAPIObj.makeImage() nine times, once for each square of the board game. The two-dimensional array grid[][] holds the location of the "o"s and the "x"s at all times. Here is the main body:

var lastPlayedBy = "o";
var grid = new Array();
grid[1] = new Array();
grid[2] = new Array();
grid[3] = new Array();
for (var i = 1; i myBrowserAPIObj.makeImage("box" + i + "" + j, // id
      "initialbutton.gif",     // URL
      100,                     // height
      100,                     // width
      "game box",              // alternative
       xBase + (i-1) * 108,    // position from left
       yBase + (j-1) * 108,    // position from top
       i,       // parameter passed to onclick handler
       j);      // parameter passed to onclick handler
  }
}

The function handleImageClick() handles user's clicks. We use DOCJSLIB to get set the images, thus changing them to "o"s and "x"s as the game progresses:

function handleImageClick(id, param1, param2) {
    if (myBrowserAPIObj.getSrc(id + "img")
      .indexOf('initialbutton.gif') myBrowserAPIObj.setSrc(id + "img", "xbutton.gif");
      lastPlayedBy = "x";
    }
    else {  // lastPlayedBy = "x"
      myBrowserAPIObj.setSrc(id + "img", "obutton.gif");
      lastPlayedBy = "o";
    }
    grid[param1][param2] = lastPlayedBy;
    if (rowComplete()) {
      alert("The " + lastPlayedBy + " wins");
      window.location.reload();
    }
    else if (itsAtie()) {
           alert("It's a tie");
           window.location.reload();
         }
}

A full listing of the code is given later in this column.

Next: use DOCJSLIB 3.1 in programming popout elements

http://www.internet.com


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: February 26, 2001
Revised: February 26, 2001

URL: http://www.webreference.com/js/column78/3.html