From 70600a1142dcc56da960f05b92131d6e9847fb59 Mon Sep 17 00:00:00 2001 From: Luke Meyers Date: Sat, 8 Feb 2020 20:39:10 -0800 Subject: [PATCH] run AI in separate goroutine --- game/ai.go | 2 +- game/commands.go | 15 ++++++++++++++- main.go | 13 ++++++------- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/game/ai.go b/game/ai.go index e5012eb..79eb921 100644 --- a/game/ai.go +++ b/game/ai.go @@ -1,6 +1,6 @@ package game -func ChooseCommand(s State, teamID int) Command { +func chooseCommand(s State, teamID int) Command { return chooseCommandHelper(s, teamID, aiDepth) } diff --git a/game/commands.go b/game/commands.go index cfdc675..ff36416 100644 --- a/game/commands.go +++ b/game/commands.go @@ -1,5 +1,9 @@ package game +import ( + "log" +) + type Command int const ( @@ -12,9 +16,18 @@ const ( var validCommands = []Command{speedUp, slowDown, left, right, clearObstacle} +func PollCommands(s State) []Command { + cmds := make([]Command, len(s.Teams)) + for i := range s.Teams { + cmd := chooseCommand(s, i) + log.Printf("team %d chose to %v", i, cmd) + cmds[i] = cmd + } + return cmds +} + func doCommand(cmd Command, s State, teamID int) State { da := 1 - //da += rand.Intn(3) - 1 r := ActiveRacer(s.Teams[teamID]) if r == nil { diff --git a/main.go b/main.go index ba8b85f..a82cae6 100644 --- a/main.go +++ b/main.go @@ -44,6 +44,9 @@ func run() error { second = time.Tick(time.Second) ) + cmdC := make(chan []game.Command) + go func() { cmdC <- game.PollCommands(s) }() + for !w.Closed() && !s.GameOver { switch { case w.Pressed(pixelgl.KeyQ): @@ -58,13 +61,7 @@ func run() error { rs.Animating = true rs.Frame = 0 - cmds := make([]game.Command, len(s.Teams)) - for i := range s.Teams { - cmd := game.ChooseCommand(s, i) - log.Printf("team %d chose to %v", i, cmd) - cmds[i] = cmd - } - + cmds := <-cmdC s = game.UpdateState(s, sOld, cmds) turn++ if s.GameOver { @@ -72,10 +69,12 @@ func run() error { sOld = s turn = 1 } + go func() { cmdC <- game.PollCommands(s) }() } w.Update() frames++ + select { case <-second: w.SetTitle(fmt.Sprintf("%s | FPS: %d", cfg.Title, frames))