aboutsummaryrefslogtreecommitdiff
path: root/logic/dice.go
diff options
context:
space:
mode:
authorFlorian Fischer <florian.fl.fischer@fau.de>2017-02-18 19:48:20 +0100
committerFlorian Fischer <florian.fl.fischer@fau.de>2017-02-18 19:48:20 +0100
commitc4f76699aa1459564792395f272052fce6b433bd (patch)
tree49f6220ec4d2314b6e5afbce1f84feeb24f7baf4 /logic/dice.go
parent23ac00e3ae0f2810a4c6fe77744cb7d66cd4b427 (diff)
downloadgoffel-c4f76699aa1459564792395f272052fce6b433bd.tar.gz
goffel-c4f76699aa1459564792395f272052fce6b433bd.zip
TIL dice is the plural of die
Diffstat (limited to 'logic/dice.go')
-rw-r--r--logic/dice.go121
1 files changed, 121 insertions, 0 deletions
diff --git a/logic/dice.go b/logic/dice.go
new file mode 100644
index 0000000..a5cbade
--- /dev/null
+++ b/logic/dice.go
@@ -0,0 +1,121 @@
+// 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)
+}