-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdeck.go
More file actions
61 lines (50 loc) · 1.24 KB
/
deck.go
File metadata and controls
61 lines (50 loc) · 1.24 KB
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
package main
import (
"errors"
"math/rand"
)
type Deck[T any] struct {
cards []T
}
func (deck *Deck[T]) Shuffle() {
shuffledDeck := make([]T, len(deck.cards))
copy(shuffledDeck, deck.cards)
for i := range shuffledDeck {
j := rand.Intn(i + 1)
shuffledDeck[i], shuffledDeck[j] = shuffledDeck[j], shuffledDeck[i]
}
deck.cards = shuffledDeck
}
func (deck *Deck[T]) DrawSingle() (T, error) {
deckLen := len(deck.cards)
if deckLen > 0 {
lastIdx := deckLen - 1
card := deck.cards[lastIdx]
deck.cards = deck.cards[:lastIdx]
return card, nil
}
return *new(T), errors.New("deck is empty")
}
func (deck *Deck[T]) Draw(numberOfCards int) ([]T, error) {
deckLen := len(deck.cards)
if deckLen >= numberOfCards {
result := make([]T, numberOfCards)
copy(result, deck.cards[deckLen-numberOfCards:])
deck.cards = deck.cards[:deckLen-numberOfCards]
return result, nil
} else {
return *new([]T), errors.New("not enough cards")
}
}
func (deck *Deck[T]) DrawAll() []T {
result := make([]T, len(deck.cards))
copy(result, deck.cards)
deck.cards = []T{}
return result
}
func (deck *Deck[T]) AddSingle(card T) {
deck.cards = append(deck.cards, card)
}
func (deck *Deck[T]) AddAll(cards []T) {
deck.cards = append(deck.cards, cards...)
}