Created
May 28, 2015 06:02
-
-
Save d-git/dbf8ff5ac456133c10d8 to your computer and use it in GitHub Desktop.
Five in a row
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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