Created
August 15, 2020 23:07
-
-
Save KelsonBall/7b46714d028b91f97b4755bf341e8eff to your computer and use it in GitHub Desktop.
This file contains 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
// assuming "Board" has a getTokenAt(row, column) function | |
// that returns "red", "blue", or null for each position | |
// and an isInBounds(row, column) function that returns | |
// true if row and column are valid, false if they are off the board | |
// returns number of players tokens that are connected in a direction | |
// (Board, string, int, int, int, int) -> int | |
function countConnectedInDirection(board, player, newTokenRow, newTokenColumn, directionX, directionY) { | |
var count = 1; // number connected, starts at 1 because of the new token | |
// scan "forward" in direction | |
var x = newTokenRow + directionX; | |
var y = newTokenColumn + directionY; | |
// while on the board and the token at (x,y) is the current players | |
while (board.isInBounds(x, y) && board.getTokenAt(x, y) === player) { | |
count++; | |
x += directionX; | |
y += directionY; | |
} | |
// scan "backward" in direction | |
var x = newTokenRow - directionX; | |
var y = newTokenColumn - directionY; | |
// while on the board and the token at (x,y) is the current players | |
while (board.isInBounds(x, y) && board.getTokenAt(x, y) === player) { | |
count++; | |
x -= directionX; | |
y -= directionY; | |
} | |
return count; | |
} | |
// check each direction for a win | |
// (Board, string, int, int) -> bool | |
function doesNewTokenResultInWinForPlayer(board, player, newTokenRow, newTokenColumn) { | |
// check column | |
let columnCount = countConnectedInDirection(board, player, newTokenRow, newTokenColumn, 0, 1); // change row by 0, columnn by 1 | |
if (columnCount >= 4) { | |
return true; | |
} | |
// row wins | |
let rowCount = countConnectedInDirection(board, player, newTokenRow, newTokenColumn, 1, 0); // change row by 1, column by 0 | |
if (rowCount >= 4) { | |
return true; | |
} | |
// check if diagonal that "descends left-to-right" wins | |
let diagonalOne = countConnectedInDirection(board, playr, newTokenRow, newTokenColumn, 1, 1); // change row by 1, column by 1 | |
if (diagonalOne >= 4) { | |
return true; | |
} | |
// check if diagonal that "assends left-to-right" wins | |
let diagonalTwo = countConnectedInDirection(board, playr, newTokenRow, newTokenColumn, 1, -1); // change row by 1, column by 1 | |
if (diagonalTwo >= 4) { | |
return true; | |
} | |
// if none of these conditions won, the result is false | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment