This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
/
room.go
96 lines (87 loc) · 2.22 KB
/
room.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
package backend
import (
"encoding/json"
"errors"
"time"
)
// Status represents a player's status in a room.
type Status int
// Status constants.
const (
StatusActive Status = iota
StatusOut
StatusDc
StatusTurn
)
// MarshalJSON returns the status of the player in JSON.
// Numbers are not the pretty thing, we send status strings instead.
func (s Status) MarshalJSON() ([]byte, error) {
var st string
switch s {
case StatusActive:
st = "active"
case StatusOut:
st = "skipped"
case StatusDc:
st = "disconnected"
case StatusTurn:
st = "turn"
default:
st = "unknown"
}
return json.Marshal(st)
}
// Room represents a playing Room.
type Room struct {
ID int `json:"id"`
Members []User `json:"members"` // The list of all members.
Status []Status `json:"status"` // The status of each member in the room.
Sentences []Sentence `json:"sentences"` // The list of all sentences.
Start time.Time `json:"start"` // The time of the start of the game.
Current time.Time `json:"current,omitempty"` // The time when the current turn started.
Timeout time.Duration `json:"timeout"` // The time of each turn.
}
// Ended returns whether the game has ended.
func (r Room) Ended() bool {
// Simply put, the game ended if and only if only one player is active.
active := 0
for _, status := range r.Status {
if status == StatusActive || status == StatusTurn {
active++
}
}
return active == 1
}
// Index returns a player's index in the slice.
// Throws an error if it's not found.
func (r Room) Index(ID string) (int, error) {
for id, user := range r.Members {
if user.ID == ID {
return id, nil
}
}
return 0, errors.New("player not found")
}
// NextTurn returns the next turn and DOES NOT modifies the current status.
// Returns true if game ended.
func (r Room) NextTurn(last int) (int, bool) {
if r.Ended() {
return r.Winner(), true
}
cur := last
for {
cur = (cur + 1) % len(r.Members)
if r.Status[cur] == StatusActive {
return cur, false
}
}
}
// Winner returns the winner.
func (r Room) Winner() int {
for id, st := range r.Status {
if st == StatusActive || st == StatusTurn {
return id
}
}
return -1
}