Skip to content

Instantly share code, notes, and snippets.

@tomcha
Created May 21, 2020 01:34
Show Gist options
  • Save tomcha/470a08773e87c593a4ef538fcecc4413 to your computer and use it in GitHub Desktop.
Save tomcha/470a08773e87c593a4ef538fcecc4413 to your computer and use it in GitHub Desktop.
lifegame
package main
import (
"fmt"
"math/rand"
"time"
)
const (
clear = "\033[2J"
head = "\033[1;1H"
areaX = 30
areaY = 30
loopCnt = 100
)
var sc1 [areaX + 2][areaY + 2]int
var sc2 [areaX + 2][areaY + 2]int
var str string
func initialize() {
rand.Seed(time.Now().UnixNano())
for x := 1; x < areaX+1; x++ {
for y := 1; y < areaY+1; y++ {
sc1[x][y] = rand.Intn(2)
}
}
}
func lifeChange() {
for x := 1; x < areaX+1; x++ {
for y := 1; y < areaY+1; y++ {
lifeEnv := sc1[x-1][y-1] + sc1[x-1][y] + sc1[x-1][y+1] + sc1[x][y-1] + sc1[x][y+1] + sc1[x+1][y-1] + sc1[x+1][y] + sc1[x+1][y+1]
if sc1[x][y] == 0 {
if lifeEnv == 3 {
sc2[x][y] = 1
} else {
sc2[x][y] = 0
}
} else {
if lifeEnv <= 1 {
sc2[x][y] = 0
} else if lifeEnv <= 3 {
sc2[x][y] = 1
} else {
sc2[x][y] = 0
}
}
}
}
sc1 = sc2
}
func drawView() {
fmt.Print(clear)
fmt.Print(head)
for y := 1; y <= areaY; y++ {
for x := 1; x <= areaX; x++ {
if sc1[x][y] == 0 {
str = " "
} else {
str = "O"
}
fmt.Print(str)
}
fmt.Println()
}
}
func main() {
initialize()
drawView()
for i := 0; i < loopCnt; i++ {
lifeChange()
drawView()
time.Sleep(10 * time.Millisecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment