-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworld.go
411 lines (359 loc) · 9.59 KB
/
world.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package rpg
import (
"fmt"
"log"
"math/rand"
"time"
"golang.org/x/image/colornames"
"github.com/aerth/rpc/librpg/common"
"github.com/aerth/rpc/librpg/maps"
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"github.com/faiface/pixel/text"
)
var SpriteFrame = pixel.R(-100, -100, 100, 100)
// World holds all information about a world
type World struct {
Name string
Bounds pixel.Rect
Regions []*Region
DObjects []*DObject
Tiles, Blocks []common.Object // sorted
Background string // path to pic, will be repeated xy if not empty
background *pixel.Sprite // sprite to repeat xy
Batches map[EntityType]*pixel.Batch // one batch for every spritemap
Color pixel.RGBA // clear window with this color
Entities []*Entity
Sheets map[EntityType]pixel.Picture
Anims map[EntityType]map[EntityState]map[Direction][]pixel.Rect // frankenmap
Char *Character
Animations []*Animation
Messages []string
Settings WorldSettings
imd *imdraw.IMDraw
text *text.Text
}
type WorldSettings struct {
NumEnemy int
}
func NewWorld(name string, difficulty int, seed string) *World {
w := new(World)
w.Name = name
if name == "" && seed == "" {
seed = fmt.Sprintf("%d", rand.Int63())
}
if name == "" {
w.Name = fmt.Sprintf("world seed %q", seed)
}
w.Color = RandomColor()
w.Sheets = make(map[EntityType]pixel.Picture)
w.Anims = make(map[EntityType]map[EntityState]map[Direction][]pixel.Rect)
char := NewCharacter("char")
char.Inventory = []Item{MakeGold(uint64(rand.Intn(7)))} // start with some loot
char.W = w
w.Char = char
w.Batches = map[EntityType]*pixel.Batch{}
// create sheets, animations , batch for each sprite map
for _, t := range []EntityType{SKELETON, SKELETON_GUARD} {
sheet, anims, err := LoadEntitySheet("sprites/"+t.String()+".png", 13, 21)
if err != nil {
panic(fmt.Errorf("error loading sheet: %s %v", t, err))
}
w.Sheets[t] = sheet
w.Anims[t] = anims
w.Batches[t] = pixel.NewBatch(&pixel.TrianglesData{}, w.Sheets[t])
}
if name != "" {
log.Println("Loading map", name)
if e := w.LoadMap("maps/" + name + ".map"); e != nil {
// log.Println(e)
if e2 := w.LoadMapFile(name); e2 != nil {
log.Println("fatal:", e2)
return nil
}
}
} else {
log.Println("generating map with seed:", seed)
omap := maps.GenerateMap(seed)
if e := w.injectMap(omap); e != nil {
log.Println("injekcting mapL:", e)
return nil
}
}
if len(w.Tiles) == 0 {
log.Println("Invalid map. No objects found")
return nil
}
char.Rect = char.Rect.Moved(common.FindRandomTile(w.Tiles))
w.Settings.NumEnemy = difficulty
return w
}
func (w World) String() string {
return w.Name
}
func (w *World) Update(dt float64) {
w.checkLevel()
// clean dynamic objecfts
dobjects := []*DObject{}
for i := range w.DObjects {
// not game time, could be.
if time.Since(w.DObjects[i].Until) > time.Millisecond {
continue
}
dobjects = append(dobjects, w.DObjects[i])
}
w.DObjects = dobjects
// clean mobs
entities := []*Entity{}
for i := range w.Entities {
if len(w.Entities) < i || w.Entities[i] == nil {
continue
}
w.Entities[i].ChangeMind(dt)
w.Entities[i].Update(dt)
if w.Entities[i].P.Health > 0 {
entities = append(entities, w.Entities[i])
continue
}
// entity is dead, spawn another
if len(w.Entities) > 10 {
continue
}
npc := w.NewEntity(SKELETON_GUARD)
npc.Rect = npc.Rect.Moved(common.FindRandomTile(w.Tiles))
entities = append(entities, npc)
npc = w.NewEntity(SKELETON)
npc.Rect = npc.Rect.Moved(common.FindRandomTile(w.Tiles))
entities = append(entities, npc)
}
w.Entities = entities
// update animations
if len(w.Animations) > 0 {
for i := range w.Animations {
w.Animations[i].update(dt)
}
}
// animations effect entities
for _, a := range w.Animations {
if a == nil || time.Since(a.start) < time.Millisecond*300 || time.Since(a.until) > time.Millisecond {
continue
}
// range each of the world's living things
for i, v := range w.Entities {
// see if they are in range
if a.rect.Contains(v.Rect.Center()) {
if a.ticker != nil {
select {
default:
continue
case <-a.ticker:
//
}
}
//w.Message(fmt.Sprintf("%s took %v damage", v.Name, a.damage))
w.Entities[i].P.Health -= a.damage
if w.Entities[i].P.Health <= 0 {
// entity damage should be function
if w.Entities[i].P.IsDead {
w.Entities[i].P.Health = 0
continue
}
w.Entities[i].P.Health = 0
w.Entities[i].P.IsDead = true
// add a new dynamic object 'loot' to the world
w.NewLoot(v.Center(), v.P.Loot)
// increase player kill count
w.Char.Stats.Kills++
// increase player experience
w.Char.ExpUp(v.P.XP)
//log.Println("Got new loot!:", FormatItemList(v.P.Loot))
//w.Char.Inventory = StackItems(w.Char.Inventory, v.P.Loot)
}
log.Printf("%s took %v damage, now at %v HP",
w.Entities[i].Name, a.damage, w.Entities[i].P.Health)
}
}
}
}
func (w *World) DrawEntity(n int) {
w.Entities[n].Draw(w.Batches[w.Entities[n].Type], w)
}
// Tile scans tiles and returns the first tile located at dot
func (w *World) Tile(dot pixel.Vec) common.Object {
if w.Tiles == nil {
log.Println("nil tiles!")
return common.Object{W: w, Type: common.O_BLOCK}
}
if len(w.Tiles) == 0 {
log.Println("no tiles to look in")
return common.Object{W: w, Type: common.O_BLOCK}
}
for i := len(w.Tiles) - 1; i >= 0; i-- {
if w.Tiles[i].Rect.Contains(dot) {
ob := w.Tiles[i]
ob.W = w
return ob
}
}
// log.Println("no tiles found at location:", dot)
// panic("bug")
return common.Object{W: w, Type: common.O_BLOCK}
}
// Block scans blocks and returns the first block located at dot
func (w *World) Block(dot pixel.Vec) common.Object {
for i := range w.Blocks {
if w.Blocks[i].Rect.Contains(dot) {
return w.Blocks[i]
}
}
return common.Object{}
}
// Object at location
func (w *World) Object(dot pixel.Vec) common.Object {
if w.Blocks != nil {
for _, v := range w.Blocks {
if v.Rect.Contains(dot) {
return v
}
}
}
for _, v := range w.Tiles {
if v.Rect.Contains(dot) {
return v
}
}
return common.Object{Type: common.O_NONE}
}
/*
// Object returns the object at dot, very expensive
func (w *World) Object(dot pixel.Vec) Object {
var ob Object
for i := range w.Objects {
if w.Objects[i].Rect.Contains(dot) {
ob = w.Objects[i]
if ob.Type == O_BLOCK { // prefer block over tile
return ob
}
}
}
return ob
}
*/
func (w *World) Draw(target pixel.Target) {
for i := range w.Entities {
w.DrawEntity(i)
}
for i := range w.Batches {
w.Batches[i].Draw(target)
}
if w.imd == nil {
w.imd = imdraw.New(nil)
}
/*
w.imd.Clear()
w.imd.Color = pixel.ToRGBA(colornames.Orange).Scaled(0.5)
w.imd.Push(w.Char.Rect.Min, w.Char.Rect.Max)
w.imd.Rectangle(3)
w.imd.Draw(target)
*/
}
func (w *World) ShowAnimations(imd *imdraw.IMDraw) {
for i := range w.Animations {
if w.Animations[i] != nil {
w.Animations[i].draw(imd)
}
}
}
func (w *World) HighlightPaths(target pixel.Target) {
imd := imdraw.New(nil)
for i := range w.Entities {
color := common.TransparentRed
if len(w.Entities[i].paths) != 0 {
for _, vv := range w.Entities[i].paths {
//color = color.Scaled(0.3)
imd.Color = color
v := w.Tile(vv)
imd.Push(v.Rect.Min, v.Rect.Max)
imd.Rectangle(4)
}
}
}
color := colornames.Purple
imd.Color = color
imd.Push(w.Char.Rect.Min, w.Char.Rect.Max)
imd.Rectangle(2)
imd.Draw(target)
}
func (w *World) Clean() {
for i := range w.Batches {
w.Batches[i].Clear()
}
}
func (w *World) CleanAnimations() {
anims := []*Animation{}
now := time.Now().UnixNano()
for i := range w.Animations {
if w.Animations[i] != nil && w.Animations[i].until.UnixNano() > now {
anims = append(anims, w.Animations[i])
} else {
//log.Println("removing animation", i)
}
}
w.Animations = anims
}
func (w *World) Reset() {
w.Char.Health = 255
w.Char.Stats = DefaultStats
w.Char.Level = 0
w.Char.Mana = 255
w.Char.Inventory = []Item{createLoot()}
w.Char.Rect = DefaultPhys.Rect.Moved(common.FindRandomTile(w.Tiles))
w.Char.Phys.Vel = pixel.ZV
w.Entities = nil
w.NewMobs(w.Settings.NumEnemy)
w.Animations = nil
}
func (w *World) IsLoot(location pixel.Vec) ([]Item, bool) {
var got []Item
var objects []*DObject
var found = false
for _, ob := range w.DObjects {
if !found && ob.Type == D_LOOT && ob.Object.Rect.Contains(location) {
got = ob.Contains
found = true
} else {
objects = append(objects, ob)
}
}
w.DObjects = objects
return got, found
}
func (w *World) Init() *pixel.Batch {
spritesheet, spritemap := LoadSpriteSheet("tileset.png")
globebatch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
for _, v := range w.Tiles {
v.Draw(globebatch, spritesheet, spritemap, 0)
}
for _, v := range w.Blocks {
v.Draw(globebatch, spritesheet, spritemap, 0)
}
return globebatch
}
func (w *World) drawTiles(path string) error {
spritesheet, spritemap := LoadSpriteSheet(path)
// layers (TODO: slice?)
// batch sprite drawing
globebatch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
// water world 67 wood, 114 117 182 special, 121 135 dirt, 128 blank, 20 grass
// rpg.DrawPattern(batch, spritemap[53], pixel.R(-3000, -3000, 3000, 3000), 100)
globebatch.Clear()
// draw it on to canvasglobe
for _, o := range w.Tiles {
o.Draw(globebatch, spritesheet, spritemap, 0)
}
for _, o := range w.Blocks {
o.Draw(globebatch, spritesheet, spritemap, 0)
}
w.Batches[EntityType(-1)] = globebatch
return nil
}