knowyt/server/src/engine/engine.go

44 lines
732 B
Go
Raw Normal View History

2021-07-29 19:06:25 +00:00
package engine
import (
"fmt"
"github.com/imkira/go-observer"
2021-08-04 23:42:21 +00:00
"math/rand"
2021-07-30 19:49:18 +00:00
"sirlab.de/go/knyt/syncdata"
2021-07-29 19:06:25 +00:00
"time"
)
2021-08-04 22:52:35 +00:00
func NewEngine(id string) *Engine {
2021-07-29 19:06:25 +00:00
engine := Engine{
2021-08-09 07:47:52 +00:00
id: id,
versionRef: 0,
obs: observer.NewProperty(syncdata.SyncData{}),
2021-07-29 19:06:25 +00:00
}
return &engine
}
2021-08-09 07:47:52 +00:00
func (eng *Engine) Run() {
2021-08-04 23:42:21 +00:00
r := rand.New(rand.NewSource(time.Now().UnixNano()))
2021-07-29 19:06:25 +00:00
for {
2021-08-06 19:46:00 +00:00
wait := int(1 + r.Float32()*5)
2021-08-04 23:42:21 +00:00
for i := 0; i < wait; i++ {
time.Sleep(1 * time.Second)
}
2021-08-09 07:47:52 +00:00
2021-08-09 08:36:19 +00:00
eng.doSomething()
}
}
func (eng *Engine) doSomething() {
eng.mu.Lock()
defer eng.mu.Unlock()
eng.versionRef++
fmt.Printf("game %s: %d\n", eng.id, eng.versionRef)
data := syncdata.SyncData{
VersionRef: eng.versionRef,
2021-07-29 19:06:25 +00:00
}
2021-08-09 08:36:19 +00:00
eng.obs.Update(data)
2021-07-29 19:06:25 +00:00
}