From 5fae7256d76992e0ec954dfd36f6c602fc7eccd0 Mon Sep 17 00:00:00 2001 From: Thomas von Dein Date: Thu, 30 May 2024 10:23:31 +0200 Subject: [PATCH] refactored grid management --- grid.go | 13 +++++++++++-- scene-play.go | 20 ++++++++------------ 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/grid.go b/grid.go index b1a080a..79f2eca 100644 --- a/grid.go +++ b/grid.go @@ -36,7 +36,7 @@ func NewGrid(width, height, density int, empty bool) *Grid { return grid } -// Create a 1:1 copy +// Create a new 1:1 instance func (grid *Grid) Clone() *Grid { newgrid := &Grid{} @@ -47,6 +47,15 @@ func (grid *Grid) Clone() *Grid { return newgrid } +// copy data +func (grid *Grid) Copy(other *Grid) { + for y := range grid.Data { + for x := range grid.Data[y] { + other.Data[y][x] = grid.Data[y][x] + } + } +} + // delete all contents func (grid *Grid) Clear() { for y := range grid.Data { @@ -57,7 +66,7 @@ func (grid *Grid) Clear() { } // initialize with random life cells using the given density -func (grid *Grid) FillRandom(game *ScenePlay) { +func (grid *Grid) FillRandom() { if !grid.Empty { for y := range grid.Data { for x := range grid.Data[y] { diff --git a/scene-play.go b/scene-play.go index 6bd6002..c3d2c99 100644 --- a/scene-play.go +++ b/scene-play.go @@ -5,7 +5,6 @@ import ( "image" "image/color" "log" - "math/rand" "os" "github.com/hajimehoshi/ebiten/v2" @@ -493,6 +492,7 @@ func (scene *ScenePlay) InitPattern() { scene.History.LoadRLE(scene.Config.RLE) } +// pre-render offscreen cache image func (scene *ScenePlay) InitCache() { op := &ebiten.DrawImageOptions{} @@ -505,13 +505,17 @@ func (scene *ScenePlay) InitCache() { for y := 0; y < scene.Config.Height; y++ { for x := 0; x < scene.Config.Width; x++ { op.GeoM.Reset() - op.GeoM.Translate(float64(x*scene.Config.Cellsize), float64(y*scene.Config.Cellsize)) + op.GeoM.Translate( + float64(x*scene.Config.Cellsize), + float64(y*scene.Config.Cellsize), + ) scene.Cache.DrawImage(scene.Tiles.White, op) } } } +// initialize grid[s], either using pre-computed from state or rle file, or random func (scene *ScenePlay) InitGrid(grid *Grid) { if grid != nil { // use pre-loaded grid @@ -529,16 +533,8 @@ func (scene *ScenePlay) InitGrid(grid *Grid) { gridb := NewGrid(scene.Config.Width, scene.Config.Height, scene.Config.Density, scene.Config.Empty) history := NewGrid(scene.Config.Width, scene.Config.Height, scene.Config.Density, scene.Config.Empty) - for y := 0; y < scene.Config.Height; y++ { - if !scene.Config.Empty { - for x := 0; x < scene.Config.Width; x++ { - if rand.Intn(scene.Config.Density) == 1 { - history.Data[y][x] = 1 - grida.Data[y][x] = 1 - } - } - } - } + grida.FillRandom() + grida.Copy(history) scene.Grids = []*Grid{ grida,