-
Notifications
You must be signed in to change notification settings - Fork 8
/
game.go
101 lines (86 loc) · 2.01 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
package tinyrpg
import (
"log"
"math/rand"
"time"
uuid "github.com/satori/go.uuid"
)
// World represents game state
type World struct {
Replica bool
Units map[string]*Unit
MyID string
}
func (world *World) AddPlayer() string {
skins := []string{"big_demon", "big_zombie", "elf_f"}
id := uuid.NewV4().String()
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
unit := &Unit{
Id: id,
X: rnd.Float64()*300 + 10,
Y: rnd.Float64()*220 + 10,
Frame: int32(rnd.Intn(4)),
Skin: skins[rnd.Intn(len(skins))],
Action: "idle",
Speed: 1,
}
world.Units[id] = unit
return id
}
func (world *World) HandleEvent(event *Event) {
log.Println(event.GetType())
log.Println(event.GetData())
switch event.GetType() {
case Event_type_connect:
data := event.GetConnect()
world.Units[data.Unit.Id] = data.Unit
case Event_type_init:
data := event.GetInit()
if world.Replica {
world.MyID = data.PlayerId
world.Units = data.Units
}
case Event_type_exit:
data := event.GetExit()
delete(world.Units, data.PlayerId)
case Event_type_move:
data := event.GetMove()
unit := world.Units[data.PlayerId]
unit.Action = UnitActionMove
unit.Direction = data.Direction
case Event_type_idle:
data := event.GetIdle()
unit := world.Units[data.PlayerId]
unit.Action = UnitActionIdle
default:
log.Println("UNKNOWN EVENT: ", event)
}
}
func (world *World) Evolve() {
ticker := time.NewTicker(time.Second / 60)
for {
select {
case <-ticker.C:
for _, unit := range world.Units {
if unit.Action == UnitActionMove {
switch unit.Direction {
case Direction_left:
unit.X -= unit.Speed
unit.Side = Direction_left
case Direction_right:
unit.X += unit.Speed
unit.Side = Direction_right
case Direction_up:
unit.Y -= unit.Speed
case Direction_down:
unit.Y += unit.Speed
default:
log.Println("UNKNOWN DIRECTION: ", unit.Direction)
}
}
}
}
}
}
const UnitActionMove = "run"
const UnitActionIdle = "idle"