Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Game of Life
package main
import (
"bytes"
"fmt"
"math/rand"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
func createBoard(height int, width int, living int) [][]string {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
board := make([][]string, height)
for y := range board {
for i := 0; i < width; i++ {
if random.Intn(100) < living {
board[y] = append(board[y], alive)
} else {
board[y] = append(board[y], dead)
}
}
}
return board
}
func printBoard(board [][]string) {
var buffer bytes.Buffer
for _, row := range board {
for _, cell := range row {
buffer.WriteString(cell)
}
buffer.WriteString("\n")
}
fmt.Println(buffer.String())
}
func countLivingNeighbours(x int, y int, board [][]string) int {
liveCount := 0
for i := y - 1; i <= y+1; i++ {
for j := x - 1; j <= x+1; j++ {
if i == y && j == x {
continue
} else if i >= 0 && i < len(board) && j >= 0 && j < len(board[0]) {
if board[i][j] == alive {
liveCount++
}
}
}
}
return liveCount
}
func tick(board [][]string) [][]string {
newBoard := make([][]string, len(board))
for i := range board {
for j, cell := range board[i] {
count := countLivingNeighbours(j, i, board)
if cell == alive {
switch {
case count < 2:
newBoard[i] = append(newBoard[i], dead)
case count >= 2 && count <= 3:
newBoard[i] = append(newBoard[i], alive)
case count > 3:
newBoard[i] = append(newBoard[i], dead)
}
} else if cell == dead {
if count == 3 {
newBoard[i] = append(newBoard[i], alive)
} else {
newBoard[i] = append(newBoard[i], dead)
}
}
}
}
return newBoard
}
func determineBoardSize() []int {
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
out, _ := cmd.Output()
dims := strings.Split(strings.Trim(string(out), "\n"), " ")
height, width := dims[0], dims[1]
heightInt, _ := strconv.Atoi(height)
widthInt, _ := strconv.Atoi(width)
return []int{heightInt, widthInt}
}
const alive string = "█"
const dead string = " "
const delay time.Duration = 30 * time.Millisecond
const initialPopulationPercentage int = 20
func main() {
boardSize := determineBoardSize()
board := createBoard(boardSize[0], boardSize[1], initialPopulationPercentage)
for {
print("\033[H\033[2J")
board = tick(board)
printBoard(board)
time.Sleep(delay)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment