diff options
Diffstat (limited to 'server/api')
| -rw-r--r-- | server/api/game.go | 60 |
1 files changed, 52 insertions, 8 deletions
diff --git a/server/api/game.go b/server/api/game.go index 636ff66..d830d71 100644 --- a/server/api/game.go +++ b/server/api/game.go @@ -2,6 +2,7 @@ package api import ( "net/http" + "sakura/data/cirno" "sakura/engine" "slices" "uuid" @@ -20,7 +21,11 @@ var connections = make(map[uuid.UUID][]*Conn) func GameCreate(w http.ResponseWriter, r *http.Request) { id := uuid.NewV7() - games[id] = engine.NewGame() + g := engine.NewGame() + games[id] = g + g.Yin.SetCharacter(cirno.Cirno) + g.Yang.SetCharacter(cirno.Cirno) + w.Write([]byte(id.String())) } @@ -36,7 +41,10 @@ func GameConnect(w http.ResponseWriter, r *http.Request) { http.Error(w, "game not found", http.StatusNotFound) return } - wsConn, err := upgrader.Upgrade(w, r, nil) + p, c := Bind(game, w, r) + wsConn, err := upgrader.Upgrade(w, r, http.Header{ + "Set-Cookie": []string{c.String()}, + }) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -53,12 +61,47 @@ func GameConnect(w http.ResponseWriter, r *http.Request) { }) return nil }) - err = wsConn.WriteJSON(game) + go PumpRead(uid, game, p, wsConn) +} + +func Bind(g *engine.Game, w http.ResponseWriter, r *http.Request) (*engine.Player, *http.Cookie) { + cookie, err := r.Cookie("User") + newUser := false + + var id string if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return + newUser = true + uid := uuid.NewV7() + id = uid.String() + cookie = &http.Cookie{ + Name: "User", + Value: id, + Quoted: true, + Secure: true, + HttpOnly: false, + Path: "/", + SameSite: http.SameSiteStrictMode, + } + http.SetCookie(w, cookie) + } else { + id = cookie.Value } - go PumpRead(uid, game, wsConn) + + switch { + case newUser && g.Yin.Cookie == "": + g.Yin.Cookie = id + return g.Yin, cookie + case newUser && g.Yang.Cookie == "": + g.Yang.Cookie = id + return g.Yang, cookie + case g.Yang.Cookie == id: + return g.Yang, cookie + case g.Yin.Cookie == id: + return g.Yin, cookie + default: + return nil, cookie + } + } func Update(id uuid.UUID, g *engine.Game) { @@ -67,9 +110,11 @@ func Update(id uuid.UUID, g *engine.Game) { } } -func PumpRead(id uuid.UUID, g *engine.Game, conn *websocket.Conn) { +func PumpRead(id uuid.UUID, g *engine.Game, p *engine.Player, conn *websocket.Conn) { var interaction engine.InteractionID for { + strippedGame := g.Present(p) + Update(id, &strippedGame) err := conn.ReadJSON(&interaction) if err != nil { break @@ -80,6 +125,5 @@ func PumpRead(id uuid.UUID, g *engine.Game, conn *websocket.Conn) { } a.Then(g) g.ActionToHistory(a) - Update(id, g) } } |
