You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
box-o-sand/conway/go/game_of_life.go

92 lines
1.6 KiB

package conway
import (
"errors"
)
type GameOfLife struct {
Height int
Width int
}
type GameGridRow struct {
Cols []int
}
type GameState struct {
Rows []*GameGridRow
}
func NewGameState(height, width int) *GameState {
state := &GameState{}
for i := 0; i < height; i++ {
row := &GameGridRow{}
for j := 0; j < width; j++ {
row.Cols = append(row.Cols, 0)
}
state.Rows = append(state.Rows, row)
}
return state
}
func (state *GameState) GetRow(y int) (*GameGridRow, error) {
if len(state.Rows) < y+1 {
return nil, errors.New("y coordinate is out of bounds!")
}
return state.Rows[y], nil
}
func (state *GameState) Set(x, y, value int) error {
row, err := state.GetRow(y)
if err != nil {
return err
}
if len(row.Cols) < x+1 {
return errors.New("x coordinate is out of bounds!")
}
row.Cols[x] = value
return nil
}
func (state *GameState) Get(x, y int) (int, error) {
row, err := state.GetRow(y)
if err != nil {
return -1, err
}
if len(row.Cols) < x+1 {
return -1, errors.New("x coordinate is out of bounds!")
}
return row.Cols[x], nil
}
func (state *GameState) Enliven(x, y int) error {
return state.Set(x, y, 1)
}
func (state *GameState) Deaden(x, y int) error {
return state.Set(x, y, 0)
}
func NewGameOfLife(height, width int) *GameOfLife {
return &GameOfLife{
Height: height,
Width: width,
}
}
func (state *GameState) ImportState(other *GameState) (err error) {
for y, row := range other.Rows {
for x, cell := range row.Cols {
if err = state.Set(x, y, cell); err != nil {
return err
}
}
}
return nil
}