Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions _examples/stop/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

import (
"github.com/elgopher/pi/piebiten"
"github.com/elgopher/pi/pikey"
"github.com/elgopher/pi/piloop"
)

func main() {
// stops the game loop when user pressed Escape key
pikey.RegisterShortcut(piloop.Stop, pikey.Esc)

piebiten.Run() // this function ends without panic once game loop is stopped

// Code in here is executed after loop is stopped
}
15 changes: 13 additions & 2 deletions piebiten/internal/ebitengame.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
package internal

import (
"math"
"time"

"github.com/elgopher/pi/piaudio"
"github.com/elgopher/pi/piebiten/internal/audio"
"github.com/elgopher/pi/piebiten/internal/input"
ebitenaudio "github.com/hajimehoshi/ebiten/v2/audio"
"math"
"time"

"github.com/hajimehoshi/ebiten/v2"

Expand Down Expand Up @@ -40,6 +41,7 @@ func RunEbitenGame() *EbitenGame {
}

pidebug.Target().SubscribeAll(game.onPidebugEvent)
piloop.Target().Subscribe(piloop.EventStop, game.onPiloopStopEvent)

return game
}
Expand Down Expand Up @@ -87,9 +89,14 @@ type EbitenGame struct {
inputBackend *input.Backend

ebitenFrame int // frame incremented on each Ebiten tick

stopped bool
}

func (g *EbitenGame) Update() error {
if g.stopped {
return ebiten.Termination
}
if ebiten.IsWindowBeingClosed() {
piloop.Target().Publish(piloop.EventWindowClose)
return ebiten.Termination
Expand Down Expand Up @@ -217,3 +224,7 @@ func (g *EbitenGame) onPidebugEvent(event pidebug.Event, _ pievent.Handler) {
g.paused = false
}
}

func (g *EbitenGame) onPiloopStopEvent(piloop.Event, pievent.Handler) {
g.stopped = true
}
1 change: 1 addition & 0 deletions piloop/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ const (
EventDraw Event = "draw" // after pi.Draw
EventLateDraw Event = "late_draw" // after EventDraw
EventWindowClose Event = "window_close" // when a user closes the window (desktop only)
EventStop Event = "stop" // when game loop is stopped by calling piloop.Stop()
)
4 changes: 4 additions & 0 deletions piloop/piloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ func DebugTarget() pievent.Target[Event] {
return debugTarget
}

func Stop() {
Target().Publish(EventStop)
}

var (
target = pievent.NewTarget[Event]()
debugTarget = pievent.NewTarget[Event]()
Expand Down
Loading