Moving bulk of console runner into library func
This commit is contained in:
parent
6bbe19c26f
commit
270eb1fc2d
@ -4,7 +4,6 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
import (
|
||||
@ -22,37 +21,10 @@ var (
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
game := NewGameOfLife(*height, *width)
|
||||
err := game.ImportRandomState()
|
||||
retCode, err := RunConsoleGame(*height, *width, *sleepMs, *mutate)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "WHAT IN FAIL?: %v\n", err)
|
||||
os.Exit(2)
|
||||
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
||||
}
|
||||
|
||||
genTicks, err := game.Generations()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "No generations?: %v\n", err)
|
||||
os.Exit(3)
|
||||
}
|
||||
|
||||
sleepInterval := time.Duration(*sleepMs * 1000 * 1000)
|
||||
for genTick := range genTicks {
|
||||
fmt.Printf("\nGeneration %v\n%v\n", genTick.N, time.Now())
|
||||
fmt.Println(game)
|
||||
|
||||
if genTick.Error != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", genTick.Message, genTick.Error)
|
||||
os.Exit(4)
|
||||
}
|
||||
|
||||
if len(genTick.Message) > 0 {
|
||||
fmt.Println(genTick.Message)
|
||||
}
|
||||
|
||||
if *mutate && genTick.N%2 == 0 {
|
||||
game.Mutate()
|
||||
}
|
||||
|
||||
time.Sleep(sleepInterval)
|
||||
}
|
||||
os.Exit(retCode)
|
||||
}
|
||||
|
@ -15,6 +15,42 @@ type GameOfLife struct {
|
||||
State *GameState
|
||||
}
|
||||
|
||||
func RunConsoleGame(height, width, sleepMs int, mutate bool) (int, error) {
|
||||
sleepInterval := time.Duration(sleepMs * 1000 * 1000)
|
||||
|
||||
game := NewGameOfLife(height, width)
|
||||
err := game.ImportRandomState()
|
||||
if err != nil {
|
||||
return 2, err
|
||||
}
|
||||
|
||||
genTicks, err := game.Generations()
|
||||
if err != nil {
|
||||
return 3, err
|
||||
}
|
||||
|
||||
for genTick := range genTicks {
|
||||
fmt.Printf("\nGeneration %v\n%v\n", genTick.N, time.Now())
|
||||
fmt.Println(game)
|
||||
|
||||
if genTick.Error != nil {
|
||||
return 4, genTick.Error
|
||||
}
|
||||
|
||||
if len(genTick.Message) > 0 {
|
||||
fmt.Println(genTick.Message)
|
||||
}
|
||||
|
||||
if mutate && genTick.N%2 == 0 {
|
||||
game.Mutate()
|
||||
}
|
||||
|
||||
time.Sleep(sleepInterval)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (game *GameOfLife) Mutate() error {
|
||||
return game.State.Mutate()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user