1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
import { board } from "../board.js"
import { Vector2 } from "../engine/vector2.js"
const SURROUNDING = [
new Vector2(-1, 0),
new Vector2(0, 1),
new Vector2(0, -1),
new Vector2(1, 0),
]
export function hasLiberties({
position,
team
}) {
return checkLiberties({
position,
team
})
}
function checkLiberties({
position,
team,
checkedStones = [],
checkedLiberties = [],
}) {
if (isInArray(position, checkedStones)) {
return false
}
if (checkedLiberties.length > 0) {
console.log(team, checkedLiberties)
}
checkedStones.push(position)
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 (!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 == data.team)
.forEach(z => {
checkLiberties({
position: z,
team: data.team,
checkedStones: data.checkedStones,
checkedLiberties: data.checkedLiberties,
})
})
}
|