猿问

如何同时打印和扫描

我正在编写一个简单的贪吃蛇游戏。


这将是非常基本的,但我现在被困住了。我使用“wsad”来引导蛇,但在原始游戏中,即使我们没有改变它的方向,蛇也会移动。我的代码等待我输入一个字母,然后蛇就会移动。所以这是我测试如何弄清楚的示例,但我无法得到结果。


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

    }


}

即使我们没有按下任何键,我如何管理此代码以打印“snake is moving”?


动漫人物
浏览 91回答 1
1回答

jeck猫

您的代码明确同步它们:for {&nbsp; &nbsp; go takeLetter(s)&nbsp; &nbsp; go Print(c)&nbsp; &nbsp; <-s&nbsp; &nbsp; <-c}该循环的每次迭代,每个函数都将执行一次,并且它将等待再次执行循环,直到两者都完成(这就是您对通道所做的)。您可能想要的是对每个函数运行一次,并让每个循环独立运行:func takeLetter() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; char, _, err := keyboard.GetSingleKey()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%c", char)&nbsp; &nbsp; }}func Print() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("snake is moving")&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; &nbsp; &nbsp; go takeLetter()&nbsp; &nbsp; &nbsp; &nbsp; go Print()&nbsp; &nbsp; &nbsp; &nbsp; select {} // keep main from exiting immediately}
随时随地看视频慕课网APP

相关分类

Go
我要回答