Last active
October 13, 2020 06:20
-
-
Save syhily/eae432dc4c8fba1836a4b892ab472ab8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
const ( | |
width = 80 | |
height = 15 | |
) | |
type Universe [][]bool | |
func NewUniverse() (result Universe) { | |
result = make([][]bool, height) | |
for i, _ := range result { | |
result[i] = make([]bool, width) | |
} | |
return | |
} | |
func (u Universe) Seed() { | |
// Seed approximately 25% of each row | |
var count int = width / 4 | |
for i := range u { | |
for j := 0; j <= count; j++ { | |
u[i][rand.Intn(width)] = true | |
} | |
} | |
} | |
func (u Universe) Show() { | |
for _, row := range u { | |
for _, alive := range row { | |
if alive { | |
fmt.Print("*") | |
} else { | |
fmt.Print(" ") | |
} | |
} | |
fmt.Println() | |
} | |
} | |
func (u Universe) Alive(x, y int) bool { | |
// x part | |
for x < 0 { | |
x += width | |
} | |
if x >= width { | |
x = x % width | |
} | |
// y part | |
for y < 0 { | |
y += height | |
} | |
if y >= height { | |
y = y % height | |
} | |
return u[y][x] | |
} | |
func (u Universe) Neighbors(x, y int) (count int) { | |
for i := x - 1; i < x + 2; i++ { | |
for j := y - 1; j < y + 2; j++ { | |
if (i != x || j != y) && u.Alive(i, j) { | |
count++ | |
} | |
} | |
} | |
return | |
} | |
func (u Universe) Next(x, y int) bool { | |
neighbors := u.Neighbors(x, y) | |
if u.Alive(x, y) { | |
return neighbors == 3 || neighbors == 2 | |
} else { | |
return neighbors == 3 | |
} | |
} | |
func Step(a, b Universe) { | |
for i, row := range a { | |
for j, _ := range row { | |
b[i][j] = a.Next(j, i) | |
} | |
} | |
} | |
func main() { | |
u := NewUniverse() | |
u.Seed() | |
m := NewUniverse() | |
for { | |
fmt.Println("\033[H") | |
u.Show() | |
Step(u, m) | |
u, m = m, u | |
time.Sleep(1 * time.Second / 10) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment