Skip to content

Instantly share code, notes, and snippets.

@supernova-at
Last active August 29, 2015 14:27
Show Gist options
  • Save supernova-at/9d97976eafab912f152a to your computer and use it in GitHub Desktop.
Save supernova-at/9d97976eafab912f152a to your computer and use it in GitHub Desktop.
Tic Tacs Toe
function evaluateBoard(data) {
/*
* Setup
*/
// Don't want to keep calling .charAt, so save all the values with easier-to-use names up front
var topLeft = data.charAt(0);
var topMiddle = data.charAt(1);
var topRight = data.charAt(2);
var centerLeft = data.charAt(3);
var centerMiddle = data.charAt(4);
var centerRight = data.charAt(5);
var bottomLeft = data.charAt(6);
var bottomMiddle = data.charAt(7);
var bottomRight = data.charAt(8);
// Ways to win: Rows
var topRow = [topLeft, topMiddle, topRight];
var centerRow = [centerLeft, centerMiddle, centerRight];
var bottomRow = [bottomLeft, bottomMiddle, bottomRight];
// Ways to win: Columns
var leftColumn = [topLeft, centerLeft, bottomLeft];
var middleColumn = [topMiddle, centerMiddle, bottomMiddle];
var rightColumn = [topRight, centerRight, bottomRight];
// Ways to win: Diagonals
var firstDiagonal = [topLeft, centerMiddle, bottomRight];
var secondDiagonal = [bottomLeft, centerMiddle, topRight];
// Put all the ways to win together in an array of "ways to win"
var waysToWin = [topRow, centerRow, bottomRow, leftColumn, middleColumn, rightColumn, firstDiagonal, secondDiagonal];
/*
* Start actual algorithm to evaluate the board
*/
// Is there a winner? Go through each way to win and see if either side won that way
var isWinner = false;
var winningSide = null;
for (var wayToWinIndex = 0; wayToWinIndex < waysToWin.length; wayToWinIndex++) {
// Which group are we testing in this iteration?
var targetGroup = waysToWin[wayToWinIndex];
// Test the group to see if it's a winner
isWinner = groupIsWinner(targetGroup);
// did someone win?
if (isWinner) {
// Which side won?
winningSide = targetGroup[0]; // x or o
break; // don't have to keep going
}
}
// If we have a winner, declare it!
if (isWinner) {
return winningSide + ' wins!';
}
else { // we don't have a winner
// is the game incomplete or tie?
// If it's a tie, there won't be any empty squares
if (data.indexOf('-') === -1) {
// No empty squares, it's a tie
return 'The game is a tie';
}
else { // there are empty sqaures. Game is incomplete
return 'The game is still in progress';
}
}
}
function groupIsWinner (group) {
// Only a winner if the three spaces match and they're not empty
return group[0] !== '-' &&
group[0] === group[1] &&
group[1] === group[2];
}
@supernova-at
Copy link
Author

@paulevans, awesome! Just getting a chance to read through this now - I'd say keep it here for now, if you want to generalize into something more easily digestible for the thread though, that would be awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment