-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck.go
59 lines (52 loc) · 1008 Bytes
/
deck.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
package go_tsuro
import (
"errors"
"math/rand"
)
type deck struct {
deck []*tile
random *rand.Rand
}
func newDeck(random *rand.Rand) *deck {
d := make([]*tile, 0)
for _, edges := range tiles {
t, _ := newTile(edges)
d = append(d, t)
}
result := &deck{
deck: d,
random: random,
}
result.Shuffle()
return result
}
func (d *deck) Remove(tile *tile) error {
for idx, t := range d.deck {
if tile.equals(t) {
d.deck = append(d.deck[:idx], d.deck[idx+1:]...)
return nil
}
}
return errors.New("tile not found")
}
func (d *deck) Add(tiles ...*tile) {
d.deck = append(d.deck, tiles...)
d.Shuffle()
}
func (d *deck) Draw() (*tile, error) {
size := len(d.deck)
if size <= 0 {
return nil, errors.New("deck is empty so cannot draw")
}
tile := d.deck[size-1]
d.deck = d.deck[:size-1]
return tile, nil
}
func (d *deck) Shuffle() {
for i := 0; i < len(d.deck); i++ {
r := d.random.Intn(len(d.deck))
if i != r {
d.deck[r], d.deck[i] = d.deck[i], d.deck[r]
}
}
}