ichigo/engine/game.go

66 lines
1.4 KiB
Go
Raw Normal View History

2021-07-23 13:12:54 +10:00
package engine
import (
2021-07-23 13:46:19 +10:00
"sort"
2021-07-23 13:12:54 +10:00
"github.com/hajimehoshi/ebiten/v2"
)
2021-07-23 14:59:49 +10:00
// Updater is a component that can update. Update is called repeatedly.
2021-07-23 13:12:54 +10:00
type Updater interface {
Update() error
}
2021-07-23 14:59:49 +10:00
// Drawer is a component that can draw itself. Draw is called often.
// DrawAfter is used to reorder components.
2021-07-23 13:12:54 +10:00
type Drawer interface {
Draw(*ebiten.Image)
2021-07-23 13:46:19 +10:00
DrawAfter(Drawer) bool
2021-07-23 13:12:54 +10:00
}
// Game implements the ebiten methods using a collection of components.
type Game struct {
2021-07-23 13:13:50 +10:00
ScreenWidth int
ScreenHeight int
Components []interface{}
2021-07-23 13:12:54 +10:00
}
// Update calls Update on all Updater components.
func (g *Game) Update() error {
for _, c := range g.Components {
if u, ok := c.(Updater); ok {
if err := u.Update(); err != nil {
return err
}
}
}
return nil
}
// Draw calls Draw on all Drawer components.
func (g *Game) Draw(screen *ebiten.Image) {
for _, c := range g.Components {
if d, ok := c.(Drawer); ok {
d.Draw(screen)
}
}
}
// Layout returns the configured screen width/height.
func (g *Game) Layout(outsideWidth, outsideHeight int) (w, h int) {
return g.ScreenWidth, g.ScreenHeight
}
2021-07-23 13:46:19 +10:00
// Sort sorts the components by draw order.
// Non-Drawers are sorted first.
func (g *Game) Sort() {
sort.Slice(g.Components, func(i, j int) bool {
a, aok := g.Components[i].(Drawer)
b, bok := g.Components[j].(Drawer)
if aok && bok {
return b.DrawAfter(a)
}
return !aok && bok
})
}