I am coding a simple SNAKE game.
It will be very basic, but I am stuck now. I use "wsad" to steer the snake, but in original game snake moves even if we didn't changed its direction. My code waits for me to input a letter, then snakes move. So here's is the sample where I was testing how to figure it out, and I couldn't get the result.
package main
import (
"fmt"
"github.com/eiannone/keyboard"
"time"
)
func takeLetter(s chan bool) {
char, _, err := keyboard.GetSingleKey()
if err != nil {
panic(err)
}
fmt.Printf("%c", char)
s <- true
}
func Print(c chan bool) {
fmt.Println("snake is moving")
time.Sleep(1 * time.Second)
c <- true
}
func main() {
c := make(chan bool)
s := make(chan bool)
for {
go takeLetter(s)
go Print(c)
<-s
<-c
}
}
How can I manage this code to print "snake is moving" even if we didnt hit any key?
Your code is explicitly synchronizing them:
for {
go takeLetter(s)
go Print(c)
<-s
<-c
}
Each iteration of that loop, each function will be executed once, and it will wait to execute the loop again until both finish (that's what you're doing with your channels). What you likely want instead is to run each function once, and have each loop independently:
func takeLetter() {
for {
char, _, err := keyboard.GetSingleKey()
if err != nil {
panic(err)
}
fmt.Printf("%c", char)
}
}
func Print() {
for {
fmt.Println("snake is moving")
time.Sleep(1 * time.Second)
}
}
func main() {
go takeLetter()
go Print()
select {} // keep main from exiting immediately
}