In: Computer Science
/* Pleasefind below the index.html file for tic tac toe 4*4(containing js code)*/
/* To find wining position every box is "marked" from top to bottom, left to right, with increasing power of 2. Each box thus is an individual bit is nine bit string, and a player boxes at any given time can be viewed as a nine-bit number. A winner can thus be easily determined by checking whether the player's current nine bits have covered any of the eight three-in-a-row combination.*/
/* Save the below file as index.html, and run in any browser */
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
(function () {
var boxes = [],notfilled = "\xA0",n = 4,MAXMOVES = n *
n,setcore,moves,turn = "X";
conditionforwin =
[0x000F,/*predefined*/0x00F0,/*hardcoded*/0x0F00,/*values*/0xF000,/*values*/0x1111,/*values*/0x2222,/*values*/0x4444,/*values*/0x8888,/*values*/0x8421,/*values*/0x1248,],
gamestart = function () {
var i;
turn = "X";
setcore = {"X": 0, "O": 0};
moves = 0;
for (i = 0; i < boxes.length; i += 1) {
boxes[i].firstChild.nodeValue = notfilled;
}
},
win = function (setcore) {
var i;
for (i = 0; i < conditionforwin.length; i += 1) {
if ((conditionforwin[i] & setcore) === conditionforwin[i])
{
return true;
}
}
return false;
},
set = function () {
if (this.firstChild.nodeValue !== notfilled) {
return;
}
this.firstChild.nodeValue = turn;
moves += 1;
setcore[turn] += this.points;
console.log(turn + " " + setcore[turn]);
if (win(setcore[turn])) {
alert(turn + " conditionforwin!");
gamestart();
} else if (moves === MAXMOVES) {
alert("Cat\u2019s game!");
gamestart();
} else {
turn = turn === "X" ? "O" : "X";
}
},
startplaying = function () {
var board = document.createElement("table"),
points = 1,
i, j,
tuple, column,
previous;
board.border = 1;
for (i = 0; i < n; i += 1) {
tuple = document.createElement("tr");
board.appendChild(tuple);
for (j = 0; j < n; j += 1) {
column = document.createElement("td");
column.align = column.valign = 'center';
column.width = column.height = 50;
column.onclick = set;
column.points = points;
column.appendChild(document.createTextNode(""));
tuple.appendChild(column);
boxes.push(column);
points += points;
}
}
previous = document.getElementById("tictactoe") ||
document.body;
previous.appendChild(board);
gamestart();
};
if (typeof window.onload === "function") {
setwhattodoloading = window.onload;
window.onload = function () {
setwhattodoloading();
startplaying();
};
} else {
window.onload = startplaying;
}
}());
</script>
</head>
<body>
</body>
</html>