Internet Explorer 5.0, Part III: Connect Three Game Code - Doc JavaScript
Connect Three Game Code
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var lastPlayedBy = "x";
var grid = new Array();
grid[1] = new Array();
grid[2] = new Array();
grid[3] = new Array();
for (var i = 1; i <= 3; i++)
for (var j = 1; j <= 3; j++)
grid[i][j] = "";
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);
}
function itsAtie() {
for( var i = 1; i <= 3; i++)
for( var j = 1; j <= 3; j++)
if (grid[i][j] == "") return(false);
return(true);
}
function handleBoxClick(i, j) {
if (eval("box" + i + j + ".src").indexOf('initialbutton.gif') < 0) return;
if (lastPlayedBy == "o") {
eval("document.all.box" + i + j + ".src = 'xbutton.gif'");
lastPlayedBy = "x";
}
else { // lastPlayedBy = "x"
eval("document.all.box" + i + j + ".src = 'obutton.gif'");
lastPlayedBy = "o";
}
grid[i][j] = lastPlayedBy;
if (rowComplete()) {
alert("The " + lastPlayedBy + " wins");
window.location.reload();
}
else if (itsAtie()) {
alert("It's a tie");
window.location.reload();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<IMG ID="box11" onClick="handleBoxClick(1,1)" SRC="initialbutton.gif">
<IMG ID="box21" onClick="handleBoxClick(2,1)" SRC="initialbutton.gif">
<IMG ID="box31" onClick="handleBoxClick(3,1)" SRC="initialbutton.gif"><BR>
<IMG ID="box12" onClick="handleBoxClick(1,2)" SRC="initialbutton.gif">
<IMG ID="box22" onClick="handleBoxClick(2,2)" SRC="initialbutton.gif">
<IMG ID="box32" onClick="handleBoxClick(3,2)" SRC="initialbutton.gif"><BR>
<IMG ID="box13" onClick="handleBoxClick(1,3)" SRC="initialbutton.gif">
<IMG ID="box23" onClick="handleBoxClick(2,3)" SRC="initialbutton.gif">
<IMG ID="box33" onClick="handleBoxClick(3,3)" SRC="initialbutton.gif">
</BODY>
Created: August 28, 1998
Revised: August 28, 1998
URL: https://www.webreference.com/js/column24/code1.html