/*
* A complete tic-tac-toe widget, using JQuery. 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 = [],
SIZE = 3,
EMPTY = " ",
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 9-bit string, and a
* player's squares at any given time can be represented as a
* unique 9-bit value. A winner can thus be easily determined by
* checking whether the player's current 9 bits have covered any
* of the eight "three-in-a-row" combinations.
*
* 273 84
* \ /
* 1 | 2 | 4 = 7
* -----+-----+-----
* 8 | 16 | 32 = 56
* -----+-----+-----
* 64 | 128 | 256 = 448
* =================
* 73 146 292
*
*/
wins = [7, 56, 448, 73, 146, 292, 273, 84],
/*
* Clears the score and move count, erases the board, and makes it
* X's turn.
*/
startNewGame = function () {
turn = "X";
score = {"X": 0, "O": 0};
moves = 0;
squares.forEach(function (square) {square.html(EMPTY);});
},
/*
* Returns whether the given score is a winning score.
*/
win = function (score) {
for (var i = 0; i < wins.length; i += 1) {
if ((wins[i] & score) === wins[i]) {
return true;
}
}
return false;
},
/*
* Sets the clicked-on square to the current player's mark,
* then checks for a win or cats game. Also changes the
* current player.
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.