// Copyright (c) 2016 Florian Fischer. All rights reserved. // Use of this source code is governed by a MIT license found in the LICENSE file. package logic import ( "errors" "fmt" "math/rand" "sort" ) var diceRunes = [7]string{"", "\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"} var fancy = false func SetFancyPrint(f bool) { fancy = f } type Dice [5]int func NewDice() Dice { d := Dice{} d.Roll(nil) return d } func (d *Dice) Roll(i []int) error { if i == nil || len(i) == 0 { i = []int{1, 2, 3, 4, 5} } for _, v := range i { if v > 6 || v < 1 { return errors.New("index out of range") } d[v-1] = rand.Int()%6 + 1 } sort.Ints(d[0:]) return nil } func (d Dice) String() string { s := "" for _, v := range d { if fancy { s += diceRunes[v] + " " } else { s += fmt.Sprintf("%d ", v) } } return fmt.Sprintf("%s", s) } func (d Dice) Sum(i int) int { s := 0 for _, v := range d { if v == i || i == 0 { s += v } } return s } func (d Dice) sumSame() []int { s := []int{1} idx := 0 for i := 1; i < 5; i++ { if d[i] == d[i-1] { s[idx]++ } else { s = append(s, 1) idx++ } } sort.Sort(sort.Reverse(sort.IntSlice(s))) return s } func (d Dice) IsThreeOfAKind() bool { return d.sumSame()[0] >= 3 } func (d Dice) IsFourOfAKind() bool { return d.sumSame()[0] >= 4 } func (d Dice) IsFullHouse() bool { s := d.sumSame() return s[0] == 3 && s[1] == 2 } func (d Dice) IsYahtzee() bool { return d.sumSame()[0] >= 5 } func (d Dice) isStraight(length int) bool { s := 1 max_s := s for i := 0; i < 4; i++ { if d[i]+1 == d[i+1] { s++ } else if d[i] != d[i+1] { if s > max_s { max_s = s } s = 1 } } if s > max_s { max_s = s } return max_s >= length } func (d Dice) IsSmallStraight() bool { return d.isStraight(4) } func (d Dice) IsLargeStraight() bool { return d.isStraight(5) }