Last active
December 5, 2019 05:29
-
-
Save adamgoose/e71682aa69faf94225a3e21d314478ba to your computer and use it in GitHub Desktop.
Game of Life
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" | |
) | |
// Board represents the game board | |
type Board struct { | |
b [][]bool | |
} | |
// NewBoard instantiates a new board with a given height and width | |
func NewBoard(h, w int) *Board { | |
b := &Board{} | |
for x := 0; x < w; x++ { | |
b.b = append(b.b, []bool{}) | |
for y := 0; y < h; y++ { | |
b.b[x] = append(b.b[x], rand.Intn(2) == 0) | |
} | |
} | |
return b | |
} | |
// Print outputs a copy of the board to the terminal. | |
func (b Board) Print() { | |
fmt.Printf("\033[0;0H") | |
fmt.Print("\nBoard:") | |
for _, col := range b.b { | |
fmt.Print("\n") | |
for _, val := range col { | |
s := "◻️" | |
if val { | |
s = "◼️" | |
} | |
fmt.Printf("%s ", s) | |
} | |
} | |
} | |
// DoGen processes a single generation | |
func (b *Board) DoGen() { | |
for x, col := range b.b { | |
for y, val := range col { | |
neighbors := b.Neighbors(x, y) | |
switch true { | |
case val && neighbors < 2: | |
b.b[x][y] = false | |
break | |
case val && (neighbors == 2 || neighbors == 3): | |
b.b[x][y] = true | |
break | |
case val && neighbors > 3: | |
b.b[x][y] = false | |
break | |
case !val && neighbors == 3: | |
b.b[x][y] = true | |
break | |
} | |
} | |
} | |
} | |
// Neighbors counts all active neighbors | |
func (b Board) Neighbors(x, y int) (n int) { | |
coords := [][]int{ | |
// row above | |
{x - 1, y - 1}, | |
{x + 0, y - 1}, | |
{x + 1, y - 1}, | |
// self row | |
{x - 1, y + 0}, | |
{x + 1, y + 0}, | |
// row below | |
{x - 1, y + 1}, | |
{x + 0, y + 1}, | |
{x + 1, y + 1}, | |
} | |
for _, c := range coords { | |
if c[0] < 0 || c[0] >= len(b.b) { | |
continue | |
} | |
if c[1] < 0 || c[1] >= len(b.b[0]) { | |
continue | |
} | |
if b.b[c[0]][c[1]] { | |
n++ | |
} | |
} | |
return | |
} | |
func main() { | |
b := NewBoard(16, 8) | |
b.Print() | |
for { | |
time.Sleep(time.Second / 5) | |
b.DoGen() | |
b.Print() | |
} | |
} | |
func init() { | |
rand.Seed(time.Now().Unix()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment