Skip to content

Instantly share code, notes, and snippets.

@thara
Last active June 30, 2020 07:30
Show Gist options
  • Save thara/56db7d191920c85fbf2e6f373736e192 to your computer and use it in GitHub Desktop.
Save thara/56db7d191920c85fbf2e6f373736e192 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Go
package main
import (
"fmt"
"time"
)
type Point struct {
x int
y int
}
func (p *Point) neighbors() []Point {
return []Point{
{p.x - 1, p.y - 1},
{p.x - 1, p.y},
{p.x - 1, p.y + 1},
{p.x, p.y - 1},
{p.x, p.y + 1},
{p.x + 1, p.y - 1},
{p.x + 1, p.y},
{p.x + 1, p.y + 1},
}
}
func (p *Point) isLiving(s State) bool {
count := 0
for _, n := range p.neighbors() {
if _, ok := s[n]; ok {
count += 1
}
}
if count == 3 {
return true
}
if count == 2 {
if _, ok := s[*p]; ok {
return true
}
}
return false
}
type State = map[Point]bool
const width = 10
const height = 10
func Advance(s State) State {
recalc := State{}
for p := range s {
for _, n := range p.neighbors() {
recalc[n] = true
}
recalc[p] = true
}
for p := range recalc {
if !p.isLiving(s) {
delete(recalc, p)
}
}
return recalc
}
func Print(s State) {
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
p := Point{x: x, y: y}
if _, ok := s[p]; ok {
fmt.Printf("*")
} else {
fmt.Printf("-")
}
}
fmt.Println()
}
}
func main() {
s := map[Point]bool{
{0, 1}: true,
{1, 2}: true,
{2, 0}: true,
{2, 1}: true,
{2, 2}: true,
}
Print(s)
for {
time.Sleep(500 * time.Millisecond)
fmt.Printf("\033[%vA\r", height)
s = Advance(s)
Print(s)
}
}
@HannahWVP
Copy link

HannahWVP commented Jun 29, 2020

Oh very interesting thank you for your work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment