Skip to content

Instantly share code, notes, and snippets.

@d-git
Created May 28, 2015 06:02
Show Gist options
  • Save d-git/dbf8ff5ac456133c10d8 to your computer and use it in GitHub Desktop.
Save d-git/dbf8ff5ac456133c10d8 to your computer and use it in GitHub Desktop.
Five in a row
function Board() {
var GOAL = 5, winnerIs, values = {'white': {}, 'black': {}};
function placePiece(col, row, player) {
values[player][col + '-' + row] = 1;
winnerIs = findWinner(col, row, player);
}
function findWinner(x, y, player) {
for (var radian = 0; radian < Math.PI; radian += Math.PI / 4) {
var dx = Math.round(Math.cos(radian)),
dy = Math.round(Math.sin(radian));
if (getCount(player, x, y, dx, dy, true) + getCount(player, x, y, dx, dy, false) + 1 >= GOAL) {
return player;
}
}
}
function getCount(player, x, y, dx, dy, along) {
var k = 1;
while (values[player][(x + (k * (along ? dx : -dx))) + '-' + (y + (k * (along ? dy : -dy)))]) {
k++;
}
return k - 1;
}
return {
placePiece: placePiece,
winner: function () {
return winnerIs;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment