-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfen.go
78 lines (68 loc) · 1.95 KB
/
fen.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
package main
import (
"errors"
"fmt"
"regexp"
"strings"
)
var defaultBoard = [8][8]byte{
{'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}}
func contains(s []byte, e byte) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func isValidFen(fen string) bool {
// var linePattern = "[1-9rnbqkpRNBQKP]+"
//var fenRegex = fmt.Sprintf("%s/%s/%s/%s/%s/%s/%s/%s w|b (K?Q?k?q?)|- ([a-h][1-8])|- \\d+ \\d+", linePattern, linePattern, linePattern, linePattern, linePattern, linePattern, linePattern, linePattern)
var fenRegex = "\\s*([rnbqkpRNBQKP1-8]+\\/){7}([rnbqkpRNBQKP1-8]+)\\s[bw-]\\s(([a-hkqA-HKQ]{1,4})|(-))\\s(([a-h][36])|(-))\\s\\d+\\s\\d+\\s*"
var isValid, _ = regexp.MatchString(fenRegex, fen)
return isValid
}
func getBoardLine(fenElement string) ([8]byte, error) {
var line = [8]byte{}
var pos = 0
for _, cellValue := range fenElement {
if pos >= 8 {
return line, errors.New(fmt.Sprintf("Oops: %s is not a valid fen element", fenElement))
break
}
if contains(validPieces, byte(cellValue)) {
line[pos] = byte(cellValue)
pos = pos + 1
continue
} else {
pos = pos + int((int(cellValue) - int('0')))
}
}
return line, nil
}
func getBoardFromFen(fen string) ([8][8]byte, error) {
if false == isValidFen(fen) {
return defaultBoard, errors.New("Invalid FEN !")
}
var splits = strings.Split(fen, " ")
var lines = strings.Split(splits[0], "/")
var board = [8][8]byte{}
for y := 0; y < 8; y++ {
var err error
board[y], err = getBoardLine(lines[y])
if err != nil {
return defaultBoard, err
}
}
return board, nil
}
func isChessPieceOrPawn(piece byte) bool{
return piece != ' ' && contains(validPieces, piece)
}