aboutsummaryrefslogtreecommitdiff
path: root/internal/game/cmd_get.go
blob: a806ffab7bb703a467623855a755fcbbf9bc892c (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package game

import (
	"fmt"
	"strings"

	"thehouseoficarus/internal/casino"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/player"
)

func (g *Game) doGet(sess *net.Session, input string) {
	p := sess.Player
	g.cancelAction(p)
	// Only stock this player may actually take counts: entries reserved
	// for another player are invisible to the pickup, so a blocked pickup
	// can never half-remove the ground stack.
	ground := g.World.AccessibleGround(p.RoomID, p.Name)
	if len(ground) == 0 {
		sess.WriteLine("There's nothing on the ground to pick up.")
		return
	}

	qty, itemName := parseQty(input)

	matches := g.findGroundMatches(itemName, p.RoomID)
	if len(matches) == 0 {
		sess.WriteLine(fmt.Sprintf("There's no '%s' here.", itemName))
		return
	}

	if len(matches) > 1 {
		unique := uniqueItemNames(matches)
		if len(unique) > 1 {
			g.showWhichOne(sess, matches)
			return
		}
	}

	itemID := matches[0].ID

	if itemID == "credits" {
		g.pickupCredits(sess, p, itemID)
		return
	}

	def, _ := g.ItemStore.Load(itemID)
	name := itemID
	if def != nil {
		name = def.Name
	}

	available := 0
	if gqty, ok := ground[itemID]; ok {
		available = gqty
	}
	if available <= 0 {
		sess.WriteLine("There's none of that here.")
		return
	}

	if qty == 0 {
		if def != nil && def.Stackable {
			qty = available
		} else {
			qty = 1
		}
	} else if qty > available {
		qty = available
	}

	// No premature free-slot gate here: a stackable pickup may merge into an
	// existing stack even when every slot is occupied, so capacity is only
	// required when a new slot is actually needed (matching doGetAll and
	// doGetAllNamed). See TestPickupMergesIntoFullInventory.

	if def != nil && def.Stackable {
		quality, maxQuality := g.groundStackProps(p, itemID)
		for i := 0; i < player.MaxInventorySlots; i++ {
			slot := p.InvSlot(i)
			if slot == nil || slot.ItemID != itemID || slot.Quality != quality || slot.MaxQuality != maxQuality {
				continue
			}
			removed, ok := g.World.RemoveReservedItem(p.RoomID, itemID, qty, p.Name)
			if !ok {
				sess.WriteLine("That's not yours!")
				return
			}
			slot.Quantity += removed
			g.saveCharacter(p)
			sess.WriteLine(fmt.Sprintf("You pick up %d x %s. (now %d)", qty, g.itemColorize(sess, def, def.Name), slot.Quantity))
			return
		}
		freeSlot := p.FirstFreeSlot()
		if freeSlot == -1 {
			sess.WriteLine("Your inventory is full.")
			return
		}
		removed, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, qty, p.Name)
		if !ok {
			sess.WriteLine("That's not yours!")
			return
		}
		p.SetInvSlot(freeSlot, g.groundSlot(itemID, removed, q, mq))
		g.saveCharacter(p)
		if qty == 1 {
			sess.WriteLine(fmt.Sprintf("You pick up a %s.", g.itemColorize(sess, def, def.Name)))
		} else {
			sess.WriteLine(fmt.Sprintf("You pick up %d x %s.", qty, g.itemColorize(sess, def, def.Name)))
		}
		return
	}

	picked := 0
	for picked < qty {
		fs := p.FirstFreeSlot()
		if fs == -1 {
			break
		}
		_, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, 1, p.Name)
		if !ok {
			break
		}
		p.SetInvSlot(fs, g.groundSlot(itemID, 1, q, mq))
		picked++
	}

	g.saveCharacter(p)
	if picked == 0 {
		sess.WriteLine("Your inventory is full.")
	} else if picked == 1 {
		sess.WriteLine(fmt.Sprintf("You pick up a %s.", g.itemColorize(sess, def, name)))
	} else {
		sess.WriteLine(fmt.Sprintf("You pick up %d x %s.", picked, g.itemColorize(sess, def, name)))
	}
}

func (g *Game) doGetAllNamed(sess *net.Session, input string) {
	p := sess.Player
	g.cancelAction(p)
	// Only takeable stock counts (see doGet).
	ground := g.World.AccessibleGround(p.RoomID, p.Name)
	if len(ground) == 0 {
		sess.WriteLine("There's nothing on the ground to pick up.")
		return
	}

	matches := g.findGroundMatches(input, p.RoomID)
	if len(matches) == 0 {
		sess.WriteLine(fmt.Sprintf("There's no '%s' here.", input))
		return
	}

	if len(matches) > 1 {
		unique := uniqueItemNames(matches)
		if len(unique) > 1 {
			g.showWhichOne(sess, matches)
			return
		}
	}

	itemID := matches[0].ID

	if itemID == "credits" {
		g.pickupCredits(sess, p, itemID)
		return
	}

	def, _ := g.ItemStore.Load(itemID)

	available := 0
	if gqty, ok := ground[itemID]; ok {
		available = gqty
	}
	if available <= 0 {
		sess.WriteLine("There's none of that here.")
		return
	}

	wanted := available
	if def != nil && !def.Stackable {
		free := p.FreeSlots()
		if wanted > free {
			wanted = free
		}
	}

	if wanted <= 0 {
		sess.WriteLine("Your inventory is full.")
		return
	}

	name := itemID
	if def != nil {
		name = def.Name
	}
	coloredName := g.itemColorize(sess, def, name)

	if def != nil && def.Stackable {
		quality, maxQuality := g.groundStackProps(p, itemID)
		for i := 0; i < player.MaxInventorySlots; i++ {
			slot := p.InvSlot(i)
			if slot == nil || slot.ItemID != itemID || slot.Quality != quality || slot.MaxQuality != maxQuality {
				continue
			}
			removed, ok := g.World.RemoveReservedItem(p.RoomID, itemID, wanted, p.Name)
			if !ok {
				sess.WriteLine("That's not yours!")
				return
			}
			slot.Quantity += removed
			g.saveCharacter(p)
			sess.WriteLine(fmt.Sprintf("You pick up %d x %s. (now %d)", removed, coloredName, slot.Quantity))
			return
		}
		freeSlot := p.FirstFreeSlot()
		if freeSlot == -1 {
			sess.WriteLine("Your inventory is full.")
			return
		}
		removed, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, wanted, p.Name)
		if !ok {
			sess.WriteLine("That's not yours!")
			return
		}
		p.SetInvSlot(freeSlot, g.groundSlot(itemID, removed, q, mq))
		g.saveCharacter(p)
		if removed == 1 {
			sess.WriteLine(fmt.Sprintf("You pick up a %s.", coloredName))
		} else {
			sess.WriteLine(fmt.Sprintf("You pick up %d x %s.", removed, coloredName))
		}
		return
	}

	picked := 0
	for picked < wanted {
		fs := p.FirstFreeSlot()
		if fs == -1 {
			break
		}
		_, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, 1, p.Name)
		if !ok {
			break
		}
		p.SetInvSlot(fs, g.groundSlot(itemID, 1, q, mq))
		picked++
	}

	g.saveCharacter(p)
	if picked == 0 {
		sess.WriteLine("Your inventory is full.")
	} else if picked == 1 {
		sess.WriteLine(fmt.Sprintf("You pick up a %s.", coloredName))
	} else {
		sess.WriteLine(fmt.Sprintf("You pick up %d x %s.", picked, coloredName))
	}
	if picked < available {
		sess.WriteLine(fmt.Sprintf("You're only able to take %d x %s!", picked, coloredName))
	}
}

func (g *Game) doGetAll(sess *net.Session) {
	p := sess.Player
	g.cancelAction(p)
	// Only takeable stock counts (see doGet); the all-or-nothing
	// RemoveReservedItem then never aborts a partial pickup.
	ground := g.World.AccessibleGround(p.RoomID, p.Name)
	if len(ground) == 0 {
		sess.WriteLine("There's nothing on the ground to pick up.")
		return
	}

	var picked []string
	creditsCapped := false
	for itemID, qty := range ground {
		if qty <= 0 {
			continue
		}
		if itemID == "credits" {
			// Same capped-removal rule as pickupCredits: only the balance
			// headroom is taken, so credits at the cap stay on the ground
			// instead of being destroyed by the clamped grant.
			room := creditHeadroom(p)
			taken := 0
			if room > 0 {
				taken = g.World.RemoveAvailableItem(p.RoomID, itemID, room, p.Name)
			}
			if taken <= 0 {
				if room <= 0 {
					creditsCapped = true
				}
				continue
			}
			g.grantCredits(p, taken)
			if taken == 1 {
				picked = append(picked, "1 credit")
			} else {
				picked = append(picked, fmt.Sprintf("%d credits", taken))
			}
			continue
		}

		def, _ := g.ItemStore.Load(itemID)
		for qty > 0 {
			if def != nil && def.Stackable {
				stacked := false
				quality, maxQuality := g.groundStackProps(p, itemID)
				for i := 0; i < player.MaxInventorySlots; i++ {
					slot := p.InvSlot(i)
					if slot == nil || slot.ItemID != itemID || slot.Quality != quality || slot.MaxQuality != maxQuality {
						continue
					}
					_, ok := g.World.RemoveReservedItem(p.RoomID, itemID, qty, p.Name)
					if !ok {
						qty = 0
						stacked = true
						break
					}
					slot.Quantity += qty
					picked = append(picked, fmt.Sprintf("%s (now %d)", g.itemColorize(sess, def, def.Name), slot.Quantity))
					stacked = true
					qty = 0
					break
				}
				if stacked {
					break
				}
				freeSlot := p.FirstFreeSlot()
				if freeSlot == -1 {
					if len(picked) > 0 {
						sess.WriteLine("You can't hold everything but you picked up:")
						formatPickupList(sess, picked)
					} else {
						sess.WriteLine("Your inventory is full!")
					}
					g.saveCharacter(p)
					return
				}
				removed, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, qty, p.Name)
				if !ok {
					break
				}
				p.SetInvSlot(freeSlot, g.groundSlot(itemID, removed, q, mq))
				name := itemID
				if def != nil {
					name = def.Name
				}
				picked = append(picked, g.itemColorize(sess, def, name))
				break
			}

			freeSlot := p.FirstFreeSlot()
			if freeSlot == -1 {
				if len(picked) > 0 {
					sess.WriteLine("You can't hold everything but you picked up:")
					formatPickupList(sess, picked)
				} else {
					sess.WriteLine("Your inventory is full!")
				}
				g.saveCharacter(p)
				return
			}

			take := 1
			_, q, mq, ok := g.World.RemoveReservedItemQ(p.RoomID, itemID, take, p.Name)
			if !ok {
				break
			}
			p.SetInvSlot(freeSlot, g.groundSlot(itemID, take, q, mq))
			name := itemID
			if def != nil {
				name = def.Name
			}
			picked = append(picked, g.itemColorize(sess, def, name))
			qty -= take
		}
	}

	g.saveCharacter(p)

	if creditsCapped {
		sess.WriteLine(g.colorize(sess, "currency_pickup", "Your purse can't hold any more credits."))
	}
	switch {
	case len(picked) > 0:
		sess.Write("You picked up: ")
		formatPickupList(sess, picked)
	case !creditsCapped:
		sess.WriteLine("Your inventory is full.")
	}
}

func (g *Game) pickupCredits(sess *net.Session, p *player.Player, itemID string) {
	// The balance cap is a hard limit: credits the purse cannot absorb must
	// stay on the ground instead of being removed and then clamped away by
	// grantCredits. Only the headroom below the cap is taken.
	room := creditHeadroom(p)
	if room <= 0 {
		sess.WriteLine(g.colorize(sess, "currency_pickup", "Your purse can't hold any more credits."))
		return
	}
	qty := g.World.RemoveAvailableItem(p.RoomID, itemID, room, p.Name)
	if qty <= 0 {
		return
	}
	g.grantCredits(p, qty)
	g.saveCharacter(p)
	if qty == 1 {
		sess.WriteLine(g.colorize(sess, "currency_pickup", "You pick up 1 credit."))
	} else {
		sess.WriteLine(g.colorize(sess, "currency_pickup", fmt.Sprintf("You pick up %d credits. (total: %d)", qty, p.Credits)))
	}
}

// creditHeadroom is how many credits p's balance can still absorb before the
// economy cap (casino.MaxCredits) is reached.
func creditHeadroom(p *player.Player) int {
	room := casino.MaxCredits - p.Credits
	if room < 0 {
		return 0
	}
	return room
}

// pickedStackProps returns the Quality and MaxQuality a freshly picked-up
// stack receives (newInventorySlot stamps full quality onto quality-bearing
// items). A pickup only merges into a slot with matching properties, since
// merging a differently qualified stack would silently destroy the picked-up
// stack's quality - the same rule withdrawBankItem applies in cmd_bank.go.
// It reads the rule through stackProps so every other stack-creation site
// (craft, harvest, ammo removal) agrees on the same values.
func (g *Game) pickedStackProps(itemID string) (quality, maxQuality int) {
	def, _ := g.ItemStore.Load(itemID)
	return stackProps(def)
}

// groundStackProps is pickedStackProps for a ground pickup: it prefers the
// quality carried by the ground entry so a partially-used item is not
// re-created at full quality (and a pickup only merges into a slot with the
// same properties).
func (g *Game) groundStackProps(p *player.Player, itemID string) (quality, maxQuality int) {
	if q, mq, ok := g.World.AccessibleGroundQuality(p.RoomID, itemID, p.Name); ok && mq > 0 {
		return q, mq
	}
	return g.pickedStackProps(itemID)
}

// groundSlot builds an inventory slot for a ground pickup, preserving the
// quality carried by the ground entry. A ground entry with no quality record
// (loot/trigger/spawn drops) falls back to the item's full quality, matching
// newInventorySlot.
func (g *Game) groundSlot(itemID string, qty, quality, maxQuality int) *player.InventorySlot {
	if maxQuality > 0 {
		return &player.InventorySlot{ItemID: itemID, Quantity: qty, Quality: quality, MaxQuality: maxQuality}
	}
	return g.newInventorySlot(itemID, qty)
}

func (g *Game) collectMatches(input string, each func(func(itemID string, slot int) bool)) []itemMatch {
	var matches []itemMatch
	each(func(itemID string, slot int) bool {
		def, err := g.ItemStore.Load(itemID)
		if err != nil {
			return true
		}
		if def.MatchesName(input) {
			matches = append(matches, itemMatch{ID: itemID, Name: def.Name, Slot: slot})
		}
		return true
	})
	return matches
}

func (g *Game) findGroundMatches(input string, roomID int) []itemMatch {
	ground := g.World.GroundItems(roomID)
	return g.collectMatches(input, func(yield func(string, int) bool) {
		for itemID := range ground {
			if !yield(itemID, -1) {
				return
			}
		}
	})
}

func (g *Game) findInventoryMatches(input string, p *player.Player) []itemMatch {
	return g.collectMatches(input, func(yield func(string, int) bool) {
		for i := 0; i < player.MaxInventorySlots; i++ {
			slot := p.InvSlot(i)
			if slot == nil {
				continue
			}
			if !yield(slot.ItemID, i) {
				return
			}
		}
	})
}

func (g *Game) executeGet(sess *net.Session, args []string, rawInput string) {
	if len(args) == 0 {
		sess.WriteLine("Get what?")
	} else if args[0] == "all" {
		if len(args) == 1 {
			g.doGetAll(sess)
		} else {
			g.doGetAllNamed(sess, strings.Join(args[1:], " "))
		}
	} else {
		g.doGet(sess, strings.Join(args, " "))
	}
}