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

359 lines
6.4 KiB

package conway
import (
"crypto/sha1"
"errors"
"fmt"
"math"
"math/rand"
"strings"
"time"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
type GameOfLife struct {
State *GameState
}
type GameStateCell struct {
Value int
X int
Y int
}
type gameGridRow struct {
Cols []int
}
type GameState struct {
Rows []*gameGridRow
}
type GenerationScoreCard struct {
GameState
}
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) Height() int {
return len(state.Rows)
}
func (state *GameState) Width() int {
if len(state.Rows) < 1 {
return -1
}
return len(state.Rows[0].Cols)
}
func (state *GameState) GetRow(y int) (*gameGridRow, error) {
if y+1 > len(state.Rows) {
return nil, errors.New("y coordinate is out of bounds!")
}
return state.Rows[y], nil
}
func (state *GameState) Set(x, y, value int) error {
if x < 0 || y < 0 {
errMsg := fmt.Sprintf("coordinates (%v, %v) are out of bounds!", x, y)
return errors.New(errMsg)
}
row, err := state.GetRow(y)
if err != nil {
return err
}
if x+1 > len(row.Cols) {
errMsg := fmt.Sprintf("x coordinate %v is out of bounds!", x)
return errors.New(errMsg)
}
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 (state *GameState) Import(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
}
func (state *GameState) Cells(cells chan *GameStateCell) error {
height := state.Height()
width := state.Width()
if height < 0 || width < 0 {
return errors.New("state has invalid dimensions!")
}
defer close(cells)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
value, err := state.Get(x, y)
if err != nil {
panic(err)
}
cells <- &GameStateCell{
Value: value,
X: x,
Y: y,
}
}
}
return nil
}
func (game *GameOfLife) Mutate() error {
return game.State.Mutate()
}
func (state *GameState) Mutate() error {
randX := rand.Intn(state.Width())
randY := rand.Intn(state.Height())
curVal, err := state.Get(randX, randY)
if err != nil {
return err
}
err = state.Set(randX, randY, int(math.Abs(float64(curVal-1))))
return nil
}
func (game *GameOfLife) Checksum() string {
return game.State.Checksum()
}
func (state *GameState) Checksum() string {
ck := sha1.New()
cells := make(chan *GameStateCell)
go state.Cells(cells)
for cell := range cells {
fmt.Fprintf(ck, "%v", cell.Value)
}
return fmt.Sprintf("%x", ck.Sum(nil))
}
func NewGameOfLife(height, width int) *GameOfLife {
return &GameOfLife{
State: NewGameState(height, width),
}
}
func (game *GameOfLife) EvaluateGeneration() error {
height, width := game.State.Height(), game.State.Width()
genScore := NewGenerationScoreCard(height, width)
genScore.Calculate(game.State)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
score, err := genScore.Get(x, y)
if err != nil {
return err
}
curState, err := game.State.Get(x, y)
if err != nil {
return err
}
if curState == 1 {
if score < 2 {
err = game.State.Deaden(x, y)
if err != nil {
return err
}
continue
}
if score == 2 || score == 3 {
continue
}
if score > 3 {
err = game.State.Deaden(x, y)
if err != nil {
return err
}
continue
}
} else if curState == 0 {
if score == 3 {
err = game.State.Enliven(x, y)
if err != nil {
return err
}
continue
} else {
continue
}
}
}
}
return nil
}
func (game *GameOfLife) ImportState(state *GameState) error {
return game.State.Import(state)
}
func (game *GameOfLife) ImportRandomState() error {
height := game.State.Height()
width := game.State.Width()
if height < 0 || width < 0 {
errStr := fmt.Sprintf("current game has invalid dimensions! %vx%v",
height, width)
return errors.New(errStr)
}
randState := NewGameState(height, width)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
err := randState.Set(x, y, rand.Intn(2))
if err != nil {
return err
}
}
}
return game.ImportState(randState)
}
func (game *GameOfLife) String() string {
return fmt.Sprintf("%s\n", game.State)
}
func (state *GameState) String() string {
var rows []string
height := state.Height()
width := state.Width()
for y := 0; y < height; y++ {
var cells []string
for x := 0; x < width; x++ {
stringVal := "■"
value, err := state.Get(x, y)
if err != nil {
return ""
}
if value == 1 {
stringVal = "□"
}
cells = append(cells, stringVal)
}
rows = append(rows, strings.Join(cells, ""))
}
return strings.Join(rows, "\n")
}
func NewGenerationScoreCard(height, width int) *GenerationScoreCard {
genScore := &GenerationScoreCard{}
for i := 0; i < height; i++ {
row := &gameGridRow{}
for j := 0; j < width; j++ {
row.Cols = append(row.Cols, 0)
}
genScore.Rows = append(genScore.Rows, row)
}
return genScore
}
func (genScore *GenerationScoreCard) Calculate(state *GameState) error {
stateHeight, stateWidth := state.Height(), state.Width()
for y := 0; y < stateHeight; y++ {
for x := 0; x < stateWidth; x++ {
value, err := state.Get(x, y)
if err != nil {
return err
}
if value == 1 {
for yOffset := -1; yOffset < 2; yOffset++ {
for xOffset := -1; xOffset < 2; xOffset++ {
xTarget := x + xOffset
yTarget := y + yOffset
if xTarget < 0 || yTarget < 0 {
continue
}
if xTarget+1 > stateWidth || yTarget+1 > stateWidth {
continue
}
if xTarget == x && yTarget == y {
continue
}
curScore, err := genScore.Get(xTarget, yTarget)
if err != nil {
continue // assume out of bounds, which is stinky
}
err = genScore.Set(xTarget, yTarget, curScore+1)
if err != nil {
return err
}
}
}
}
}
}
return nil
}