forked from gabrielecirulli/2048
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (76 loc) · 1.81 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/afghl/2048-ai/lib"
"github.com/gorilla/websocket"
"html/template"
"log"
"net/http"
"time"
)
var (
addr = flag.String("addr", ":8080", "http service address")
)
func main() {
fmt.Println("start")
flag.Parse()
http.HandleFunc("/ai", ai)
static := http.FileServer(http.Dir("./2048"))
http.Handle("/js/", static)
http.Handle("/style/", static)
http.Handle("/meta/", static)
http.Handle("/favicon.ico", static)
html := template.Must(template.ParseFiles("./2048/index.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = html.Execute(w, nil)
})
log.Printf("Service started on \x1b[32;1m%s\x1b[32;1m\x1b[0m\n", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type req struct {
Size int `json:"size"`
Grid [][]int `json:"grid"`
}
type rsp struct {
Act int `json:"act"`
}
func ai(w http.ResponseWriter, r *http.Request) {
fmt.Printf("in ai method \n")
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade:", err)
return
}
defer ws.Close()
agent := lib.NewAgent(3)
for {
_, p, err := ws.ReadMessage()
timer := time.NewTimer(1 * time.Millisecond)
if err != nil {
break
}
m := &req{}
if err := json.Unmarshal(p, m); err != nil {
fmt.Errorf("unmarshal error, %v \n", err)
return
}
state := lib.NewState(m.Size, m.Grid, 1)
act := agent.GetAction(state)
fmt.Printf("get action: %v\n", act)
r, _ := json.Marshal(rsp{Act: int(act)})
<-timer.C
if err := ws.WriteMessage(websocket.TextMessage, r); err != nil {
fmt.Errorf("write req error: %v \n", err)
}
}
}