-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeck.go
54 lines (48 loc) · 966 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
package main
import (
"errors"
"math/rand"
"strings"
"time"
)
// Deck represents the deck of cars - talon
type Deck struct {
cards []*Card
}
func newDeck() *Deck {
rand.Seed(time.Now().Unix())
cards := make([]*Card, 36)
i := 0
for _, v := range cardValues {
for _, s := range cardSuits {
cards[i] = &Card{Value: v, Suit: s}
i = i + 1
}
}
return &Deck{
cards: cards,
}
}
func (p *Deck) shuffle() {
for i := range p.cards {
j := rand.Intn(i + 1)
p.cards[i], p.cards[j] = p.cards[j], p.cards[i]
}
}
func (p *Deck) getCard() (*Card, error) {
n := len(p.cards)
if n > 0 {
card := p.cards[n-1]
// delete
p.cards = append(p.cards[:n-1], p.cards[n:]...)
return card, nil
}
return &Card{}, errors.New("no cards left in deck")
}
func (p *Deck) asString() string {
var cardsStrings []string
for _, card := range p.cards {
cardsStrings = append(cardsStrings, card.Value+card.Suit)
}
return strings.Join(cardsStrings, " ")
}