Add a general shuffler and deck shuffling.

This commit is contained in:
2023-04-01 19:13:42 -07:00
parent 20561c574c
commit b8c0e5603a
2 changed files with 71 additions and 1 deletions

View File

@ -23,7 +23,7 @@ const (
// The Deck stores cards yet-to-be-dealt.
type Deck[C StatsCollection] struct {
cards []Card[C]
rand rand.Rand
rand *rand.Rand
}
// Len returns the number of cards in the Deck.
@ -196,3 +196,45 @@ func (d *Deck[C]) InsertRandomRange(loFrac, hiFrac float64, card Card[C]) error
errs.Add(d.Insert(slot, card))
return errs.Emit()
}
// Shuffle completely shuffles the deck. If the deck has one or fewer cards,
// this returns WarningTooFewCards since nothing can be shuffled.
func (d *Deck[C]) Shuffle() error {
if len(d.cards) < 2 {
return WarningTooFewCards
}
ShuffleAll(d.cards, d.rand)
return nil
}
// ShufflePart shuffles the `n` cards of the deck starting at `loc`.
// If the provided range doesn't fit in the deck, this returns
// WarningTopClamped and/or WarningBottomClamped. If the eventual range
// of cards to be shuffled (after any off-the-end issues are corrected)
// is one or less, this returns WarningTooFewCards since nothing can
// be shuffled.
func (d *Deck[C]) ShufflePart(loc, n int) error {
if n < 2 {
// Nothing to do.
return WarningTooFewCards
}
var errs ErrorCollector
if loc < 0 {
errs.Add(Warningf("%w: loc was %d", WarningTopClamped, loc))
loc = 0
}
if loc+n > d.Len() {
errs.Add(Warningf("%w: deck size %d does not have %d cards at and after location %d",
WarningBottomClamped, len(d.cards), n, loc))
n = d.Len() - loc
// Now is there anything to do?
if n < 2 {
errs.Add(WarningTooFewCards)
return errs.Emit()
}
}
ShufflePart(d.cards, d.rand, loc, n)
return nil
}