Created
February 15, 2017 19:19
-
-
Save adamwatters/3512458271cfa04b0468d889c6cd7458 to your computer and use it in GitHub Desktop.
Checking if a piece in the game of Go is dead.
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
const spaceAt = (board, x, y) => { | |
if (x < 0 || x > board[0].length - 1) { | |
return 'outOfBounds' | |
} | |
if (y < 0 || y > board.length - 1) { | |
return 'outOfBounds' | |
} | |
return {content: board[y][x], x: x, y: y} | |
} | |
const DIRECTIONS = [{x: 1, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 0, y: -1}]; | |
const neighborsOf = (board, x, y) => { | |
const neighbors = []; | |
DIRECTIONS.forEach((d) => { | |
const neighbor = spaceAt(board, x + d.x, y + d.y); | |
if (neighbor !== 'outOfBounds') { | |
neighbors.push(neighbor); | |
} | |
}) | |
return neighbors; | |
} | |
const isEmpty = (space) => { | |
return space.content === 'e' | |
} | |
const areSameColor = (spaceOne, spaceTwo) => { | |
return spaceOne.content === spaceTwo.content; | |
} | |
const isUnvisited = (space, visitedSpaces) => { | |
return !(visitedSpaces.some(visitedSpace => { | |
return visitedSpace.x === space.x && visitedSpace.y === space.y | |
})) | |
} | |
const findUnvisitedAndSameColor = (space, neighbors, visited) => { | |
return neighbors.filter(neighbor => { | |
return areSameColor(neighbor, space) && isUnvisited(neighbor, visited) | |
}) | |
} | |
const isDead = (board, x, y) => { | |
const startingSpace = spaceAt(board, x, y); | |
if (startingSpace === 'outOfBounds') { | |
return 'outOfBounds' | |
} | |
if (isEmpty(startingSpace)) { | |
return 'emptySpace' | |
} | |
const visited = []; | |
const innerIsDead = (space) => { | |
const neighbors = neighborsOf(board, space.x, space.y); | |
if (neighbors.find(isEmpty)) { | |
return false; | |
} | |
const unvisitedAndSameColor = findUnvisitedAndSameColor(space, neighbors, visited) | |
if (unvisitedAndSameColor.length === 0) { | |
return true; | |
} | |
visited.push(space); | |
return unvisitedAndSameColor.every((uv) => { | |
return innerIsDead(uv) | |
}) | |
} | |
return innerIsDead(startingSpace) | |
} | |
const aliveBoard = [ | |
['e', 'e', 'e', 'e'], | |
['b', 'b', 'w', 'b'], | |
['b', 'b', 'w', 'b'], | |
['b', 'w', 'w', 'w'], | |
['b', 'b', 'b', 'b'], | |
]; | |
const deadBoard = [ | |
['e', 'e', 'e', 'e'], | |
['b', 'b', 'b', 'b'], | |
['b', 'b', 'w', 'b'], | |
['b', 'w', 'w', 'w'], | |
['b', 'b', 'w', 'b'], | |
]; | |
console.log(isDead(aliveBoard, 2, 3)) | |
console.log(isDead(deadBoard, 2, 3)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment