-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.go
More file actions
122 lines (98 loc) · 2.37 KB
/
game.go
File metadata and controls
122 lines (98 loc) · 2.37 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"sync"
"github.com/dhconnelly/rtreego"
"github.com/gravestench/mathlib"
"github.com/hajimehoshi/ebiten/v2"
)
const (
fWidth = float64(Width)
fHeight = float64(Height)
)
type Game struct {
boidCount int
boids []*Boid
tick int
pixels []byte
}
func (g *Game) Update() error {
g.checkInput()
var wg sync.WaitGroup
currentCount := len(g.boids)
toCreateCount := g.boidCount - currentCount
boidChan := make(chan *Boid, toCreateCount)
wg.Add(g.boidCount)
for i := 0; i < g.boidCount; i++ {
idx := i
go func() {
defer wg.Done()
if idx >= currentCount {
boidChan <- newBoid(idx, nil)
} else {
boid := g.boids[idx]
boid.update(g.tick)
}
}()
}
wg.Wait()
close(boidChan)
points := make([]rtreego.Spatial, 0, g.boidCount)
for _, boid := range g.boids {
points = append(points, *boid)
}
if toCreateCount > 0 {
boids := make([]*Boid, 0, toCreateCount)
for boid := range boidChan {
boids = append(boids, boid)
points = append(points, *boid)
}
g.boids = append(g.boids, boids...)
}
global.setIndex(newIndex(points...))
g.tick++
return nil
}
func (g *Game) resetPixels() {
for i := range g.pixels {
g.pixels[i] = 255
}
}
func (g *Game) drawBoid(boid *Boid, wg *sync.WaitGroup) {
defer wg.Done()
trailChan := make(chan *TrailPixel, global.params.trailLength.value())
boid.getTrailPixels(g.tick, trailChan)
for trailPixel := range trailChan {
g.pixels[trailPixel.pixelIndex] = trailPixel.colourValue
g.pixels[trailPixel.pixelIndex+1] = trailPixel.colourValue
}
position := boid.Position()
x := int(position.X)
y := int(position.Y)
pixelDataPosition := (y*Width + x) * 4
g.pixels[pixelDataPosition] = 0
g.pixels[pixelDataPosition+1] = 0
}
func (g *Game) Draw(screen *ebiten.Image) {
g.resetPixels()
var wg sync.WaitGroup
wg.Add(len(g.boids))
for _, boid := range g.boids {
go g.drawBoid(boid, &wg)
}
wg.Wait()
screen.ReplacePixels(g.pixels)
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return Width, Height
}
func (g *Game) addBoid(position *mathlib.Vector2) {
boid := newBoid(g.boidCount, position)
g.boids = append(g.boids, boid)
g.boidCount++
}
func NewGame() *Game {
boidCount := boidCount
boids := make([]*Boid, 0, boidCount)
pixels := make([]byte, 4*Width*Height)
return &Game{boidCount: boidCount, boids: boids, pixels: pixels}
}