Skip to content

Commit b3b47f6

Browse files
committed
Add loop context
1 parent f7909ed commit b3b47f6

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

gopher-maze-2/cmd/maze/main.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
package main
22

33
import (
4+
"context"
45
"runtime"
56

67
"github.com/necrophonic/3d-gopher-maze/gopher-maze-2/internal/game"
78
)
89

910
func main() {
11+
ctx := context.Background()
12+
1013
g := game.New(true)
1114

1215
// Start rendering loop
13-
go g.Loop()
16+
go g.Loop(ctx)
1417

1518
// Start player input loop
1619
go g.Player.Loop()

gopher-maze-2/internal/game/game.go

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package game
22

33
import (
4+
"context"
45
"fmt"
6+
"log"
57
"os"
68
"time"
79

@@ -42,23 +44,30 @@ func New(debug bool) *Game {
4244
}
4345
}
4446

47+
var a string
48+
4549
// Loop is the main game loop. It is designed
4650
// to be called as a goroutine
47-
func (g *Game) Loop() {
51+
func (g *Game) Loop(ctx context.Context) {
4852
ds.Add("Game loop started")
4953
ticker := time.NewTicker(g.Tick)
5054
defer ticker.Stop()
51-
for range ticker.C {
52-
// Refresh the terminal before
53-
// calling render to build the view.
54-
terminal.Clear()
55-
rendered, err := g.Render()
56-
if err != nil {
57-
// TODO better error handling
58-
fmt.Println("Error:", err)
59-
os.Exit(1)
55+
for {
56+
select {
57+
case <-ctx.Done():
58+
log.Println("Main game loop closing")
59+
return
60+
case <-ticker.C:
61+
// Refresh the terminal before
62+
// calling render to build the view.
63+
terminal.Clear()
64+
rendered, err := g.Render()
65+
if err != nil {
66+
// TODO better error handling
67+
fmt.Println("Error:", err)
68+
os.Exit(1)
69+
}
70+
fmt.Println(rendered)
6071
}
61-
fmt.Println(rendered)
62-
// time.Sleep(g.Tick)
6372
}
6473
}

0 commit comments

Comments
 (0)