-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.go
417 lines (345 loc) · 10.1 KB
/
game.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package gamestate
import (
"context"
"image"
"image/color"
"log"
maps2 "maps"
"slices"
"time"
"github.com/ebitenui/ebitenui"
"github.com/ebitenui/ebitenui/widget"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/vector"
"github.com/gopher-co/td-game/models/config"
"github.com/gopher-co/td-game/models/general"
"github.com/gopher-co/td-game/models/ingame"
"github.com/gopher-co/td-game/replay"
)
// CurrentState is an enum that represents the current state of the game.
type CurrentState int
const (
// Running is the state when the game is running.
Running CurrentState = iota
// Paused is the state when the game is paused.
Paused
// NextWaveReady is the state when the next wave is ready.
NextWaveReady
)
// GameState is a struct that represents the state of the game.
type GameState struct {
// LevelName is a name of the level.
LevelName string
// Map is a map of the game.
Map *ingame.Map
// TowersToBuy is a map of towers that can be bought.
TowersToBuy map[string]*config.Tower
// EnemyToCall is a map of enemies that can be called.
EnemyToCall map[string]*config.Enemy
// Ended is a flag that represents if the game is ended.
Ended bool
// Win is a flag that represents if the game is won.
Win bool
// State is a current state of the game.
State CurrentState
// UI is a UI of the game.
UI *ebitenui.UI
// CurrentWave is a number of the current wave.
CurrentWave int
// GameRule is a game rule of the game.
GameRule ingame.GameRule
// Time is a time of the game.
Time general.Frames
// PlayerMapState is a state of the player on the map.
PlayerMapState ingame.PlayerMapState
// tookTower is a tower that was taken from the right sidebar.
tookTower *config.Tower
// chosenTower is a tower that was chosen from the map.
chosenTower *ingame.Tower
// speedUp is a flag that represents if the game is speeded up.
speedUp bool
// cancel is a function that cancels the context.
cancel context.CancelFunc
// Watcher is a watcher of the game.
Watcher *replay.Watcher
// PlayerState is a state of the player.
PlayerState *ingame.PlayerState
}
// New creates a new entity of GameState.
func New(
level *config.Level,
maps map[string]*config.Map,
en map[string]*config.Enemy,
tw map[string]*config.Tower,
ps *ingame.PlayerState,
w general.Widgets,
) *GameState {
tw2 := maps2.Clone(tw)
filter(tw2, func(s string, c *config.Tower) bool {
if c.OpenLevel == 0 {
return false
}
_, ok := ps.LevelsComplete[c.OpenLevel]
return !ok
})
gs := &GameState{
LevelName: level.LevelName,
Map: ingame.NewMap(maps[level.MapName]),
TowersToBuy: tw2,
EnemyToCall: en,
State: NextWaveReady,
CurrentWave: -1,
GameRule: ingame.NewGameRule(level.GameRule),
PlayerMapState: ingame.PlayerMapState{
Health: 100,
Money: 650,
},
Watcher: &replay.Watcher{
Name: level.LevelName,
InitPlayerMapState: ingame.PlayerMapState{
Health: 100,
Money: 650,
},
Actions: make([]replay.Action, 0, 2500),
},
PlayerState: ps,
}
ctx, cancel := context.WithCancel(context.Background())
gs.UI = gs.loadGameUI(ctx, w)
gs.cancel = cancel
return gs
}
// Update updates the state of the game.
func (s *GameState) Update() error {
if s.Ended {
return nil
}
if s.State == Paused {
return nil
}
// if clicked on tower
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButton0) {
s.rightSidebarHandle()
}
// put tower on the map
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButton0) && s.tookTower != nil {
t := s.putTowerHandler(s.tookTower)
if t != nil {
s.Watcher.Append(s.Time, replay.PutTower, replay.InfoPutTower{
Name: t.Name,
X: int(t.State.Pos.X),
Y: int(t.State.Pos.Y),
})
}
} else if inpututil.IsMouseButtonJustPressed(ebiten.MouseButton2) {
s.tookTower = nil
}
s.UI.Update()
if s.Ended {
return nil
}
if s.State == NextWaveReady {
if inpututil.IsKeyJustPressed(ebiten.KeySpace) {
btn := s.UI.Container.Children()[0].(*widget.Container). // mapContainer
Children()[2].(*widget.Container). // speed
Children()[0].(*widget.Container). // buttonGroup
Children()[0].(*widget.Button)
btn.ClickedEvent.Fire(&widget.ButtonClickedEventArgs{Button: btn})
}
return nil
}
if inpututil.IsKeyJustPressed(ebiten.KeySpace) {
btn := s.UI.Container.Children()[0].(*widget.Container). // mapContainer
Children()[2].(*widget.Container). // speed
Children()[0].(*widget.Container). // buttonGroup
Children()[1].(*widget.Button)
btn.ClickedEvent.Fire(&widget.ButtonClickedEventArgs{Button: btn})
}
s.Map.Update()
if s.PlayerMapState.Dead() {
s.Ended = true
s.setStateAfterEnd()
return nil
}
wave := s.GameRule[s.CurrentWave]
s.updateRunning(wave)
if wave.Ended() && !s.Map.AreThereAliveEnemies() {
s.setStateAfterWave()
if s.CurrentWave == len(s.GameRule)-1 {
s.Ended = true
s.Win = true
s.setStateAfterEnd()
}
return nil
}
s.Time++
return nil
}
// End returns true if the game is ended.
func (s *GameState) End() bool {
return s.Ended
}
// Draw draws the game on the screen.
func (s *GameState) Draw(screen *ebiten.Image) {
if s.Ended == true {
return
}
subScreen := screen.SubImage(image.Rect(0, 0, 1500, 1080))
s.Map.Draw(subScreen.(*ebiten.Image))
if s.tookTower != nil {
s.drawTookImageBeforeCursor(screen)
}
s.UI.Draw(screen)
}
// setStateAfterWave sets the state after the wave.
func (s *GameState) setStateAfterWave() {
s.State = NextWaveReady
s.Map.Enemies = []*ingame.Enemy{}
s.Map.Projectiles = []*ingame.Projectile{}
}
// clear clears the game state.
func (s *GameState) clear() {
ebiten.SetTPS(60)
s.cancel()
s.cancel = nil
}
// setStateAfterEnd sets the state after the end of the game.
func (s *GameState) setStateAfterEnd() {
s.clear()
// replay save
s.Watcher.Append(s.Time, replay.Stop, replay.InfoStop{Null: nil})
timestamp := time.Now().Truncate(0).Format("2006-01-02T15_04_05")
s.Watcher.Time = timestamp
if err := replay.Save("./Replays/replay_"+timestamp+".json", s.Watcher); err != nil {
log.Println("couldn't save replay:", err)
return
}
}
// updateRunning updates the state of the game when it is running.
func (s *GameState) updateRunning(wave *ingame.Wave) {
es := wave.CallEnemies()
for _, str := range es {
s.Map.Enemies = append(s.Map.Enemies, ingame.NewEnemy(s.EnemyToCall[str], s.Map.Path))
}
for _, e := range s.Map.Enemies {
if e.State.Dead {
if e.State.PassPath {
s.PlayerMapState.Health = max(s.PlayerMapState.Health-e.DealDamageToPlayer(), 0)
} else {
s.PlayerMapState.Money += e.MoneyAward
e.MoneyAward = 0
}
}
}
}
// drawTookImageBeforeCursor draws the image of the tower that was taken from the right sidebar.
func (s *GameState) drawTookImageBeforeCursor(screen *ebiten.Image) {
img := s.tookTower.Image()
cx, cy := ebiten.CursorPosition()
ix, iy := img.Bounds().Dx(), img.Bounds().Dy()
if !ingame.CheckCollisionPath(general.Point{X: general.Coord(cx), Y: general.Coord(cy)}, s.Map.Path) {
vector.DrawFilledCircle(screen, float32(cx), float32(cy), s.tookTower.InitRadius, color.RGBA{A: 0x20}, false)
} else {
vector.DrawFilledCircle(screen, float32(cx), float32(cy), s.tookTower.InitRadius, color.RGBA{0xff, 0, 0, 0x20}, false)
}
geom := ebiten.GeoM{}
geom.Translate(float64(cx-ix/2), float64(cy-iy/2))
screen.DrawImage(img, &ebiten.DrawImageOptions{GeoM: geom})
}
// filter filters the map m by the function f.
func filter[K comparable, V any, M ~map[K]V](m M, f func(K, V) bool) {
for k, v := range m {
if f(k, v) {
delete(m, k)
}
}
}
// rightSidebarHandle handles the right sidebar.
func (s *GameState) rightSidebarHandle() {
x, _ := ebiten.CursorPosition()
if x <= 1500 {
ts := slices.Clone(s.Map.Towers)
slices.Reverse(ts)
b := true
for _, t := range ts {
if b && t.IsClicked() {
t.Chosen = true
s.chosenTower = t
b = !b
s.updateTowerUI(t)
s.showTowerInfoMenu()
} else {
t.Chosen = false
}
}
if b {
s.showTowerMenu()
}
}
}
// putTowerHandler handles the putting of the tower.
func (s *GameState) putTowerHandler(tt *config.Tower) *ingame.Tower {
x, y := ebiten.CursorPosition()
pos := general.Point{X: general.Coord(x), Y: general.Coord(y)}
if x < 1500 && s.PlayerMapState.Money >= tt.Price {
if t := ingame.NewTower(tt, pos, s.Map.Path); t != nil {
s.tookTower = nil
s.PlayerMapState.Money -= tt.Price
s.Map.Towers = append(s.Map.Towers, t)
return t
}
}
return nil
}
// sellTowerHandler handles the selling of the tower.
func (s *GameState) sellTowerHandler(t *ingame.Tower) {
p := t.Price
for i := 0; i < t.UpgradesBought; i++ {
p += t.Upgrades[i].Price
}
p = p * 7 / 10
s.PlayerMapState.Money += p
t.Sold = true
s.chosenTower = nil
}
// upgradeTowerHandler handles the upgrading of the tower.
func (s *GameState) upgradeTowerHandler(t *ingame.Tower) {
if !t.Upgrade(s.PlayerState.LevelsComplete) {
return
}
price := t.Upgrades[t.UpgradesBought-1].Price
s.PlayerMapState.Money -= price
}
// turnOnTowerHandler handles the turning on of the tower.
func (s *GameState) turnOnTowerHandler(t *ingame.Tower) {
t.State.IsTurnedOn = true
}
// turnOffTowerHandler handles the turning off of the tower.
func (s *GameState) turnOffTowerHandler(t *ingame.Tower) {
t.State.IsTurnedOn = false
}
// tuneFirstTowerHandler handles the tuning of the tower.
// It sets the tower to aim at the first enemy.
func (s *GameState) tuneFirstTowerHandler(t *ingame.Tower) {
t.State.AimType = ingame.First
}
// tuneStrongTowerHandler handles the tuning of the tower.
// It sets the tower to aim at the strongest enemy.
func (s *GameState) tuneStrongTowerHandler(t *ingame.Tower) {
t.State.AimType = ingame.Strongest
}
// tuneWeakTowerHandler handles the tuning of the tower.
// It sets the tower to aim at the weakest enemy.
func (s *GameState) tuneWeakTowerHandler(t *ingame.Tower) {
t.State.AimType = ingame.Weakest
}
// findTowerIndex finds the index of the tower t in the map of towers.
func (s *GameState) findTowerIndex(t *ingame.Tower) int {
for k, v := range s.Map.Towers {
if v == t {
return k
}
}
return -1
}