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
|
package main
import (
"log"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"muhq.space/muhqs-game/go/ui"
)
type (
// keyAction is a function applying an action for an input event to the game.
// It reports if it should be removed after its invocation.
// An unsuccessful action returns err != nil.
keyAction func(ui.InputEvent, *Game) (bool, error)
// keyBindings maps inputs to actions
keyBindings map[any]keyAction
)
func (g *Game) handleKeyBindings(bindings keyBindings) (err error) {
for i, ev := range ui.Input {
for _k, a := range bindings {
var remove bool
switch k := _k.(type) {
case ebiten.MouseButton:
if ev.Kind == ui.Click && ev.Ctx.(ui.ClickCtx).Btn == k {
remove, err = a(ev, g)
ui.ConsumeInput(i)
}
case ui.InputType:
if k != ev.Kind {
continue
}
remove, err = a(ev, g)
ui.ConsumeInput(i)
// TODO: model simple key presses using the inout queue
case ebiten.Key:
if inpututil.IsKeyJustPressed(k) {
remove, err = a(ev, g)
}
}
if remove {
delete(bindings, _k)
}
if err != nil {
return
}
}
}
return
}
func selection(ev ui.InputEvent, g *Game) (bool, error) {
x, y := ev.X, ev.Y
obj := g.findObjectAt(x, y)
if obj == nil {
return false, nil
}
if g.prompt != nil {
if err := g.prompt.Add(obj); err != nil {
log.Println("Not added", obj, "to active prompt:", err)
if g.prompt.Cancelable() {
g.handleSelection(obj, x, y)
}
} else {
g.updateHighlight()
}
} else {
g.handleSelection(obj, x, y)
}
return false, nil
}
func pass(_ ui.InputEvent, g *Game) (bool, error) {
g.passButton.Click(0, 0)
return false, nil
}
func reset(_ ui.InputEvent, g *Game) (bool, error) {
g.reset()
return false, nil
}
|