1
0
Fork 0

refactor: move ui code from game/state/handlers/menu.go to its own package in game/ui

This commit is contained in:
Henrik Hautakoski 2025-10-19 11:36:12 +02:00
parent 190c6ad914
commit bcd6025aa3
5 changed files with 118 additions and 45 deletions

33
game/ui/button.go Normal file
View file

@ -0,0 +1,33 @@
package ui
import (
"tetris/engine/render"
rl "github.com/gen2brain/raylib-go/raylib"
)
type Button struct {
Text string
Action func()
}
func NewButton(text string, action func()) Button {
return Button{
Text: text,
Action: action,
}
}
func (b Button) HandleInput() {
if rl.IsKeyPressed(rl.KeyEnter) {
b.Action()
}
}
func (b Button) Draw(x, y int32, selected bool) {
col := rl.White
if selected {
col = rl.Red
}
render.DrawTextCenter(x, y, 32, b.Text, col)
}

59
game/ui/menu.go Normal file
View file

@ -0,0 +1,59 @@
package ui
import (
"tetris/assets"
"tetris/engine/audio"
rl "github.com/gen2brain/raylib-go/raylib"
)
type Menu struct {
selected int
entries []Widget
}
func NewMenu(entries []Widget) Menu {
return Menu{
entries: entries,
}
}
func (menu Menu) Entries() []Widget {
return menu.entries
}
func (menu *Menu) Select(index int) {
menu.selected = min(index, len(menu.entries)-1)
}
func (menu Menu) Selected() Widget {
return menu.entries[menu.selected]
}
func (menu Menu) IsSelected(index int) bool {
return menu.selected == index
}
func (menu *Menu) Next() {
if menu.selected+1 < len(menu.entries) {
menu.selected = menu.selected + 1
audio.Play(assets.SFX_MENU_SELECT)
}
}
func (menu *Menu) Previous() {
if menu.selected-1 >= 0 {
menu.selected = menu.selected - 1
audio.Play(assets.SFX_MENU_SELECT)
}
}
func (menu *Menu) HandleInput() {
if rl.IsKeyPressed(rl.KeyDown) {
menu.Next()
} else if rl.IsKeyPressed(rl.KeyUp) {
menu.Previous()
} else {
menu.Selected().HandleInput()
}
}

6
game/ui/widget.go Normal file
View file

@ -0,0 +1,6 @@
package ui
type Widget interface {
HandleInput()
Draw(x, y int32, selected bool)
}