Netscape 6, Part V: DOCJSLIB 1.1: The Tic-Tac-Toe Functions - Doc Javascript
Netscape 6, Part V: DOCJSLIB 1.1
The Tic-Tac-Toe Functions
Now that you understand how the event handler is working, the application is almost ready. There are two functions that need to be written, the one that checks for a winner, and the one that checks for ties. Checking for a winning row is done here by just going row by row and verifying that all three squares have the same player written on it:
function rowComplete() {
var lastPlayedBy = grid[1][1];
if ((lastPlayedBy != "") &&
(grid[2][1] == lastPlayedBy) &&
(grid[3][1] == lastPlayedBy)) return(true);
lastPlayedBy = grid[1][2];
if ((lastPlayedBy != "") &&
(grid[2][2] == lastPlayedBy) &&
(grid[3][2] == lastPlayedBy)) return(true);
lastPlayedBy = grid[1][3];
if ((lastPlayedBy != "") &&
(grid[2][3] == lastPlayedBy) &&
(grid[3][3] == lastPlayedBy)) return(true);
lastPlayedBy = grid[1][1];
if ((lastPlayedBy != "") &&
(grid[1][2] == lastPlayedBy) &&
(grid[1][3] == lastPlayedBy)) return(true);
lastPlayedBy = grid[2][1];
if ((lastPlayedBy != "") &&
(grid[2][2] == lastPlayedBy) &&
(grid[2][3] == lastPlayedBy)) return(true);
lastPlayedBy = grid[3][1];
if ((lastPlayedBy != "") &&
(grid[3][2] == lastPlayedBy) &&
(grid[3][3] == lastPlayedBy)) return(true);
lastPlayedBy = grid[1][1];
if ((lastPlayedBy != "") &&
(grid[2][2] == lastPlayedBy) &&
(grid[3][3] == lastPlayedBy)) return(true);
lastPlayedBy = grid[1][3];
if ((lastPlayedBy != "") &&
(grid[2][2] == lastPlayedBy) &&
(grid[3][1] == lastPlayedBy)) return(true);
}
The function that checks for a tie is much shorter. We scan the grid and return if there is still empty clickable boxes:
function itsAtie() {
for( var i = 1; i <= 3; i++)
for( var j = 1; j <= 3; j++)
if (grid[i][j] == "") return(false);
return(true);
}
Next: The Tic-Tac-Toe Code
Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: January 29, 2001
Revised: January 29, 2001
URL: https://www.webreference.com/js/column76/9.html