forked from poiriermike/battlesnake-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.go
More file actions
66 lines (54 loc) · 1.5 KB
/
commands.go
File metadata and controls
66 lines (54 loc) · 1.5 KB
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
package main
import (
"encoding/json"
"net/http"
)
type JSON map[string]string
func respond(res http.ResponseWriter, obj JSON) {
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(obj)
}
func handleInfo(res http.ResponseWriter, req *http.Request) {
respond(res, JSON{
"color": "#ff0000",
"head": "https://golang.org/doc/gopher/gopherbw.png",
})
}
func handleStart(res http.ResponseWriter, req *http.Request) {
respond(res, JSON{
"taunt": "battlesnake-go!",
})
}
func handleMove(res http.ResponseWriter, req *http.Request) {
data, err := NewMoveRequest(req)
if err != nil {
respond(res, JSON{"move": "north", "taunt": "can't parse this!"})
return
}
snake := data.GetSnake(SNAKE_ID)
if snake == nil {
respond(res, JSON{"move": "north", "taunt": "snake not found!"})
return
}
board := NewBoard(data)
location := snake.Head()
var chosenDirection string
if tile := board.GetTile(location.X, location.Y-1); tile == EMPTY {
chosenDirection = "north"
} else if tile := board.GetTile(location.X, location.Y+1); tile == EMPTY {
chosenDirection = "south"
} else if tile := board.GetTile(location.X-1, location.Y); tile == EMPTY {
chosenDirection = "west"
} else if tile := board.GetTile(location.X+1, location.Y); tile == EMPTY {
chosenDirection = "east"
} else {
chosenDirection = "north"
}
respond(res, JSON{
"move": chosenDirection,
"taunt": "go go go!",
})
}
func handleEnd(res http.ResponseWriter, req *http.Request) {
respond(res, JSON{})
}