diff options
author | nil <niljo@airmail.cc> | 2024-12-14 21:38:07 +0100 |
---|---|---|
committer | nil <niljo@airmail.cc> | 2024-12-14 21:38:07 +0100 |
commit | add682d6aaa50b2c1561731cdb1696bf7665cba3 (patch) | |
tree | 81bbb91e40d3aa537f41ab884ff4f7dd13d113c9 /src/engine/liberty.js | |
parent | 1b6275b4fbc4ab7bcd876938f807aad9ce1900a6 (diff) |
liberty fix and tidying code
Diffstat (limited to 'src/engine/liberty.js')
-rw-r--r-- | src/engine/liberty.js | 63 |
1 files changed, 45 insertions, 18 deletions
diff --git a/src/engine/liberty.js b/src/engine/liberty.js index d5d4448..6d1bbda 100644 --- a/src/engine/liberty.js +++ b/src/engine/liberty.js @@ -24,46 +24,73 @@ function checkLiberties({ checkedStones = [], checkedLiberties = [], }) { - if ( - Array.from(checkedStones) - .some(p => Vector2.equals(p, position)) - ) { + if (isInArray(position, checkedStones)) { return false } + + if (checkedLiberties.length > 0) { + console.log(team, checkedLiberties) + } checkedStones.push(position) - let surroundingSquares = Array.from(SURROUNDING) + let surroundingSquares = getSurroundingSquares(position) + + findEmptySquares( + surroundingSquares, + checkedLiberties + ) + + findFriendlyStones( + surroundingSquares, + {team, checkedStones, checkedLiberties} + ) + + if (checkedLiberties.length == 1 && checkedStones.length < 2) { + return true + } + + if (checkedLiberties.length > 1) { + return true + } + + return false +} + +function isInArray(position, array) { + return Array.from(array) + .some(p => Vector2.equals(p, position)) +} + +function getSurroundingSquares(position) { + return Array.from(SURROUNDING) .map(v => Vector2.sum(v, position)) .filter(z => 0 <= z.x && z.x < board.size && 0 <= z.y && z.y < board.size ) +} +function findEmptySquares(surroundingSquares, checkedLiberties) { surroundingSquares .filter(z => board.stones[z.y][z.x] == undefined) .forEach(z => { - if (!Array.from(checkedStones) - .some(p => Vector2.equals(p, z)) - ) { + if (!isInArray(z, checkedLiberties)) { checkedLiberties.push(z) } }) +} +function findFriendlyStones(surroundingSquares, data) { surroundingSquares .filter(z => board.stones[z.y][z.x] != undefined) - .filter(z => board.stones[z.y][z.x].team == team) + .filter(z => board.stones[z.y][z.x].team == data.team) .forEach(z => { checkLiberties({ position: z, - team: team, - checkedStones: checkedStones, - checkedLiberties: checkedLiberties, + team: data.team, + checkedStones: data.checkedStones, + checkedLiberties: data.checkedLiberties, }) }) - - if (checkedLiberties.length > 0) { - return true - } - - return false } + |