2024-04-27 22:32:05 +03:00
|
|
|
package game
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2024-05-06 20:43:35 +03:00
|
|
|
"mvvasilev/last_light/engine"
|
2024-04-27 22:32:05 +03:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const TICK_RATE int64 = 50 // tick every 50ms ( 20 ticks per second )
|
|
|
|
|
|
|
|
type GameContext struct {
|
2024-05-06 20:43:35 +03:00
|
|
|
renderContext *engine.RenderContext
|
2024-04-27 22:32:05 +03:00
|
|
|
|
|
|
|
game *Game
|
|
|
|
}
|
|
|
|
|
|
|
|
func CreateGameContext() *GameContext {
|
|
|
|
gc := new(GameContext)
|
|
|
|
|
2024-05-06 20:43:35 +03:00
|
|
|
rc, err := engine.CreateRenderContext()
|
2024-04-27 22:32:05 +03:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("%~v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
gc.renderContext = rc
|
|
|
|
gc.game = CreateGame()
|
|
|
|
|
|
|
|
return gc
|
|
|
|
}
|
|
|
|
|
|
|
|
func (gc *GameContext) Run() {
|
2024-05-06 18:59:14 +03:00
|
|
|
lastLoop := time.Now()
|
2024-04-27 22:32:05 +03:00
|
|
|
lastTick := time.Now()
|
|
|
|
|
|
|
|
for {
|
2024-05-06 18:59:14 +03:00
|
|
|
deltaTime := 1 + time.Since(lastLoop).Microseconds()
|
|
|
|
lastLoop = time.Now()
|
2024-04-27 22:32:05 +03:00
|
|
|
|
|
|
|
for _, e := range gc.renderContext.CollectInputEvents() {
|
|
|
|
gc.game.Input(e)
|
|
|
|
}
|
|
|
|
|
2024-05-06 18:59:14 +03:00
|
|
|
if time.Since(lastTick).Milliseconds() >= TICK_RATE {
|
|
|
|
stop := !gc.game.Tick(deltaTime)
|
2024-04-27 22:32:05 +03:00
|
|
|
|
2024-05-06 18:59:14 +03:00
|
|
|
if stop {
|
|
|
|
gc.renderContext.Stop()
|
|
|
|
os.Exit(0)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
lastTick = time.Now()
|
2024-04-27 22:32:05 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
drawables := gc.game.CollectDrawables()
|
|
|
|
gc.renderContext.Draw(deltaTime, drawables)
|
|
|
|
}
|
|
|
|
}
|