forked from jbowens/codenames
-
Notifications
You must be signed in to change notification settings - Fork 18
/
game.go
212 lines (188 loc) · 4.2 KB
/
game.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package codenames
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"math/rand"
"time"
)
const imagesPerGame = 20
type Team int
const (
Neutral Team = iota
Red
Blue
Black
)
func (t Team) String() string {
switch t {
case Red:
return "red"
case Blue:
return "blue"
case Black:
return "black"
default:
return "neutral"
}
}
func (t Team) Other() Team {
if t == Red {
return Blue
}
if t == Blue {
return Red
}
return t
}
func (t Team) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
func (t Team) Repeat(n int) []Team {
s := make([]Team, n)
for i := 0; i < n; i++ {
s[i] = t
}
return s
}
// GameState encapsulates enough data to reconstruct
// a Game's state. It's used to recreate games after
// a process restart.
type GameState struct {
Seed int64 `json:"seed"`
Round int `json:"round"`
Revealed []bool `json:"revealed"`
}
func (gs GameState) ID() string {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(gs)
if err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(buf.Bytes())
}
func decodeGameState(s string) (GameState, bool) {
data, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return GameState{}, false
}
var state GameState
err = gob.NewDecoder(bytes.NewReader(data)).Decode(&state)
return state, err == nil
}
func randomState() GameState {
return GameState{
Seed: rand.Int63(),
Revealed: make([]bool, imagesPerGame),
}
}
type Game struct {
GameState
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
StartingTeam Team `json:"starting_team"`
WinningTeam *Team `json:"winning_team,omitempty"`
Images []string `json:"-"`
RoundImages []string `json:"words"`
Layout []Team `json:"layout"`
}
func (g *Game) checkWinningCondition() {
if g.WinningTeam != nil {
return
}
var redRemaining, blueRemaining bool
for i, t := range g.Layout {
if g.Revealed[i] {
continue
}
switch t {
case Red:
redRemaining = true
case Blue:
blueRemaining = true
}
}
if !redRemaining {
winners := Red
g.WinningTeam = &winners
}
if !blueRemaining {
winners := Blue
g.WinningTeam = &winners
}
}
func (g *Game) NextTurn() error {
if g.WinningTeam != nil {
return errors.New("game is already over")
}
g.Round++
return nil
}
func (g *Game) Guess(idx int) error {
if idx > len(g.Layout) || idx < 0 {
return fmt.Errorf("index %d is invalid", idx)
}
if g.Revealed[idx] {
return errors.New("cell has already been revealed")
}
g.Revealed[idx] = true
if g.Layout[idx] == Black {
winners := g.CurrentTeam().Other()
g.WinningTeam = &winners
return nil
}
g.checkWinningCondition()
if g.Layout[idx] != g.CurrentTeam() {
g.Round = g.Round + 1
}
return nil
}
func (g *Game) CurrentTeam() Team {
if g.Round%2 == 0 {
return g.StartingTeam
}
return g.StartingTeam.Other()
}
func newGame(id string, imagePaths []string, state GameState) *Game {
rnd := rand.New(rand.NewSource(state.Seed))
game := &Game{
ID: id,
CreatedAt: time.Now(),
StartingTeam: Team(rnd.Intn(2)) + Red,
Images: imagePaths,
RoundImages: make([]string, 0, imagesPerGame),
Layout: make([]Team, 0, imagesPerGame),
GameState: state,
}
// Pick 25 random images.
used := map[string]struct{}{}
for len(used) < imagesPerGame {
w := imagePaths[rnd.Intn(len(imagePaths))]
if _, ok := used[w]; !ok {
used[w] = struct{}{}
game.RoundImages = append(game.RoundImages, w)
}
}
// Pick a random permutation of team assignments.
var teamAssignments []Team
teamAssignments = append(teamAssignments, Red.Repeat(7)...)
teamAssignments = append(teamAssignments, Blue.Repeat(7)...)
teamAssignments = append(teamAssignments, Neutral.Repeat(4)...)
teamAssignments = append(teamAssignments, Black)
teamAssignments = append(teamAssignments, game.StartingTeam)
shuffleCount := rnd.Intn(5) + 5
for i := 0; i < shuffleCount; i++ {
shuffle(rnd, teamAssignments)
}
game.Layout = teamAssignments
return game
}
func shuffle(rnd *rand.Rand, teamAssignments []Team) {
for i := range teamAssignments {
j := rnd.Intn(i + 1)
teamAssignments[i], teamAssignments[j] = teamAssignments[j], teamAssignments[i]
}
}