diff --git a/cmd/gol/gol.go b/cmd/gol/gol.go index 4c52030..de10e4e 100644 --- a/cmd/gol/gol.go +++ b/cmd/gol/gol.go @@ -3,6 +3,7 @@ package main import ( "flag" "log" + "math/rand" "os" "os/signal" "runtime/pprof" @@ -15,6 +16,7 @@ import ( func main() { cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file") + initrandom := flag.Bool("random", false, "initialize arena with random values") flag.Parse() // Jeśli podano flagę cpuprofile, rozpocznij profilowanie @@ -29,27 +31,39 @@ func main() { } defer pprof.StopCPUProfile() } - game() + game(*initrandom) } -func game() { +func initArena(front gol.Arena, initRandom bool) { + if initRandom { + for y := range front { + for x := range front[y] { + front[y][x] = rand.Intn(2) == 1 + } + } + } else { + // draw initial objects + // glider + front[0][3] = true + front[1][4] = true + front[2][2] = true + front[2][3] = true + front[2][4] = true + + // cross + front[16][21] = true + front[17][21] = true + front[18][21] = true + } +} + +func game(initrandom bool) { // arenas - front one is printed, then new state is calculated into the back one // next front and back are switched front := gol.New(20, 40) back := gol.New(20, 40) - // draw initial objects - // glider - front[0][3] = true - front[1][4] = true - front[2][2] = true - front[2][3] = true - front[2][4] = true - - // cross - front[16][21] = true - front[17][21] = true - front[18][21] = true + initArena(front, initrandom) // catch interrupt signals sigs := make(chan os.Signal, 1) diff --git a/gol/arena.go b/gol/arena.go index 9810e0b..5c16ddd 100644 --- a/gol/arena.go +++ b/gol/arena.go @@ -55,12 +55,6 @@ func (a Arena) NextGen(to Arena) { } func (a Arena) life(x, y int) bool { - neighbours := a.countNeighbours(x, y) - iAmAlive := a[y][x] - return neighbours == 3 || (iAmAlive && neighbours == 2) -} - -func (a Arena) countNeighbours(x, y int) int { ysize := len(a) xsize := len(a[0]) @@ -75,7 +69,11 @@ func (a Arena) countNeighbours(x, y int) int { if a[ny][nx] { count++ } + if count > 3 { + return false // early exit + } } } - return count + iAmAlive := a[y][x] + return count == 3 || (iAmAlive && count == 2) }