From 270eb1fc2da5976d2baf243ba550008a09f33f33 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 12 Dec 2012 21:33:53 -0500 Subject: [PATCH] Moving bulk of console runner into library func --- conway/conways-game-of-life/main.go | 34 +++------------------------ conway/game_of_life.go | 36 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 31 deletions(-) diff --git a/conway/conways-game-of-life/main.go b/conway/conways-game-of-life/main.go index 2c085d9..bc0bc01 100644 --- a/conway/conways-game-of-life/main.go +++ b/conway/conways-game-of-life/main.go @@ -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) } diff --git a/conway/game_of_life.go b/conway/game_of_life.go index e8cd891..ed35fd4 100644 --- a/conway/game_of_life.go +++ b/conway/game_of_life.go @@ -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() }