run AI in separate goroutine

This commit is contained in:
Luke Meyers 2020-02-08 20:39:10 -08:00
parent 0cb604f102
commit 70600a1142
3 changed files with 21 additions and 9 deletions

View File

@ -1,6 +1,6 @@
package game package game
func ChooseCommand(s State, teamID int) Command { func chooseCommand(s State, teamID int) Command {
return chooseCommandHelper(s, teamID, aiDepth) return chooseCommandHelper(s, teamID, aiDepth)
} }

View File

@ -1,5 +1,9 @@
package game package game
import (
"log"
)
type Command int type Command int
const ( const (
@ -12,9 +16,18 @@ const (
var validCommands = []Command{speedUp, slowDown, left, right, clearObstacle} 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 { func doCommand(cmd Command, s State, teamID int) State {
da := 1 da := 1
//da += rand.Intn(3) - 1
r := ActiveRacer(s.Teams[teamID]) r := ActiveRacer(s.Teams[teamID])
if r == nil { if r == nil {

13
main.go
View File

@ -44,6 +44,9 @@ func run() error {
second = time.Tick(time.Second) second = time.Tick(time.Second)
) )
cmdC := make(chan []game.Command)
go func() { cmdC <- game.PollCommands(s) }()
for !w.Closed() && !s.GameOver { for !w.Closed() && !s.GameOver {
switch { switch {
case w.Pressed(pixelgl.KeyQ): case w.Pressed(pixelgl.KeyQ):
@ -58,13 +61,7 @@ func run() error {
rs.Animating = true rs.Animating = true
rs.Frame = 0 rs.Frame = 0
cmds := make([]game.Command, len(s.Teams)) cmds := <-cmdC
for i := range s.Teams {
cmd := game.ChooseCommand(s, i)
log.Printf("team %d chose to %v", i, cmd)
cmds[i] = cmd
}
s = game.UpdateState(s, sOld, cmds) s = game.UpdateState(s, sOld, cmds)
turn++ turn++
if s.GameOver { if s.GameOver {
@ -72,10 +69,12 @@ func run() error {
sOld = s sOld = s
turn = 1 turn = 1
} }
go func() { cmdC <- game.PollCommands(s) }()
} }
w.Update() w.Update()
frames++ frames++
select { select {
case <-second: case <-second:
w.SetTitle(fmt.Sprintf("%s | FPS: %d", cfg.Title, frames)) w.SetTitle(fmt.Sprintf("%s | FPS: %d", cfg.Title, frames))