-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (92 loc) · 2.1 KB
/
main.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"fmt"
"log"
"math"
"math/rand"
"time"
"github.com/hajimehoshi/ebiten/v2"
)
var (
WIDTH int = 160
HEIGHT int = 120
startTPS int = 30
globalTick int = 0
worldBorder bool = false
)
type Game struct {
world *World
pixels []byte
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func (g *Game) Draw(screen *ebiten.Image) {
// h + left click: heavy- weight spaceship (HWSS)
if ebiten.IsKeyPressed(ebiten.KeyH) && ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {
x, y := ebiten.CursorPosition()
g.world.heavyWeightSpaceship(x, y)
}
// r: reset world
if ebiten.IsKeyPressed(ebiten.KeyR) {
log.Print("reseting world")
g.world.reset()
}
// p: populate world
if ebiten.IsKeyPressed(ebiten.KeyP) {
log.Print("populating world")
g.world.randPopulate(1337)
}
// update tps, up or down
currTPS := int(math.Round(ebiten.CurrentTPS()))
if ebiten.IsKeyPressed(ebiten.KeyUp) {
ebiten.SetMaxTPS(currTPS + 1)
}
if ebiten.IsKeyPressed(ebiten.KeyDown) && currTPS > 0 {
ebiten.SetMaxTPS(currTPS - 1)
}
// draw
g.pixels = g.world.toPixel(g.pixels)
screen.ReplacePixels(g.pixels)
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return WIDTH, HEIGHT
}
func (g *Game) Update() error {
globalTick++
alive, dead := g.world.update(worldBorder)
aliveRatio := (alive / (alive + dead)) * 100
ebiten.SetWindowTitle(
fmt.Sprintf("tps: %d | gen: %d | alive: %d | dead: %d | alive ratio: %.2f%%",
int(math.Round(ebiten.CurrentTPS())),
globalTick,
int(alive),
int(dead),
aliveRatio,
))
return nil
}
func initMtx(width, height int) [][]Cell {
m := make([][]Cell, width)
for i := range m {
m[i] = make([]Cell, height)
}
return m
}
func main() {
g := &Game{
world: &World{
width: WIDTH,
height: HEIGHT,
mtx: initMtx(WIDTH, HEIGHT),
},
pixels: make([]byte, WIDTH*HEIGHT*4),
}
ebiten.SetMaxTPS(startTPS)
ebiten.SetWindowSize(640, 480)
ebiten.SetWindowTitle("Your game's title")
g.world.randPopulate((WIDTH * HEIGHT) / 2)
if err := ebiten.RunGame(g); err != nil {
log.Fatal(err)
}
}