Skip to content

Instantly share code, notes, and snippets.

@sdevani
Created May 2, 2014 15:00
Show Gist options
  • Save sdevani/d7d554da8be5b7df9f69 to your computer and use it in GitHub Desktop.
Save sdevani/d7d554da8be5b7df9f69 to your computer and use it in GitHub Desktop.
Tic Tac Toe Solution
// Using NaN instead of null is a clever hack. See checkForWinner for details.
var spaces = [
NaN, NaN, NaN,
NaN, NaN, NaN,
NaN, NaN, NaN
];
var player1 = 'veggies';
var player2 = 'junkfood';
var currentPlayer = null;
var gameWon = false;
var setNextTurn = function () {
if (currentPlayer === player1) {
currentPlayer = player2;
}
else {
currentPlayer = player1;
}
$('#turn-label').text(currentPlayer);
};
var checkForWinner = function () {
// Because (NaN === NaN) is always false, we can safely assume
// that if three spaces in a row are the same, all three spaces are
// marked by a player, and not all empty.
if ( spaces[0] === spaces[1] && spaces[1] === spaces[2]
|| spaces[3] === spaces[4] && spaces[4] === spaces[5]
|| spaces[6] === spaces[7] && spaces[7] === spaces[8]
|| spaces[0] === spaces[3] && spaces[3] === spaces[6]
// TODO: Check for rest of game winning cases
)
{
console.log('somebody won');
$(document).trigger('game-win', currentPlayer);
}
};
$(document).on('click', '#board .space', function (e) {
if (gameWon) {
alert("Game is over");
return;
}
var spaceNum = $(e.currentTarget).index();
console.log('You clicked on space #' + spaceNum);
// Marks the space with the current player's name
// TODO: Don't mark it unless the space is blank
if (spaces[spaceNum]) {
alert("This space has already been taken");
} else {
spaces[spaceNum] = currentPlayer;
// Adds a class to elem so css can take care of the visuals
$('#board .space:eq(' + spaceNum + ')').addClass(currentPlayer);
checkForWinner();
setNextTurn();
}
});
$(document).on('game-win', function (e, winner) {
alert(winner);
gameWon = true;
});
// Start the game
setNextTurn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment