-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.go
64 lines (50 loc) · 1.61 KB
/
game.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import "github.com/qjuanp/gameoflife/board"
type GameOfLife struct {
board.Board
}
const ALIVE bool = true
const DEAD bool = false
func NewGameOfSize(rows uint, columns uint) GameOfLife {
return GameOfLife{board.NewRandomBoard(rows, columns, 1)}
}
func (game *GameOfLife) next() GameOfLife {
newBoardState := board.NewEmptyBoardAsBigAs(&game.Board)
for rowIndex, row := range game.Board {
for columnIndex, cell := range row {
aliveNeighbors := game.checkAliveNeighboars(rowIndex, columnIndex)
newBoardState[rowIndex][columnIndex] = newCellState(cell, aliveNeighbors)
}
}
return GameOfLife{newBoardState}
}
func (game *GameOfLife) checkAliveNeighboars(rowIdx int, columnIdx int) uint8 {
var aliveNeighbors uint8 = 0
for row, hasNextRow, currentRowIndex, itRows := game.Board.IterateNeighborsOfRow(rowIdx); hasNextRow; row, hasNextRow, currentRowIndex = itRows() {
for cell, hasNextColumns, currentColumnIndex, itColumns := game.Board.IterateNightborsOf(row, columnIdx); hasNextColumns; cell, hasNextColumns, currentColumnIndex = itColumns() {
if (rowIdx != currentRowIndex || columnIdx != currentColumnIndex) && cell == ALIVE {
aliveNeighbors++
}
}
}
return aliveNeighbors
}
func newCellState(cell bool, quantityOfAliveNeighbors uint8) bool {
// Overpopulation
if quantityOfAliveNeighbors > 3 {
return DEAD
}
// Revive
if quantityOfAliveNeighbors == 3 {
return ALIVE
}
// Right conditions
if cell == ALIVE && quantityOfAliveNeighbors >= 2 && quantityOfAliveNeighbors <= 3 {
return ALIVE
}
if quantityOfAliveNeighbors <= 1 {
return DEAD
}
// no rule applied
return cell
}