aboutsummaryrefslogtreecommitdiff
path: root/internal/game/cmd_shop.go
blob: c6b7831ad0ad954fbcde16d46d7bfa4521a3b9da (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
package game

import (
	"fmt"
	"strconv"
	"strings"

	"thehouseoficarus/internal/action"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/object"
)

func (g *Game) handleShopInput(sess *net.Session, input string) {
	if sess.Player == nil {
		sess.State = net.StateGame
		g.writePrompt(sess)
		return
	}

	input = strings.TrimSpace(input)
	parts := strings.Fields(strings.ToLower(input))
	if len(parts) == 0 {
		g.showShopBrowse(sess)
		return
	}

	cmd := parts[0]

	switch cmd {
	case "buy":
		g.cmdShopBuy(sess, parts[1:])
	case "sell":
		g.cmdShopSell(sess, parts[1:])
	case "browse", "list":
		g.showShopBrowse(sess)
	case "leave", "bye", "exit", "quit":
		g.leaveShop(sess)
		return
	default:
		sess.WriteLine("Commands: buy <item>, sell <item>, browse, leave")
	}
	g.writeShopPrompt(sess)
}

func parseShopQty(args []string) (int, string, bool) {
	if len(args) == 0 {
		return 1, "", false
	}
	if strings.EqualFold(args[0], "all") {
		rest := strings.Join(args[1:], " ")
		return 0, rest, true
	}
	if n, err := strconv.Atoi(args[0]); err == nil && n > 0 {
		return n, strings.Join(args[1:], " "), false
	}
	return 1, strings.Join(args, " "), false
}

func (g *Game) cmdShopBuy(sess *net.Session, args []string) {
	cfg := g.shopConfig(sess)
	if cfg == nil {
		return
	}

	qty, itemName, all := parseShopQty(args)
	if itemName == "" {
		sess.WriteLine("Buy what? Use 'browse' to see available items.")
		return
	}

	g.doShopBuy(sess, itemName, qty, all)
}

func (g *Game) cmdShopSell(sess *net.Session, args []string) {
	cfg := g.shopConfig(sess)
	if cfg == nil {
		return
	}

	qty, itemName, all := parseShopQty(args)
	if itemName == "" {
		sess.WriteLine("Sell what?")
		return
	}

	g.doShopSell(sess, itemName, qty, all)
}

func (g *Game) writeShopPrompt(sess *net.Session) {
	sess.Write(fmt.Sprintf("\n%s", g.colorize(sess, "dialog", "> ")))
}

func (g *Game) shopConfig(sess *net.Session) *action.ShopConfig {
	cfg := sess.Shop
	return cfg
}

type shopMatch struct {
	si   *action.ShopItem
	name string
	def  *object.ItemDef
}

func (g *Game) showShopBrowse(sess *net.Session) {
	cfg := g.shopConfig(sess)
	if cfg == nil {
		return
	}

	if cfg.Message != "" {
		sess.WriteLine(fmt.Sprintf("\n%s", g.colorize(sess, "dialog", cfg.Message)))
	}

	if len(cfg.Items) == 0 {
		sess.WriteLine("This shop has nothing for sale.")
		return
	}

	unicode := true
	if p := sess.Player; p != nil {
		unicode = p.OptionBool("unicode")
	}

	t := Table{
		Title:   "Shop Inventory",
		Columns: []string{"Item", "Buy Price", "Sell Price"},
	}

	for _, si := range cfg.Items {
		def, _ := g.ItemStore.Load(si.ItemID)
		itemName := si.ItemID
		if def != nil {
			itemName = def.Name
		}
		buyStr := fmt.Sprintf("%d cr", si.BuyPrice)
		sellStr := "\u2014"
		if si.SellPrice > 0 {
			sellStr = fmt.Sprintf("%d cr", si.SellPrice)
		}
		t.Rows = append(t.Rows, []string{
			g.colorize(sess, "item", itemName),
			g.colorize(sess, "credits_pickup", buyStr),
			g.colorize(sess, "credits_pickup", sellStr),
		})
	}

	for _, line := range t.Render(unicode) {
		sess.WriteLine(line)
	}
}

func (g *Game) findShopMatches(input string, cfg *action.ShopConfig) []shopMatch {
	var matches []shopMatch
	for i := range cfg.Items {
		si := &cfg.Items[i]
		itemName := si.ItemID
		def, _ := g.ItemStore.Load(si.ItemID)
		if def != nil {
			itemName = def.Name
		}
		if object.WordPrefixMatch(input, itemName) {
			matches = append(matches, shopMatch{si: si, name: itemName, def: def})
		}
	}
	return matches
}

func (g *Game) doShopBuy(sess *net.Session, input string, qty int, all bool) {
	cfg := g.shopConfig(sess)
	if cfg == nil {
		return
	}

	p := sess.Player

	matches := g.findShopMatches(input, cfg)
	if len(matches) == 0 {
		sess.WriteLine("That item isn't for sale here. Use 'browse' to see shop inventory.")
		return
	}

	if len(matches) > 1 {
		sess.WriteLine("That's ambiguous, which one?")
		for _, m := range matches {
			sess.WriteLine(fmt.Sprintf("  - %s", g.colorize(sess, "item", m.name)))
		}
		return
	}

	si := matches[0].si
	def := matches[0].def

	actualQty := qty
	if all || qty == 0 {
		affordable := p.Credits / si.BuyPrice
		if def != nil && def.Stackable {
			actualQty = affordable
		} else {
			freeSlots := p.FreeSlots()
			actualQty = affordable
			if actualQty > freeSlots {
				actualQty = freeSlots
			}
		}
	}

	if actualQty <= 0 {
		if p.Credits < si.BuyPrice {
			sess.WriteLine(fmt.Sprintf("You need %d credits to buy that (you have %d).", si.BuyPrice, p.Credits))
		} else {
			sess.WriteLine("Your inventory is full.")
		}
		return
	}

	g.buyShopItem(sess, *si, actualQty)
}

func (g *Game) buyShopItem(sess *net.Session, si action.ShopItem, qty int) {
	p := sess.Player

	totalCost := si.BuyPrice * qty
	if p.Credits < totalCost {
		qty = p.Credits / si.BuyPrice
		if qty <= 0 {
			sess.WriteLine(fmt.Sprintf("You need %d credits to buy that (you have %d).", si.BuyPrice, p.Credits))
			return
		}
		totalCost = si.BuyPrice * qty
	}

	def, _ := g.ItemStore.Load(si.ItemID)
	displayName := si.ItemID
	if def != nil {
		displayName = def.Name
	}

	if def != nil && def.Stackable {
		for i := 0; i < 28; i++ {
			slot := p.InvSlot(i)
			if slot != nil && slot.ItemID == si.ItemID {
				p.Credits -= totalCost
				slot.Quantity += qty
				g.AccountStore.SaveCharacter(p)
				itemColor := g.itemColorize(sess, def, displayName)
				if qty == 1 {
					sess.WriteLine(fmt.Sprintf("You buy a %s for %s credits.", itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", si.BuyPrice))))
				} else {
					sess.WriteLine(fmt.Sprintf("You buy %d %s for %s credits.", qty, itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", totalCost))))
				}
				return
			}
		}

		freeSlot := p.FirstFreeSlot()
		if freeSlot == -1 {
			sess.WriteLine("Your inventory is full.")
			return
		}

		p.Credits -= totalCost
		p.SetInvSlot(freeSlot, g.newInventorySlot(si.ItemID, qty))
		g.AccountStore.SaveCharacter(p)

		itemColor := g.itemColorize(sess, def, displayName)
		if qty == 1 {
			sess.WriteLine(fmt.Sprintf("You buy a %s for %s credits.", itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", si.BuyPrice))))
		} else {
			sess.WriteLine(fmt.Sprintf("You buy %d %s for %s credits.", qty, itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", totalCost))))
		}
		return
	}

	freeSlots := p.FreeSlots()
	if qty > freeSlots {
		if freeSlots == 0 {
			sess.WriteLine("Your inventory is full.")
			return
		}
		qty = freeSlots
		totalCost = si.BuyPrice * qty
		if p.Credits < totalCost {
			qty = p.Credits / si.BuyPrice
			totalCost = si.BuyPrice * qty
		}
	}

	if qty <= 0 {
		if p.Credits < si.BuyPrice {
			sess.WriteLine(fmt.Sprintf("You need %d credits to buy that (you have %d).", si.BuyPrice, p.Credits))
		} else {
			sess.WriteLine("Your inventory is full.")
		}
		return
	}

	p.Credits -= totalCost
	for j := 0; j < qty; j++ {
		freeSlot := p.FirstFreeSlot()
		p.SetInvSlot(freeSlot, g.newInventorySlot(si.ItemID, 1))
	}
	g.AccountStore.SaveCharacter(p)

	itemColor := g.itemColorize(sess, def, displayName)
	if qty == 1 {
		sess.WriteLine(fmt.Sprintf("You buy a %s for %s credits.", itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", si.BuyPrice))))
	} else {
		sess.WriteLine(fmt.Sprintf("You buy %d %s for %s credits.", qty, itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", totalCost))))
	}
}

func (g *Game) doShopSell(sess *net.Session, input string, qty int, all bool) {
	cfg := g.shopConfig(sess)
	if cfg == nil {
		return
	}

	p := sess.Player

	matches := g.findInventoryMatches(input, p)
	if len(matches) == 0 {
		sess.WriteLine("You don't have that item.")
		return
	}

	if len(matches) > 1 {
		sess.WriteLine("That's ambiguous, which one?")
		for _, m := range uniqueItemNames(matches) {
			sess.WriteLine(fmt.Sprintf("  - %s", g.colorize(sess, "item", m)))
		}
		return
	}

	match := matches[0]

	var shopItem *action.ShopItem
	for i := range cfg.Items {
		si := &cfg.Items[i]
		if si.ItemID == match.ID && si.SellPrice > 0 {
			shopItem = si
			break
		}
	}

	if shopItem == nil {
		def, _ := g.ItemStore.Load(match.ID)
		displayName := match.ID
		if def != nil {
			displayName = def.Name
		}
		sess.WriteLine(fmt.Sprintf("The shop doesn't want to buy %s.", g.colorize(sess, "item", displayName)))
		return
	}

	totalInInv := p.CountItem(match.ID)
	actualQty := qty
	if all || qty == 0 {
		actualQty = totalInInv
	} else if actualQty > totalInInv {
		actualQty = totalInInv
	}

	if actualQty <= 0 {
		sess.WriteLine("You don't have that item.")
		return
	}

	p.RemoveItem(match.ID, actualQty)
	p.Credits += shopItem.SellPrice * actualQty
	g.AccountStore.SaveCharacter(p)

	def, _ := g.ItemStore.Load(match.ID)
	displayName := match.Name
	itemColor := g.itemColorize(sess, def, displayName)
	if actualQty == 1 {
		sess.WriteLine(fmt.Sprintf("You sell a %s for %s credits.", itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", shopItem.SellPrice))))
	} else {
		totalCredits := shopItem.SellPrice * actualQty
		sess.WriteLine(fmt.Sprintf("You sell %d %s for %s credits.", actualQty, itemColor, g.colorize(sess, "credits_pickup", fmt.Sprintf("%d", totalCredits))))
	}
}

func (g *Game) leaveShop(sess *net.Session) {
	sess.Shop = nil
	p := sess.Player
	if p == nil || p.Action == nil || p.Action.Type != "talk" {
		sess.State = net.StateGame
		if p != nil {
			g.cancelAction(p)
		}
		g.writePrompt(sess)
		return
	}

	nodeKey, _ := p.Action.Data["node"].(string)

	cfg, ok := p.Action.Data["talk_cfg"].(*action.TalkConfig)
	if !ok || cfg == nil {
		sess.State = net.StateGame
		g.cancelAction(p)
		g.writePrompt(sess)
		return
	}

	node, ok := cfg.Nodes[nodeKey]
	if !ok {
		sess.State = net.StateGame
		g.cancelAction(p)
		g.writePrompt(sess)
		return
	}

	sess.State = net.StateTalk
	visible := 0
	for _, opt := range node.Options {
		if opt.Condition != nil && !g.checkCondition(sess, opt.Condition) {
			continue
		}
		visible++
		sess.WriteLine(fmt.Sprintf("  %d. %s", visible, opt.Text))
	}
	if visible == 0 {
		sess.State = net.StateGame
		g.cancelAction(p)
		g.writePrompt(sess)
		return
	}
	sess.Write("\nChoice: ")
}