-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess2_api.go
100 lines (93 loc) · 2.59 KB
/
chess2_api.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"net/http"
"sort"
"github.com/CGamesPlay/chess2/pkg/chess2"
"github.com/gin-gonic/gin"
)
func parseArmySymbol(value string, param string) (chess2.Army, error) {
var army chess2.Army
var found bool
if value == "" {
return chess2.ArmyNone, fmt.Errorf("%s is required", param)
} else if len(value) == 1 {
army, found = chess2.FindArmySymbol(rune(value[0]))
}
if !found {
return chess2.ArmyNone, fmt.Errorf("%s must be a valid army symbol", param)
}
return army, nil
}
func formatGame(game chess2.Game) gin.H {
response := make(gin.H)
response["epd"] = chess2.EncodeEpd(game)
legalMoves := game.GenerateLegalMoves()
legalMovesStr := make([]string, len(legalMoves))
for i := 0; i < len(legalMoves); i++ {
legalMovesStr[i] = legalMoves[i].String()
}
sort.Strings(legalMovesStr)
response["legal_moves"] = legalMovesStr
response["game_over"] = game.GameState() != chess2.GameInProgress
switch game.GameState() {
case chess2.GameInProgress:
response["winner"] = nil
case chess2.GameOverWhite:
response["winner"] = "white"
case chess2.GameOverBlack:
response["winner"] = "black"
case chess2.GameOverDraw:
response["winner"] = "draw"
}
return response
}
func setupRouter() *gin.Engine {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
r.GET("/new", func(c *gin.Context) {
white, whiteErr := parseArmySymbol(c.Query("white"), "white")
black, blackErr := parseArmySymbol(c.Query("black"), "black")
if whiteErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": whiteErr.Error()})
}
if blackErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": blackErr.Error()})
}
game := chess2.GameFromArmies(white, black)
c.JSON(http.StatusOK, formatGame(game))
})
r.POST("/move", func(c *gin.Context) {
var request gin.H
if err := c.BindJSON(&request); err != nil {
return
}
game, err := chess2.ParseEpd(request["epd"].(string))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
move, err := chess2.ParseUci(request["move"].(string))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
nextGame := game.ApplyMove(move)
response := formatGame(nextGame)
duels := game.GenerateDuels(move)
// Strip off the first item, which is always "don't initiate a duel"
duelsStr := make([]string, len(duels)-1)
for i := 1; i < len(duels); i++ {
duelsStr[i-1] = duels[i].String()[4:]
}
response["available_duels"] = duelsStr
c.JSON(http.StatusOK, response)
})
return r
}
func main() {
r := setupRouter()
r.Run()
}