我正在尝试编写具有多行的赛马模拟器。 每行将代表一个goroutine计算出的一匹马的位置。
由于某种原因,该代码在Go Playground上运行时不会像我的计算机上那样随机输出数字。
package main
import (
"math/rand"
"os"
"strconv"
"time"
)
var counter = 0
func main() {
i := 1
horses := 9
for i <= horses {
go run(i)
i++
}
time.Sleep(5000 * time.Millisecond)
print("\ncounter: " + strconv.Itoa(counter))
print("\nEnd of main()")
}
func run(number int) {
var i = 1
var steps = 5
for i <= steps {
print("[" + strconv.Itoa(number) + "]")
rand.Seed(time.Now().UnixNano())
sleep := rand.Intn(10)
time.Sleep(time.Duration(sleep) * time.Millisecond)
i++
counter++
}
if i == steps {
println(strconv.Itoa(number) + " wins")
os.Exit(1)
}
}
游乐场:https://play.golang.org/p/pycZ4EdH7SQ
我的无序输出是:
[1][5][8][2][3][4][7][9][6][7][9][9][4][3]...
但是我的问题是我将如何打印以下数字:
[1][1]
[2][2][2][2][2][2][2][2]
[3][3][3]
...
[N][N][N][N][N]
答案 0 :(得分:1)
you may want to check out this stackoverflow answer which uses goterm to move the terminal cursor and allow you to overwrite part of it.
The idea is that once you get to the terminal bit you want to be "dynamic" (much like a videogame screen clear+redraw), you always reposition the cursor and "draw" your "horses" position.
Note that with this you will need to store their positions somewhere, to then "draw" their positions at each "frame".
With this exercise you are getting close to how video games work, and for this you may want to set up a goroutine with a given refresh rate to clear your terminal and render what you want.