1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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)
}
|