Skip to content

Instantly share code, notes, and snippets.

@Glyphack
Created May 29, 2023 14:59
Show Gist options
  • Save Glyphack/62a60cecb6b05253c692e8c7d4565072 to your computer and use it in GitHub Desktop.
Save Glyphack/62a60cecb6b05253c692e8c7d4565072 to your computer and use it in GitHub Desktop.
Game of life in go
package main
import "fmt"
type Cell struct {
x int
y int
state int
}
const (
DEAD = iota
ALIVE
)
func main() {
board := make([][]int, 9)
for i := range board {
board[i] = make([]int, 9)
}
board[0][0] = 1
board[0][1] = 1
board[0][2] = 1
board[1][0] = 1
board[1][1] = 1
board[1][2] = 1
board[2][0] = 1
board[2][1] = 1
board[2][2] = 1
iterations := 3
fmt.Println("Initial board:")
showBoard(board)
for i := 0; i < iterations; i++ {
calculateNextBoard(board)
}
fmt.Println("final board:")
showBoard(board)
}
func calculateNextBoard(board [][]int) {
var nextBoard [][]int
nextBoard = make([][]int, len(board))
for i := range board {
nextBoard[i] = make([]int, len(board[i]))
}
for i := range board {
for j := range board[i] {
cell := Cell{i, j, board[i][j]}
aliveNeighbours := getAliveNeighbours(cell, board)
nextBoard[i][j] = calculateNextState(cell, aliveNeighbours)
}
}
for i := range board {
for j := range board[i] {
board[i][j] = nextBoard[i][j]
}
}
}
func calculateNextState(cell Cell, aliveNeighbours int) int {
switch cell.state {
case ALIVE:
if aliveNeighbours >= 2 && aliveNeighbours <= 3 {
return ALIVE
}
case DEAD:
if aliveNeighbours == 3 {
return ALIVE
}
}
return DEAD
}
func getAliveNeighbours(cell Cell, board [][]int) int {
aliveNeighbours := 0
for i := cell.x - 1; i <= cell.x+1; i++ {
for j := cell.y - 1; j <= cell.y+1; j++ {
if i == cell.x && j == cell.y {
continue
}
if i >= 0 && i < len(board) && j >= 0 && j < len(board[i]) && board[i][j] == ALIVE {
aliveNeighbours++
}
}
}
// fmt.Printf("Alive neighbours for cell (%d, %d): %d \n", cell.x, cell.y, aliveNeighbours)
return aliveNeighbours
}
func showBoard(board [][]int) {
for i := range board {
for j := range board[i] {
fmt.Printf("%d ", board[i][j])
}
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment