aboutsummaryrefslogtreecommitdiff
path: root/internal/world/mob.go
blob: cc2d2b2e4955f710d8e466de46ae61775e435cf7 (plain)
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
412
413
414
415
416
417
418
419
package world

import (
	"fmt"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"gopkg.in/yaml.v3"
	"thehouseoficarus/internal/behavior"
)

type MobDropTable struct {
	Remains string               `yaml:"remains"`
	Loot    []behavior.DropEntry `yaml:"loot"`
}

type MobDef struct {
	ID                 string       `yaml:"id"`
	Name               string       `yaml:"name"`
	Description        string       `yaml:"description"`
	IdleDescriptions   []string     `yaml:"idle_descriptions"`
	CombatDescriptions []string     `yaml:"combat_descriptions"`
	Attack             int          `yaml:"attack"`
	Strength           int          `yaml:"strength"`
	Defense            int          `yaml:"defense"`
	HP                 int          `yaml:"hp"`
	Ranged             int          `yaml:"ranged"`
	Science            int          `yaml:"science"`
	Speed              float64      `yaml:"speed"`
	Aggressive         bool         `yaml:"aggressive"`
	Protected          bool         `yaml:"protected"`
	Unique             bool         `yaml:"unique"`
	RespawnTicks       float64      `yaml:"respawn_ticks"`
	Drops              MobDropTable `yaml:"drops"`

	AttackBonus   int    `yaml:"attack_bonus"`
	StrengthBonus int    `yaml:"strength_bonus"`
	AttackType    string `yaml:"attack_type"`

	StabDefense    int `yaml:"stab_defense"`
	SlashDefense   int `yaml:"slash_defense"`
	CrushDefense   int `yaml:"crush_defense"`
	ScienceDefense int `yaml:"science_defense"`
	RangedDefense  int `yaml:"ranged_defense"`

	Weakness   string  `yaml:"weakness"`
	StealTable string  `yaml:"steal_table"`
	StealLevel int     `yaml:"steal_level"`
	StealXP    int     `yaml:"steal_xp"`
	StealSpeed float64 `yaml:"steal_speed"`

	AssassinLevel int    `yaml:"assassin_level"`
	FinishingBlow string `yaml:"finishing_blow"`
	DamageWithout string `yaml:"damage_without"`
	Size          string `yaml:"size"`

	// Kind discriminates a normal combat mob ("" or "combat") from a "task"
	// worksite (build a solar panel, survey a rock, etc.). A task mob reuses the
	// entire combat engine but its HP drains to 0 to COMPLETE the work; it never
	// attacks back (the room hazard, if any, supplies the danger). The progress
	// bar is displayed inverted (filling toward 100%).
	Kind            string `yaml:"kind"`
	Verb            string `yaml:"verb"`             // flavor verb for messages (default "work")
	ProgressNoun    string `yaml:"progress_noun"`    // flavor noun, e.g. "construction"
	CompleteMessage string `yaml:"complete_message"` // shown on completion

	Talk *behavior.TalkConfig `yaml:"talk,omitempty"`
}

func (d *MobDef) IsTalkable() bool { return d.Talk != nil }

func (d *MobDef) IsTask() bool { return d.Kind == "task" }

type MobInstance struct {
	InstanceID        string
	DefID             string
	Name              string
	Description       string
	HP                int
	MaxHP             int
	Attack            int
	Strength          int
	Defense           int
	Ranged            int
	Science           int
	Speed             float64
	Aggressive        bool
	Protected         bool
	Unique            bool
	RespawnTicks      float64
	RoomID            int
	HomeRoomID        int
	Drops             MobDropTable
	IdleDescription   string
	WanderRooms       []int
	WanderInterval    float64
	WanderTickCounter int
	regenerateTick    int

	AttackBonus   int
	StrengthBonus int
	AttackType    string

	StabDefense    int
	SlashDefense   int
	CrushDefense   int
	ScienceDefense int
	RangedDefense  int

	Weakness   string
	StealTable string
	StealLevel int
	StealXP    int
	StealSpeed float64

	AssassinLevel int
	FinishingBlow string
	DamageWithout string
	Size          string

	Kind            string
	Verb            string
	ProgressNoun    string
	CompleteMessage string

	TalkConfig *behavior.TalkConfig

	Owner             string
	OwnerOnly         bool
	SpawnedByTrigger  bool
	DespawnOnLeave    bool
	DespawnRooms      []int
	DespawnTicks      float64
	DespawnCounter    int
}

func (m *MobInstance) IsTalkable() bool { return m.TalkConfig != nil }

func (m *MobInstance) IsTask() bool { return m.Kind == "task" }

func NewMobInstance(def *MobDef, instanceID string, roomID int, wanderRooms []int, wanderInterval float64) *MobInstance {
	hp := def.HP
	if def.Protected && hp <= 0 {
		hp = 1
	}
	return &MobInstance{
		InstanceID:      instanceID,
		DefID:           def.ID,
		Name:            def.Name,
		Description:     def.Description,
		HP:              hp,
		MaxHP:           hp,
		Attack:          def.Attack,
		Strength:        def.Strength,
		Defense:         def.Defense,
		Ranged:          def.Ranged,
		Science:         def.Science,
		Speed:           def.Speed,
		Aggressive:      def.Aggressive,
		Protected:       def.Protected,
		Unique:          def.Unique,
		RespawnTicks:    def.RespawnTicks,
		RoomID:          roomID,
		HomeRoomID:      roomID,
		WanderRooms:     wanderRooms,
		WanderInterval:  wanderInterval,
		Drops:           def.Drops,
		AttackBonus:     def.AttackBonus,
		StrengthBonus:   def.StrengthBonus,
		AttackType:      def.AttackType,
		StabDefense:     def.StabDefense,
		SlashDefense:    def.SlashDefense,
		CrushDefense:    def.CrushDefense,
		ScienceDefense:  def.ScienceDefense,
		RangedDefense:   def.RangedDefense,
		Weakness:        def.Weakness,
		StealTable:      def.StealTable,
		StealLevel:      def.StealLevel,
		StealXP:         def.StealXP,
		StealSpeed:      def.StealSpeed,
		AssassinLevel:   def.AssassinLevel,
		FinishingBlow:   def.FinishingBlow,
		DamageWithout:   def.DamageWithout,
		Size:            def.Size,
		Kind:            def.Kind,
		Verb:            def.Verb,
		ProgressNoun:    def.ProgressNoun,
		CompleteMessage: def.CompleteMessage,
		TalkConfig:      def.Talk,
	}
}

const (
	MatchNone   = 0
	MatchPrefix = 1
	MatchExact  = 2
)

func (m *MobInstance) MatchQuality(input string) int {
	lower := strings.ToLower(input)
	if strings.ToLower(m.Name) == lower {
		return MatchExact
	}
	if behavior.WordPrefixMatch(input, m.Name) {
		return MatchPrefix
	}
	return MatchNone
}

func pickIdleDescription(descriptions []string) string {
	if len(descriptions) == 0 {
		return ""
	}
	return descriptions[rand.Intn(len(descriptions))]
}

func (m *MobInstance) StartRegen() {
	if m.regenerateTick == 0 {
		m.regenerateTick = 100
	}
}

func (m *MobInstance) DespawnTickCount() int {
	return m.DespawnCounter
}

func (m *MobInstance) DecrementDespawnCounter() {
	if m.DespawnCounter > 0 {
		m.DespawnCounter--
	}
}

func (m *MobInstance) ResetDespawnCounter(ticks int) {
	m.DespawnCounter = ticks
}

type MobStore struct {
	dataDir   string
	mu        sync.Mutex
	pathIndex map[string]string
	defs      map[string]*MobDef
	instances map[string]*MobInstance
}

func NewMobStore(dataDir string) *MobStore {
	return &MobStore{
		dataDir:   dataDir,
		pathIndex: behavior.BuildPathIndex(filepath.Join(dataDir, "mobs")),
		defs:      make(map[string]*MobDef),
		instances: make(map[string]*MobInstance),
	}
}

func (s *MobStore) LoadDef(id string) (*MobDef, error) {
	s.mu.Lock()
	if def, ok := s.defs[id]; ok {
		s.mu.Unlock()
		return def, nil
	}
	s.mu.Unlock()

	path, ok := s.pathIndex[id]
	if !ok {
		return nil, fmt.Errorf("read mob %s: no such mob", id)
	}
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read mob %s: %w", id, err)
	}
	var def MobDef
	if err := yaml.Unmarshal(data, &def); err != nil {
		return nil, fmt.Errorf("parse mob %s: %w", id, err)
	}
	def.ID = id

	s.mu.Lock()
	s.defs[id] = &def
	s.mu.Unlock()
	return &def, nil
}

func (s *MobStore) AllDefIDs() map[string]bool {
	ids := make(map[string]bool)
	for id := range s.pathIndex {
		ids[id] = true
	}
	return ids
}

func (s *MobStore) ReloadDefs(dataDir string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.defs = make(map[string]*MobDef)
	s.pathIndex = behavior.BuildPathIndex(filepath.Join(dataDir, "mobs"))
}

func (s *MobStore) GetInstance(id string) *MobInstance {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.instances[id]
}

func (s *MobStore) AllInstances() []*MobInstance {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []*MobInstance
	for _, inst := range s.instances {
		out = append(out, inst)
	}
	return out
}

func (s *MobStore) MobsInRoom(roomID int) []*MobInstance {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []*MobInstance
	for _, inst := range s.instances {
		if inst.RoomID == roomID && inst.HP > 0 {
			out = append(out, inst)
		}
	}
	return out
}

func (s *MobStore) Tick() {
	s.mu.Lock()
	defer s.mu.Unlock()

	for _, inst := range s.instances {
		if inst.HP <= 0 || inst.HP >= inst.MaxHP {
			inst.regenerateTick = 0
			continue
		}
		inst.regenerateTick--
		if inst.regenerateTick <= 0 {
			inst.HP++
			if inst.HP >= inst.MaxHP {
				inst.HP = inst.MaxHP
				inst.regenerateTick = 0
			} else {
				inst.regenerateTick = 100
			}
		}
	}
}

func (s *MobStore) RollIdleDescription(inst *MobInstance) {
	def, err := s.LoadDef(inst.DefID)
	if err != nil {
		return
	}
	inst.IdleDescription = pickIdleDescription(def.IdleDescriptions)
	inst.WanderTickCounter = 0
}

func (s *MobStore) SpawnTransient(def *MobDef, cfg *SpawnMobConfig, roomID int, owner string) *MobInstance {
	s.mu.Lock()
	defer s.mu.Unlock()

	instID := fmt.Sprintf("trigger_%s_%d_%d", cfg.ID, roomID, len(s.instances))
	inst := NewMobInstance(def, instID, roomID, nil, 0)
	inst.Owner = owner
	inst.OwnerOnly = cfg.OwnerOnly
	inst.SpawnedByTrigger = true
	inst.DespawnOnLeave = cfg.DespawnOnLeave
	inst.DespawnRooms = cfg.DespawnRooms
	inst.DespawnTicks = cfg.DespawnTicks
	inst.IdleDescription = pickIdleDescription(def.IdleDescriptions)
	s.instances[instID] = inst
	return inst
}

func (s *MobStore) RemoveInstance(instanceID string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.instances, instanceID)
}

func (s *MobStore) RemoveMobsInRoom(roomID int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for id, inst := range s.instances {
		if inst.RoomID == roomID {
			delete(s.instances, id)
		}
	}
}

func (s *MobStore) SeedMobs(roomID int, entries []RoomMob) {
	type defWrapper struct {
		def *MobDef
		err error
		rm  RoomMob
	}
	defs := make([]defWrapper, len(entries))
	for i, rm := range entries {
		d, err := s.LoadDef(rm.ID)
		defs[i] = defWrapper{d, err, rm}
	}

	s.mu.Lock()
	defer s.mu.Unlock()
	for i, dw := range defs {
		if dw.err != nil {
			continue
		}
		defID := dw.rm.ID
		instID := fmt.Sprintf("%s_%d_%d", defID, roomID, i)
		if _, exists := s.instances[instID]; exists {
			continue
		}
		inst := NewMobInstance(dw.def, instID, roomID, dw.rm.WanderRooms, dw.rm.WanderInterval)
		inst.IdleDescription = pickIdleDescription(dw.def.IdleDescriptions)
		s.instances[instID] = inst
	}
}