122 lines
2.1 KiB
Go
122 lines
2.1 KiB
Go
|
package ui
|
||
|
|
||
|
import (
|
||
|
"time"
|
||
|
|
||
|
"opslag.de/schobers/galleg/allegro5"
|
||
|
)
|
||
|
|
||
|
func shouldClose(ev allegro5.Event) bool {
|
||
|
switch e := ev.(type) {
|
||
|
case *allegro5.KeyCharEvent:
|
||
|
switch e.KeyCode {
|
||
|
case allegro5.KeyEscape:
|
||
|
return true
|
||
|
case allegro5.KeyF4:
|
||
|
if e.Modifiers&allegro5.KeyModAlt == allegro5.KeyModAlt {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
case *allegro5.DisplayCloseEvent:
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
func shouldToggleDebug(ev allegro5.Event) bool {
|
||
|
switch e := ev.(type) {
|
||
|
case *allegro5.KeyCharEvent:
|
||
|
switch e.KeyCode {
|
||
|
case allegro5.KeyD:
|
||
|
return e.Modifiers&allegro5.KeyModAlt == allegro5.KeyModAlt
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
func switchState(ctx Context, curr State, s State) error {
|
||
|
var err error
|
||
|
err = curr.Leave(ctx)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
return s.Enter(ctx)
|
||
|
}
|
||
|
|
||
|
func Init() error {
|
||
|
return allegro5.Init(allegro5.InitAll)
|
||
|
}
|
||
|
|
||
|
func Run(w, h int, title string, s State, f Fonts, opts *allegro5.NewDisplayOptions) error {
|
||
|
if nil == opts {
|
||
|
opts = &allegro5.NewDisplayOptions{}
|
||
|
}
|
||
|
disp, err := allegro5.NewDisplay(w, h, *opts)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
disp.SetWindowTitle(title)
|
||
|
defer disp.Destroy()
|
||
|
|
||
|
evq, err := allegro5.NewEventQueue()
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
evq.RegisterDisplay(disp)
|
||
|
evq.RegisterKeyboard()
|
||
|
evq.RegisterMouse()
|
||
|
defer evq.Destroy()
|
||
|
|
||
|
ctx := newContext(disp, f)
|
||
|
|
||
|
var state = s
|
||
|
err = state.Enter(ctx)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
var t = time.Now()
|
||
|
main:
|
||
|
for nil != state {
|
||
|
for ev := evq.Get(); ev != nil; ev = evq.Get() {
|
||
|
if shouldClose(ev) {
|
||
|
break main
|
||
|
}
|
||
|
if shouldToggleDebug(ev) {
|
||
|
ctx.dbg.enbl = !ctx.dbg.enbl
|
||
|
}
|
||
|
err := state.Handle(ctx, ev)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
var now = time.Now()
|
||
|
var dt = now.Sub(t)
|
||
|
var s, err = state.Update(ctx, dt)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
t = now
|
||
|
if s != nil {
|
||
|
err = switchState(ctx, state, s)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
state = s
|
||
|
}
|
||
|
ctx.dbg.resetRainbow()
|
||
|
err = state.Render(ctx)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
disp.Flip()
|
||
|
time.Sleep(10 * time.Millisecond)
|
||
|
}
|
||
|
err = state.Leave(ctx)
|
||
|
if nil != err {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|