From 06e44045ac78fa51cf98542a9a7d774022c3a1a2 Mon Sep 17 00:00:00 2001 From: Shanti Chellaram Date: Sat, 15 Mar 2025 23:32:55 +0900 Subject: [PATCH] Add initial "event loop" and scene Start with the main menu with only one option, and build the abstractions between the event loop and what the scene itself handles. --- lib/lib.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/lib/lib.go b/lib/lib.go index 80dc8eb..12391be 100644 --- a/lib/lib.go +++ b/lib/lib.go @@ -1,22 +1,98 @@ package lib -import "github.com/hajimehoshi/ebiten/v2" +import ( + "github.com/hajimehoshi/ebiten/v2" + "github.com/hajimehoshi/ebiten/v2/ebitenutil" + "github.com/hajimehoshi/ebiten/v2/inpututil" +) + +// Scenes: Main Menu +// Game Mode + +//Scene - is the highest-level element of state the game can be in. + +type GameEvent struct { + Type int +} + +type HandleResult int + +const ( + EventNoOp int = iota + EventKeyRelease +) + +const ( + DoNothing HandleResult = iota + EndProgram +) + +type Scene interface { + HandleEvent(*GameEvent) HandleResult + Draw(screen *ebiten.Image) +} // Implements ebiten.Game type TetrisGame struct { + activeScene Scene +} + +type MainMenuScene struct { + selections [1]string + currentSelectionIndex int +} + +func (menu *MainMenuScene) HandleEvent(e *GameEvent) HandleResult { + if e.Type == 1 { + if menu.selections[menu.currentSelectionIndex] == "Quit" { + return EndProgram + } + } + return DoNothing +} + +func (menu *MainMenuScene) Draw(screen *ebiten.Image) { + ebitenutil.DebugPrint(screen, menu.selections[menu.currentSelectionIndex]) } func NewGame() (*TetrisGame, error) { - return &TetrisGame{}, nil + return &TetrisGame{ + activeScene: &MainMenuScene{ + selections: [1]string{"Quit"}, + currentSelectionIndex: 0, + }, + }, nil } func (g *TetrisGame) Layout(outsideWidth, outsideHeight int) (int, int) { + //TODO: Make this do whatever it is supposed to do : resizing etc return 640, 480 } func (g *TetrisGame) Update() error { + //while there are events + + var keys []ebiten.Key + keys = inpututil.AppendJustReleasedKeys(keys) + + var event GameEvent + if len(keys) > 0 { + event = GameEvent{Type: EventKeyRelease} + } else { + event = GameEvent{Type: EventNoOp} + } + + switch g.activeScene.HandleEvent(&event) { + case EndProgram: + return ebiten.Termination + case DoNothing: + return nil + default: + return nil + } return nil } func (g *TetrisGame) Draw(screen *ebiten.Image) { + g.activeScene.Draw(screen) }