...

Source file src/code.rocketnine.space/tslocum/joker/deck.go

Documentation: code.rocketnine.space/tslocum/joker

     1  package joker
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  // Deck defines a playing card deck containing any number of cards.
     9  type Deck struct {
    10  	Cards Cards
    11  
    12  	rand *rand.Rand
    13  }
    14  
    15  // NewDeck initializes a deck of cards. A seed value of 0 is replaced with the
    16  // current unix time in nanoseconds.
    17  func NewDeck(c Cards, seed int64) *Deck {
    18  	if seed == 0 {
    19  		seed = time.Now().UnixNano()
    20  	}
    21  
    22  	return &Deck{Cards: c.Copy(), rand: rand.New(rand.NewSource(seed))}
    23  }
    24  
    25  // Shuffle randomizes the order of the deck using the Fisher-Yates shuffle
    26  // algorithm.
    27  func (d *Deck) Shuffle() {
    28  	for i := len(d.Cards) - 1; i > 0; i-- {
    29  		j := d.rand.Intn(i + 1)
    30  		d.Cards[i], d.Cards[j] = d.Cards[j], d.Cards[i]
    31  	}
    32  }
    33  
    34  // Draw removes cards from the deck and returns them as a slice.
    35  func (d *Deck) Draw(count int) (cards Cards, ok bool) {
    36  	if count > len(d.Cards) {
    37  		return nil, false
    38  	}
    39  
    40  	cards = d.Cards[0:count].Copy()
    41  	d.Cards = d.Cards[count:]
    42  	return cards, true
    43  }
    44  

View as plain text