1

I am attempting to write a horse race simulator with multiple rows. Each row will represent one horse location calculated by a goroutine.

For some reason the code, when run on the Go Playground, does not output the numbers randomly as happens on my machine.

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)
    }
}

Playground: https://play.golang.org/p/pycZ4EdH7SQ

My output unordered is:

[1][5][8][2][3][4][7][9][6][7][9][9][4][3]...

But my question is how would I go about to print the numbers like:

[1][1]
[2][2][2][2][2][2][2][2]
[3][3][3]
...
[N][N][N][N][N]
peterSO
  • 158,998
  • 31
  • 281
  • 276
pigfox
  • 1,301
  • 3
  • 28
  • 52
  • 2
    It's terminal emulator specific, not really a Go programming question. – zerkms Apr 08 '19 at 04:57
  • 3
    you would need to clear & rewrite if you want to append to a previously written line. – ifnotak Apr 08 '19 at 06:32
  • 2
    Regarding the random order, the rand.Seed(...) is intended to be called once, with a non constant value. Typically the current time is suitable as the time advances on most environments, but the playground always starts at the same moment in time (so it is always predictable). Move rand.Seed(..) to the top of main(). – Mark Apr 08 '19 at 06:52

1 Answers1

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.

Lucat
  • 2,242
  • 1
  • 30
  • 41