Introducing DOCJSLIB, Part I: Writing Application Functions - Doc JavaScript
Writing Application 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);
}
Created: October 12, 1998
Revised: October 12, 1998
URL: https://www.webreference.com/js/column27/appfunctions.html