75 lines
1.3 KiB
Go
75 lines
1.3 KiB
Go
package conway
|
|
|
|
var (
|
|
neighbors = []neighbor{
|
|
neighbor{-1, -1},
|
|
neighbor{-1, 0},
|
|
neighbor{-1, 1},
|
|
neighbor{0, -1},
|
|
neighbor{0, 1},
|
|
neighbor{1, -1},
|
|
neighbor{1, 0},
|
|
neighbor{1, 1},
|
|
}
|
|
)
|
|
|
|
type GenerationScoreCard struct {
|
|
GameState
|
|
}
|
|
|
|
type neighbor struct {
|
|
X int
|
|
Y int
|
|
}
|
|
|
|
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 {
|
|
stateWidth := state.Width()
|
|
stateCells, err := state.Cells()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for stateCell := range stateCells {
|
|
if stateCell.Value == 0 {
|
|
continue
|
|
}
|
|
|
|
for _, neighbor := range neighbors {
|
|
xTarget := stateCell.X + neighbor.X
|
|
yTarget := stateCell.Y + neighbor.Y
|
|
|
|
if xTarget < 0 || yTarget < 0 {
|
|
continue
|
|
}
|
|
|
|
if xTarget+1 > stateWidth || yTarget+1 > stateWidth {
|
|
continue
|
|
}
|
|
|
|
curScore, err := genScore.Get(xTarget, yTarget)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
err = genScore.Set(xTarget, yTarget, curScore+1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|