spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column27


Writing Application Functions

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

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);
}

http://www.internet.com


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger


Created: October 12, 1998
Revised: October 12, 1998

URL: http://www.webreference.com/js/column27/appfunctions.html