-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconwaysgame.go
87 lines (74 loc) · 2.03 KB
/
conwaysgame.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"log"
"math"
"math/rand"
"strconv"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
)
// Game controller
type ConwaysGame struct{}
// Initialize window and run Ebiten game runtime
func (g *ConwaysGame) Start() {
ebiten.SetWindowSize(S, S)
ebiten.SetWindowTitle("Conway's Game of Life Playground")
if err := ebiten.RunGame(g); err != nil {
log.Fatal(err)
}
}
// Each iteration of the game has its data updated here
// evolve() calls the Conway algorithm for next generation
func (g *ConwaysGame) Update() error {
time.Sleep(time.Duration(delay) * time.Millisecond)
board = evolve()
return nil
}
// Each iteration get rendered to screen here using Ebiten
func (g *ConwaysGame) Draw(screen *ebiten.Image) {
// Render background
screen.DrawImage(background, nil)
// Track generations
gen++
ebitenutil.DebugPrint(screen, strconv.Itoa(gen))
// Population: keeps track of total bits rendered
totalDots := 0
// Add random bit for extra noise
if rain > 0 && gen%rainInterval == 0 {
randomizeSeed(rain)
}
// Iterate through all points, calculate neighbors, color and render to image
for j := Vi; j < Vm; j++ {
for i := Vi; i < Vm; i++ {
var v int
if board[j][i] == 1 {
// Set randomized color
v = int(math.Pow(2, float64(rand.Intn(16)+1)))
totalDots++
} else {
// Skip rendering process for off bits
v = 0
continue
}
if sharp && getNeighbors(j, i) == 0 {
continue
}
// https://github.com/hajimehoshi/ebiten/blob/main/examples/2048/2048/tile.go
op := &ebiten.DrawImageOptions{}
x := (i-Vi)*tileSize + (i-Vi+1)*tileMargin
y := (j-Vi)*tileSize + (j-Vi+1)*tileMargin
op.GeoM.Translate(float64(x), float64(y))
r, g, b, a := colorToScale(tileBackgroundColor(v))
op.ColorM.Scale(r, g, b, a)
screen.DrawImage(tileImage, op)
}
}
// Play note based on board state
if sound {
algoSound(totalDots)
}
}
func (g *ConwaysGame) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return S, S
}