dice.go 871 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "strconv"
  6. "strings"
  7. )
  8. type Dice struct {
  9. Number uint // Number of dice to roll
  10. }
  11. // Perform the rolls without the Pips
  12. func (d *Dice) Roll() (total, wild int, rolls []int) {
  13. var die int
  14. for range make([]byte, d.Number-1) {
  15. die = rand.Intn(6) + 1
  16. total += die
  17. rolls = append(rolls, die)
  18. }
  19. wild = rand.Intn(6) + 1
  20. return
  21. }
  22. // Returns the text form for this Dice
  23. //
  24. // Without the Pips
  25. func (d *Dice) String() string {
  26. return fmt.Sprintf("%dD", d.Number)
  27. }
  28. func NewDice(D uint) *Dice {
  29. return &Dice{
  30. Number: D,
  31. }
  32. }
  33. func NewDiceFromString(text string) (*Dice, error) {
  34. var (
  35. number int
  36. err error
  37. )
  38. if strings.Contains(text, "D") {
  39. text = strings.ReplaceAll(text, "D", "")
  40. }
  41. number, err = strconv.Atoi(text)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &Dice{
  46. Number: uint(number),
  47. }, nil
  48. }