4 x 4 Tic Tac Toe
A trivial 4 x 4 tic tac toe game, using only regular JavaScript events.
JavaScript
/*
* A complete 4 x 4 tic-tac-toe widget. Just include this script in a
* browser page and play. A tic-tac-toe game will be included
* as a child element of the element with id "tictactoe". If the
* page has no such element, it will just be added at the end of
* the body.
*/
(function () {
var squares = [],
EMPTY = "\xA0",
SIZE = 1024,
MAX_MOVES = SIZE * SIZE,
score,
moves,
turn = "X";
/*
* To determine a win condition, each square is "tagged" from left
* to right, top to bottom, with successive powers of 2. Each cell
* thus represents an individual bit in a 16-bit string, and a
* player's squares at any given time can be represented as a
* unique 16-bit value. A winner can thus be easily determined by
* checking whether the player's current 16 bits have covered any
* of the eight "three-in-a-row" combinations.
*
* 1 | 2 | 4 | 8
* -----+------+-------+------
* 16 | 32 | 64 | 128
* -----+------+-------+------
* 256 | 512 | 1024 | 2048
* -----+------+-------+------
* 4096 | 8192 | 16384 | 32768
*
*/
wins = [
0x000F, // top row
0x00F0, // second row
0x0F00, // third row
0xF000, // fourth row
0x1111, // first column
0x2222, // second column
0x4444, // third column
0x8888, // fourth column
0x8421, // upper left diagonal
0x1248, // upper right diagonal
],
/*
* Clears the score and move count, erases the board, and makes it
* X's turn.
*/
startNewGame = function () {
var i;
turn = "X";
score = {"X": 0, "O": 0};
moves = 0;
for (i = 0; i < squares.length; i += 1) {
squares[i].firstChild.nodeValue = EMPTY;
}
},
/*
* Returns whether...