/
defs.go
138 lines (125 loc) · 2.61 KB
/
defs.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
package main
import (
"time"
"fmt"
"github.com/vhochmann/hex/game"
"github.com/vhochmann/hex/ui"
"github.com/vhochmann/hex/engine"
)
const(
NormalPrint = "%s"
SelectPrint = "**%s**"
)
var InitialState State = InitState
type State func(*game.Game) (State, *game.Game)
func Run(g *game.Game) {
g = game.NewGame()
defer g.DumpLog()
defer ui.Uninit()
for s := InitialState; s != nil; {
s, g = s(g)
}
}
// States!
func InitState(g *game.Game) (State, *game.Game) {
return TitleState, g
}
func TitleState(g *game.Game) (State, *game.Game) {
ui.Clear()
ui.Print(0, 0, "Title State")
ui.Update()
ui.GetEvent()
return MenuState, g
}
func SaveState(g *game.Game) (State, *game.Game) {
ui.Clear()
ui.Print(0,0,"Saving...")
// do actual saving here
ui.PrintSliceAtBottom(g.Read(8))
ui.Update()
time.Sleep(time.Millisecond * 200)
return PlayState, g
}
func LoadState(g *game.Game) (State, *game.Game) {
ui.Clear()
ui.Print(0, 0, "Loading...")
// do actual loading here
ui.PrintSliceAtBottom(g.Read(8))
ui.Update()
time.Sleep(time.Millisecond*200)
return PlayState, g
}
func MenuState(g *game.Game) (State, *game.Game) {
var offSet = 4
var current = 0
var printFormat string
var ev ui.Event
var options = []struct{
name string
val State
}{
{"Play", PlayState},
{"Save", SaveState},
{"Load", LoadState},
{"Exit", ExitState},
}
menu:
for {
ui.Clear()
for i := range options {
if i == current {
printFormat = SelectPrint
} else {
printFormat = NormalPrint
}
ui.Print(offSet*2, offSet+i, fmt.Sprintf(printFormat, options[i].name))
}
ui.PrintSliceAtBottom(g.Read(8))
ui.Update()
switch ev = ui.GetEvent(); ev.Key {
case ui.DOWN:
if current + 1 < len(options) {
current++
}
case ui.UP:
if current - 1 > -1 {
current--
}
case ui.ENTER:
break menu
}
}
return options[current].val, g
}
func PlayState(g *game.Game) (State, *game.Game) {
mc := g.Spawn()
loop:
for {
ui.Clear()
for i := range g.Players.Players {
if plyr := &g.Players.Players[i]; plyr.Alive {
plyr.Update()
ui.DrawRune(int(plyr.Pos.X), int(plyr.Pos.Y), '#')
//ui.SetCell(int(plyr.Pos.X), int(plyr.Pos.Y), '#')
}
}
ui.PrintSliceAtBottom(g.Read(8))
ui.Update()
switch ev := ui.GetEvent(); ev.Key {
case ui.ESC:
break loop
case ui.UP:
mc.SetVel(engine.Vec(0.0, -1.0))
case ui.DOWN:
mc.SetVel(engine.Vec(0.0, 1.0))
case ui.LEFT:
mc.SetVel(engine.Vec(-1.0, 0))
case ui.RIGHT:
mc.SetVel(engine.Vec(1.0, 0))
}
}
return MenuState, g
}
func ExitState(g *game.Game) (State, *game.Game) {
return nil, g // ExitState is only state that returns nil
}