-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.go
83 lines (65 loc) · 1.39 KB
/
game.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
package main
import (
"errors"
"github.com/gdamore/tcell/v2"
)
type Game struct {
screen tcell.Screen
audio Audio
gameboard *Gameboard
}
var ErrInvalidButtonSetName = errors.New("invalid button set name")
func NewGame(screen tcell.Screen, buttonSetName string) (*Game, error) {
audio := newAudio()
gameboard := &Gameboard{}
buttonSetCreator, ok := buttonSetCreators[buttonSetName]
if !ok {
return nil, ErrInvalidButtonSetName
}
gameboard.ids, gameboard.buttons, gameboard.layout = buttonSetCreator()
return &Game{
screen,
audio,
gameboard,
}, nil
}
func (g *Game) Start() error {
if err := g.audio.register("pop", "pop.mp3"); err != nil {
return err
}
g.draw(true)
for {
ev := g.screen.PollEvent()
gb := g.gameboard
switch ev := ev.(type) {
case *tcell.EventResize:
g.screen.Sync()
case *tcell.EventKey:
if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC {
return nil
}
if ev.Key() == tcell.KeyRune {
switch r := ev.Rune(); r {
case ' ':
gb.NewRound()
default:
_ = g.audio.play("pop")
maybeTrigger := ButtonTrigger(r)
bid, ok := gb.ids[maybeTrigger]
if !ok {
return ErrTriggerNotFound
}
err := gb.PushButton(bid)
if err != nil {
return err
}
}
}
}
g.draw(false)
}
}
func (g *Game) draw(force bool) {
g.gameboard.draw(g.screen, force)
g.screen.Show()
}