From add682d6aaa50b2c1561731cdb1696bf7665cba3 Mon Sep 17 00:00:00 2001 From: nil Date: Sat, 14 Dec 2024 21:38:07 +0100 Subject: liberty fix and tidying code --- src/engine/liberty.js | 63 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 18 deletions(-) (limited to 'src/engine/liberty.js') 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 } + -- cgit v1.2.3