-
Notifications
You must be signed in to change notification settings - Fork 4
/
deck.go
84 lines (69 loc) · 1.81 KB
/
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
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
package main
import (
"math/rand"
"time"
)
// Deck is standard playing card collection, it contains up to 52 unique cards.
type Deck struct {
Cards []*Card
}
// Shuffle reorganises the cards in the deck to a random order
func (d *Deck) Shuffle() {
d.ShuffleFromSeed(time.Now().UnixNano())
}
// ShuffleFromSeed reorganises the cards in the deck to a random order using
// the specified seed for rand.Seed().
func (d *Deck) ShuffleFromSeed(seed int64) {
rand.Seed(seed)
for c := 0; c < len(d.Cards); c++ {
swap := rand.Intn(len(d.Cards))
if swap != c {
d.Cards[swap], d.Cards[c] = d.Cards[c], d.Cards[swap]
}
}
}
// Push adds the specified card to the top of the deck
func (d *Deck) Push(card *Card) {
d.Cards = append(d.Cards, card)
}
// Pop removes the top card from the deck and returns it
func (d *Deck) Pop() *Card {
card := d.Cards[0]
d.Cards = d.Cards[1:]
return card
}
// Remove takes the specified card out of the deck
func (d *Deck) Remove(card *Card) {
for i, c := range d.Cards {
if cardEquals(c, card) {
d.Cards = append(d.Cards[:i], d.Cards[i+1:]...)
}
}
}
// NewSortedDeck returns a standard deck in sorted order - starting with Ace of Clubs, ending with King of Spades.
func NewSortedDeck() *Deck {
deck := &Deck{}
c := 0
suit := SuitClubs
for i := 0; i < 4; i++ {
for value := 1; value <= ValueKing; value++ {
deck.Cards = append(deck.Cards, NewCard(value, suit))
c++
}
suit++
}
return deck
}
// NewShuffledDeck returns a 52 card deck in random order.
func NewShuffledDeck() *Deck {
deck := NewSortedDeck()
deck.Shuffle()
return deck
}
// NewShuffledDeckFromSeed returns a 52 card deck in random order.
// The randomness is seeded using the seed parameter.
func NewShuffledDeckFromSeed(seed int64) *Deck {
deck := NewSortedDeck()
deck.ShuffleFromSeed(seed)
return deck
}