-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrpc.go
62 lines (49 loc) · 1.3 KB
/
rpc.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
package main
import (
"context"
"fmt"
"github.com/golang-cz/snake/proto"
)
func (s *Server) JoinGame(ctx context.Context, stream proto.JoinGameStreamWriter) error {
events := make(chan *proto.State, 10)
state, subscriptionId := s.subscribe(events)
defer s.unsubscribe(subscriptionId)
// Send initial state.
if err := stream.Write(state, nil); err != nil {
return err
}
// Send updates. TODO: Send diffs only.
for {
select {
case <-ctx.Done():
switch err := ctx.Err(); err {
case context.Canceled:
return proto.ErrWebrpcClientDisconnected
default:
return proto.ErrWebrpcInternalError
}
case state := <-events:
if err := stream.Write(state, nil); err != nil {
return err
}
}
}
}
func (s *Server) CreateSnake(ctx context.Context, username string) (uint64, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.createSnake(username)
}
func (s *Server) TurnSnake(ctx context.Context, snakeId uint64, direction *proto.Direction) error {
if direction == nil {
return fmt.Errorf("nil direction")
}
s.mu.Lock()
defer s.mu.Unlock()
snake, ok := s.state.Snakes[snakeId]
if !ok {
return proto.ErrSnakeNotFound.WithCause(fmt.Errorf("snakeId %v not found", snakeId))
}
// Turn snake, if possible, and buffer up to 2 actions.
return turnSnake(snake, direction, 2)
}