Skip to content

Commit 135c07b

Browse files
committed
Add piloop.Stop() function
This function can be used to stop the game loop.
1 parent 00f550e commit 135c07b

4 files changed

Lines changed: 31 additions & 2 deletions

File tree

_examples/stop/main.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package main
2+
3+
import (
4+
"github.com/elgopher/pi/piebiten"
5+
"github.com/elgopher/pi/pikey"
6+
"github.com/elgopher/pi/piloop"
7+
)
8+
9+
func main() {
10+
pikey.RegisterShortcut(piloop.Stop, pikey.Esc)
11+
12+
piebiten.Run()
13+
}

piebiten/internal/ebitengame.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44
package internal
55

66
import (
7+
"math"
8+
"time"
9+
710
"github.com/elgopher/pi/piaudio"
811
"github.com/elgopher/pi/piebiten/internal/audio"
912
"github.com/elgopher/pi/piebiten/internal/input"
1013
ebitenaudio "github.com/hajimehoshi/ebiten/v2/audio"
11-
"math"
12-
"time"
1314

1415
"github.com/hajimehoshi/ebiten/v2"
1516

@@ -40,6 +41,7 @@ func RunEbitenGame() *EbitenGame {
4041
}
4142

4243
pidebug.Target().SubscribeAll(game.onPidebugEvent)
44+
piloop.Target().Subscribe(piloop.EventStop, game.onPiloopStopEvent)
4345

4446
return game
4547
}
@@ -87,9 +89,14 @@ type EbitenGame struct {
8789
inputBackend *input.Backend
8890

8991
ebitenFrame int // frame incremented on each Ebiten tick
92+
93+
stopped bool
9094
}
9195

9296
func (g *EbitenGame) Update() error {
97+
if g.stopped {
98+
return ebiten.Termination
99+
}
93100
if ebiten.IsWindowBeingClosed() {
94101
piloop.Target().Publish(piloop.EventWindowClose)
95102
return ebiten.Termination
@@ -217,3 +224,7 @@ func (g *EbitenGame) onPidebugEvent(event pidebug.Event, _ pievent.Handler) {
217224
g.paused = false
218225
}
219226
}
227+
228+
func (g *EbitenGame) onPiloopStopEvent(piloop.Event, pievent.Handler) {
229+
g.stopped = true
230+
}

piloop/event.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ const (
1313
EventDraw Event = "draw" // after pi.Draw
1414
EventLateDraw Event = "late_draw" // after EventDraw
1515
EventWindowClose Event = "window_close" // when a user closes the window (desktop only)
16+
EventStop Event = "stop" // when game loop is stopped by calling piloop.Stop()
1617
)

piloop/piloop.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ func DebugTarget() pievent.Target[Event] {
1717
return debugTarget
1818
}
1919

20+
func Stop() {
21+
Target().Publish(EventStop)
22+
}
23+
2024
var (
2125
target = pievent.NewTarget[Event]()
2226
debugTarget = pievent.NewTarget[Event]()

0 commit comments

Comments
 (0)