-
Notifications
You must be signed in to change notification settings - Fork 2
/
vector.go
81 lines (73 loc) · 1.66 KB
/
vector.go
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
package chess_engine
type Vector struct {
DiffFile int8
DiffRank int8
}
func NewVector(f, r int8) Vector {
return Vector{f, r}
}
func (v Vector) Invert() Vector {
return Vector{v.DiffFile * -1, v.DiffRank * -1}
}
func (v Vector) Normalize() Vector {
maxDiff := v.DiffFile
if maxDiff < 0 {
maxDiff = maxDiff * -1
}
if v.DiffRank > maxDiff {
maxDiff = v.DiffRank
} else if (v.DiffRank * -1) > maxDiff {
maxDiff = v.DiffRank * -1
}
normDiffFile, normDiffRank := v.DiffFile/maxDiff, v.DiffRank/maxDiff
return Vector{normDiffFile, normDiffRank}
}
func (v Vector) FromPosition(pos Position) Position {
return Position(int8(pos) + v.DiffFile + (v.DiffRank * 8))
}
func (v Vector) FollowVectorUntilEdgeOfBoard(pos Position) []Position {
result := []Position{}
diff := Position(v.DiffFile + v.DiffRank*8)
if v.DiffFile == 0 {
pos += diff
for pos >= 0 && pos < 64 {
result = append(result, pos)
pos += diff
}
return result
}
file := (pos % 8)
lastPos := Position(0)
maxHorizontal := Position(0)
if v.DiffFile == -1 {
maxHorizontal = file
} else {
maxHorizontal = 7 - file
}
lastPos = pos + maxHorizontal*diff
if lastPos == pos {
return result
}
pos += diff
for pos >= 0 && pos < 64 && maxHorizontal > 0 {
maxHorizontal--
result = append(result, pos)
pos += diff
if pos == lastPos && pos >= 0 && pos < 64 {
result = append(result, pos)
break
}
}
return result
}
func (v Vector) IsPointOnLine(p1, p2 Position) bool {
for _, pos := range v.FollowVectorUntilEdgeOfBoard(p1) {
if pos == p2 {
return true
}
}
return false
}
func (v Vector) Eq(v2 Vector) bool {
return v.DiffFile == v2.DiffFile && v.DiffRank == v2.DiffRank
}