-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
85 lines (70 loc) · 1.61 KB
/
server.go
File metadata and controls
85 lines (70 loc) · 1.61 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
package main
import (
"Kadane/core"
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
var world core.World
var running bool = true
// Prints a usage message to os.Stderr (standard error).
func usage() {
fmt.Fprintf(os.Stderr, "usage: server [options]\n")
flag.PrintDefaults()
os.Exit(2)
}
// Flag Variables (addr)
var (
addr = flag.String("addr", "localhost:8080", "address to serve")
)
func main() {
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments (none).
args := flag.Args()
if len(args) != 0 {
usage()
}
world = CreateGameWorld()
go gameLoop()
router := gin.Default()
router.Use(cors.Default())
router.GET("/api/game", gameApiHandler)
// serve index.html for unknown routes (SPA fallback)
router.NoRoute(func(c *gin.Context) {
c.File("./client/build/index.html")
})
router.Run("localhost:8080")
}
func gameApiHandler(c *gin.Context) {
entCollection := world.GetCollection()
list := make([]core.EntityInfo, 0, 5)
entityList := *entCollection.GetEntities()
for _, value := range entityList {
entityInfo := core.CreateInfo(&value)
list = append(list, entityInfo)
}
c.IndentedJSON(http.StatusOK, list)
}
// Game loop function
func gameLoop() {
const fps = 60
frameDuration := time.Second / fps
var elapsedTime time.Duration
for running {
startTime := time.Now()
// Game update logic
world.DoTick(float64(elapsedTime.Milliseconds()))
// Control frame rate
elapsedTime = time.Since(startTime)
sleepDuration := frameDuration - elapsedTime
if sleepDuration > 0 {
time.Sleep(sleepDuration)
}
}
}