This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
impl.go
561 lines (471 loc) · 11.3 KB
/
impl.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package splenda
import (
"encoding/base64"
"errors"
"math/rand"
)
// Impl implements Splenda's game logic.
type Impl struct {
db *DB
rng rng
}
type realrng struct{}
func (realrng) Intn(n int) int {
return rand.Intn(n)
}
// NewImpl creates a new Impl.
func NewImpl(db *DB) *Impl {
return &Impl{
db: db,
rng: realrng{},
}
}
// NewImplSeed creates a new impl with the given psuedorandom seed.
func NewImplSeed(db *DB, seed int64) *Impl {
return &Impl{
db: db,
rng: rand.New(rand.NewSource(seed)),
}
}
// ListGames lists all the games that the given user is in.
func (i *Impl) ListGames(userID string) ([]*GameSummary, error) {
games, err := i.db.ListGames(userID)
if err != nil {
return nil, err
}
ret := []*GameSummary{}
for gameID, players := range games {
ret = append(ret, &GameSummary{
ID: gameID,
Players: players,
})
}
return ret, nil
}
func newID() string {
bs := make([]byte, 16)
if _, err := rand.Read(bs); err != nil {
panic(err)
}
return base64.URLEncoding.EncodeToString(bs)
}
func numCoins(players []string) int {
switch len(players) {
case 2:
return 4
case 3:
return 5
case 4:
return 7
default:
panic("weird number of players")
}
}
// NewGame creates a new game.
func (i *Impl) NewGame(userID string, players []string) (string, error) {
if find(userID, players) == -1 {
return "", errors.New("you must be one of the players")
}
if len(players) < 2 {
return "", errors.New("need at least two players")
}
if len(players) > 4 {
return "", errors.New("no more than four players")
}
if !unique(players) {
return "", errors.New("players must be unique")
}
gameID := newID()
tx, err := i.db.NewTX(gameID)
if err != nil {
return "", err
}
defer tx.Close()
players = shuffle(players, i.rng)
// Set up the game table itself.
if err := tx.InsertGame(players[0]); err != nil {
return "", err
}
nc := numCoins(players)
coins := map[string]int{
red: nc,
blue: nc,
green: nc,
black: nc,
white: nc,
wild: 5,
}
if err := tx.InsertCoins(coins); err != nil {
return "", err
}
nobles := pickNobles(len(players)+1, i.rng)
if err := tx.InsertNobles(nobles); err != nil {
return "", err
}
t1 := shuffleCards(tier1, i.rng)
t2 := shuffleCards(tier2, i.rng)
t3 := shuffleCards(tier3, i.rng)
if err := tx.InsertCards(t1[:4], t2[:4], t3[:4]); err != nil {
return "", err
}
if err := tx.InsertDecks(t1[4:], t2[4:], t3[4:]); err != nil {
return "", err
}
// Set up the players.
if err := tx.InsertPlayers(players); err != nil {
return "", err
}
allcolors := []string{red, blue, green, black, white, wild}
for _, player := range players {
if err := tx.InsertPlayerCoins(player, allcolors); err != nil {
return "", err
}
}
if err := tx.Commit(); err != nil {
return "", err
}
return gameID, nil
}
// GetGame gets the current state of a given game.
func (i *Impl) GetGame(gameID string, userID string, ts string) (*Game, error) {
tx, err := i.db.NewTX(gameID)
if err != nil {
return nil, err
}
defer tx.Close()
if !tx.IsPlaying(userID) {
return nil, errors.New("no such game")
}
game, err := tx.GetGameBasics()
if err != nil {
return nil, err
}
// TODO: Do something different if ts is current?
table, err := getTable(tx)
if err != nil {
return nil, err
}
game.Table = table
players, err := getPlayers(tx)
if err != nil {
return nil, err
}
game.Players = players
if err := tx.Commit(); err != nil {
return nil, err
}
return game, nil
}
// DeleteGame deletes a game.
func (i *Impl) DeleteGame(gameID string, userID string) error {
tx, err := i.db.NewTX(gameID)
if err != nil {
return err
}
defer tx.Close()
if !tx.IsPlaying(userID) {
return errors.New("no such game")
}
if err := tx.DeleteGame(); err != nil {
return err
}
return tx.Commit()
}
// Take3 takes three coins of different colors.
func (i *Impl) Take3(gameID string, userID string, colors []string) (string, error) {
if len(colors) == 0 || len(colors) > 3 {
return "", errors.New("must specify three colors")
}
for _, c := range colors {
if !isNormalColor(c) {
return "", errors.New("invalid coin color")
}
}
if !unique(colors) {
return "", errors.New("colors must be unique")
}
m := mover{gameID: gameID, userID: userID, db: i.db}
return m.Move(func(tx *TX) (string, string, error) {
if m.State() != play {
return "", "", errors.New("can't do that right now")
}
delta := map[string]int{}
for _, c := range colors {
delta[c] = 1
}
if err := m.EarnCoins(tx, delta, delta); err != nil {
return "", "", err
}
return m.NextPlayer()
})
}
func unique(strs []string) bool {
set := map[string]struct{}{}
for _, str := range strs {
set[str] = struct{}{}
}
return len(set) == len(strs)
}
// Take2 takes two coins of the same color.
func (i *Impl) Take2(gameID string, userID string, color string) (string, error) {
if !isNormalColor(color) {
return "", errors.New("invalid coin color")
}
m := mover{gameID: gameID, userID: userID, db: i.db}
return m.Move(func(tx *TX) (string, string, error) {
if m.State() != play {
return "", "", errors.New("can't do that right now")
}
limit := map[string]int{color: 4}
delta := map[string]int{color: 2}
if err := m.EarnCoins(tx, limit, delta); err != nil {
return "", "", err
}
return m.NextPlayer()
})
}
// Reserve reserves a card.
func (i *Impl) Reserve(gameID string, userID string, tier int, index int) (string, error) {
m := mover{gameID: gameID, userID: userID, db: i.db}
return m.Move(func(tx *TX) (string, string, error) {
if m.State() != play {
return "", "", errors.New("can't do that right now")
}
// Make sure the player does not already have too many reserved cards.
_, reservedIDs, err := tx.GetPlayerCards(userID)
if err != nil {
return "", "", err
}
if len(reservedIDs) >= 3 {
return "", "", errors.New("too many cards already reserved")
}
// Grab the ID of the card that's currently in that position.
// TODO: Handle reserving directly off the top of the deck.
card, err := m.GetCardID(tx, tier, index)
if err != nil {
return "", "", err
}
// Insert it to the player's hand.
reserved := true
if err := tx.InsertPlayerCard(userID, card, reserved); err != nil {
return "", "", err
}
// Replace it on the board.
if err := m.DealCard(tx, tier, index); err != nil {
return "", "", err
}
// Give the player a wildcard coin if we can.
delta := map[string]int{wild: 1}
err = m.EarnCoins(tx, delta, delta)
if err != nil && err != ErrInsufficientCoins {
return "", "", err
}
return m.NextPlayer()
})
}
// Buy buys a card.
func (i *Impl) Buy(gameID string, userID string, tier int, index int) (string, error) {
m := mover{gameID: gameID, userID: userID, db: i.db}
return m.Move(func(tx *TX) (string, string, error) {
if m.State() != play {
return "", "", errors.New("can't do that right now")
}
// Grab the card that's currently in that position.
cardID, err := m.GetCardID(tx, tier, index)
if err != nil {
return "", "", err
}
card, ok := cardFromID(cardID)
if !ok {
return "", "", errors.New("bogus card ID")
}
// Get the current card count.
cards, err := m.GetCardCounts(tx)
if err != nil {
return "", "", err
}
// Pay the cost of the card.
if err := m.PayCost(tx, cards, card.cost); err != nil {
return "", "", err
}
reserved := false
if tier > 0 {
// Insert it to the player's hand.
if err := tx.InsertPlayerCard(userID, cardID, reserved); err != nil {
return "", "", err
}
// Replace it on the board.
if err := m.DealCard(tx, tier, index); err != nil {
return "", "", err
}
} else {
// Simply convert it to un-reserved.
if err := tx.UpdatePlayerCard(userID, cardID, reserved); err != nil {
return "", "", err
}
}
cards[card.color]++
return nextState(&m, tx, cards)
})
}
//
// Helper functions.
//
// NextState returns the next state to transition to after a player buys a card.
func nextState(m *mover, tx *TX, cards map[string]int) (string, string, error) {
// Does this player now have enough cards to pick a noble? If yes, give them
// time to pick one.
can, err := m.CanAffordNoble(tx, cards)
if err != nil {
return "", "", err
}
if can {
return picknoble, m.userID, nil
}
// Is this the last player, and if so has someone won the game? If so
// stop playing and let them know they won.
over, err := isGameOver(tx)
if err != nil {
return "", "", err
}
if over {
return gameover, m.userID, nil
}
// Otherwise just go to the next player's turn.
return m.NextPlayer()
}
// IsGameOver returns true if the game is now over.
func isGameOver(tx *TX) (bool, error) {
players, err := getPlayers(tx)
if err != nil {
return false, err
}
for _, p := range players {
if p.Points >= 15 {
return true, nil
}
}
return false, nil
}
// GetTable gets information about the table.
func getTable(tx *TX) (*Table, error) {
coins, err := tx.GetCoins()
if err != nil {
return nil, err
}
nobleIDs, err := tx.GetNobles()
if err != nil {
return nil, err
}
nobles, err := ToNobles(nobleIDs)
if err != nil {
return nil, err
}
cards, err := getCards(tx)
if err != nil {
return nil, err
}
decks, err := tx.GetDecks()
if err != nil {
return nil, err
}
return &Table{
Coins: coins,
Nobles: nobles,
Cards: cards,
Decks: decks,
}, nil
}
// GetCards gets the cards currently on the table.
func getCards(tx *TX) ([][]*Card, error) {
cards := [][]*Card{}
for tier := 1; tier <= 3; tier++ {
ids, err := tx.GetCards(tier)
if err != nil {
return nil, err
}
row, err := ToCards(ids)
if err != nil {
return nil, err
}
cards = append(cards, row)
}
return cards, nil
}
// GetPlayers gets data about the players in this game.
func getPlayers(tx *TX) ([]*Player, error) {
userIDs, err := tx.GetPlayers()
if err != nil {
return nil, err
}
players := []*Player{}
for _, userID := range userIDs {
player, err := getPlayer(tx, userID)
if err != nil {
return nil, err
}
players = append(players, player)
}
return players, nil
}
// GetPlayer gets data about the given player.
func getPlayer(tx *TX, userID string) (*Player, error) {
coins, err := tx.GetPlayerCoins(userID)
if err != nil {
return nil, err
}
nobleIDs, err := tx.GetPlayerNobles(userID)
if err != nil {
return nil, err
}
nobles, err := ToNobles(nobleIDs)
if err != nil {
return nil, err
}
cardIDs, reservedIDs, err := tx.GetPlayerCards(userID)
if err != nil {
return nil, err
}
cards, err := partitionCards(cardIDs)
if err != nil {
return nil, err
}
reserved, err := ToCards(reservedIDs)
if err != nil {
return nil, err
}
points := score(nobles, cards)
return &Player{
ID: userID,
Coins: coins,
Nobles: nobles,
Cards: cards,
Reserved: reserved,
Points: points,
}, nil
}
// Partition partitions a player's cards by color.
func partitionCards(ids []string) (map[string][]*Card, error) {
ret := map[string][]*Card{}
for _, id := range ids {
card, err := ToCard(id)
if err != nil {
return nil, err
}
ret[card.Color] = append(ret[card.Color], card)
}
return ret, nil
}
// Score calculates the current score for a player.
func score(nobles []*Noble, cards map[string][]*Card) int {
points := 0
for _, noble := range nobles {
points += noble.Points
}
for _, row := range cards {
for _, card := range row {
points += card.Points
}
}
return points
}