-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameboard.go
127 lines (106 loc) · 2.19 KB
/
gameboard.go
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
122
123
124
125
126
127
package main
import (
"errors"
"github.com/gdamore/tcell/v2"
"golang.org/x/exp/maps"
)
const (
IDLE buttonState = iota
WANTED
PUSHED
)
const (
MIN_WANTED_AMOUNT = 5
MAX_WANTED_AMOUNT = 10
)
var (
ErrButtonNotFound = errors.New("button not found")
ErrTriggerNotFound = errors.New("button trigger not found")
)
type (
Gameboard struct {
ids ButtonIds
buttons Buttons
layout Layout
}
ButtonTrigger rune
ButtonIds map[ButtonTrigger]ButtonId
ButtonId int
Buttons map[ButtonId]*Button
Layout map[ButtonId]ButtonLayout
ButtonLayout struct {
x, y int
symbol [][]rune
}
)
func (gb *Gameboard) NewRound() {
gb.reset()
gb.wantRandomButtons()
}
func (gb *Gameboard) PushButton(bid ButtonId) error {
b, ok := gb.buttons[bid]
if !ok {
return ErrButtonNotFound
}
b.push()
return nil
}
type (
Button struct {
state buttonState
prevState buttonState
}
buttonState int
)
func (gb *Gameboard) draw(s tcell.Screen, force bool) {
for bid, b := range gb.buttons {
layout := gb.layout[bid]
b.draw(s, layout, force)
}
}
func (gb *Gameboard) reset() {
for _, b := range gb.buttons {
b.idle()
}
}
func (gb *Gameboard) wantRandomButtons() {
randomIds := generateUniqueRandoms(maps.Keys(gb.buttons), MIN_WANTED_AMOUNT, MAX_WANTED_AMOUNT)
for _, id := range randomIds {
button := gb.buttons[id]
button.want()
}
}
func (b *Button) draw(s tcell.Screen, layout ButtonLayout, force bool) {
if b.state == b.prevState && !force {
return
}
originX, originY, symbol := layout.x, layout.y, layout.symbol
var style tcell.Style
switch b.state {
case IDLE:
style = tcell.StyleDefault.Foreground(tcell.ColorGreen)
case WANTED:
style = tcell.StyleDefault.Foreground(tcell.ColorDarkOrange)
case PUSHED:
style = tcell.StyleDefault.Foreground(tcell.ColorDarkOliveGreen)
}
for y, row := range symbol {
for x, r := range row {
s.SetContent(originX+x, originY+y, r, nil, style)
}
}
}
func (b *Button) idle() {
b.prevState = b.state
b.state = IDLE
}
func (b *Button) want() {
b.prevState = b.state
b.state = WANTED
}
func (b *Button) push() bool {
wasWanted := b.state != WANTED
b.prevState = b.state
b.state = PUSHED
return wasWanted
}