joker/deck.go

44 lines
943 B
Go
Raw Permalink Normal View History

2020-01-15 15:56:59 +00:00
package joker
2020-01-09 15:24:45 +00:00
import (
2020-01-12 15:41:12 +00:00
"math/rand"
"time"
2020-01-09 15:24:45 +00:00
)
// Deck defines a playing card deck containing any number of cards.
type Deck struct {
Cards Cards
2020-08-20 00:33:22 +00:00
rand *rand.Rand
2020-01-12 15:41:12 +00:00
}
2020-01-09 15:24:45 +00:00
2020-01-14 03:37:38 +00:00
// NewDeck initializes a deck of cards. A seed value of 0 is replaced with the
// current unix time in nanoseconds.
2020-01-12 15:41:12 +00:00
func NewDeck(c Cards, seed int64) *Deck {
if seed == 0 {
seed = time.Now().UnixNano()
2020-01-09 15:24:45 +00:00
}
2020-08-20 00:33:22 +00:00
return &Deck{Cards: c.Copy(), rand: rand.New(rand.NewSource(seed))}
2020-01-09 15:24:45 +00:00
}
2020-08-20 00:33:22 +00:00
// Shuffle randomizes the order of the deck using the Fisher-Yates shuffle
// algorithm.
2020-01-12 15:41:12 +00:00
func (d *Deck) Shuffle() {
2020-08-20 00:33:22 +00:00
for i := len(d.Cards) - 1; i > 0; i-- {
j := d.rand.Intn(i + 1)
2020-01-12 15:41:12 +00:00
d.Cards[i], d.Cards[j] = d.Cards[j], d.Cards[i]
2020-01-09 15:24:45 +00:00
}
}
// Draw removes cards from the deck and returns them as a slice.
2020-01-12 15:41:12 +00:00
func (d *Deck) Draw(count int) (cards Cards, ok bool) {
2020-01-09 15:24:45 +00:00
if count > len(d.Cards) {
2020-01-12 15:41:12 +00:00
return nil, false
2020-01-09 15:24:45 +00:00
}
2020-01-12 15:41:12 +00:00
cards = d.Cards[0:count].Copy()
2020-01-09 15:24:45 +00:00
d.Cards = d.Cards[count:]
2020-01-12 15:41:12 +00:00
return cards, true
2020-01-09 15:24:45 +00:00
}