github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/dice/dice.go (about)

     1  // Package dice contains common functions to generate random number.
     2  // It also initialize math/rand with the time in seconds at launch time.
     3  package dice // import "github.com/xmplusdev/xmcore/common/dice"
     4  
     5  import (
     6  	"math/rand"
     7  )
     8  
     9  // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
    10  func Roll(n int) int {
    11  	if n == 1 {
    12  		return 0
    13  	}
    14  	return rand.Intn(n)
    15  }
    16  
    17  // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
    18  func RollDeterministic(n int, seed int64) int {
    19  	if n == 1 {
    20  		return 0
    21  	}
    22  	return rand.New(rand.NewSource(seed)).Intn(n)
    23  }
    24  
    25  // RollUint16 returns a random uint16 value.
    26  func RollUint16() uint16 {
    27  	return uint16(rand.Int63() >> 47)
    28  }
    29  
    30  func RollUint64() uint64 {
    31  	return rand.Uint64()
    32  }
    33  
    34  func NewDeterministicDice(seed int64) *DeterministicDice {
    35  	return &DeterministicDice{rand.New(rand.NewSource(seed))}
    36  }
    37  
    38  type DeterministicDice struct {
    39  	*rand.Rand
    40  }
    41  
    42  func (dd *DeterministicDice) Roll(n int) int {
    43  	if n == 1 {
    44  		return 0
    45  	}
    46  	return dd.Intn(n)
    47  }