-
Notifications
You must be signed in to change notification settings - Fork 0
/
genloot.go
100 lines (85 loc) · 2.33 KB
/
genloot.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
package looter
import (
"fmt"
"io"
"log"
"github.com/BurntSushi/toml"
wr "github.com/mroth/weightedrand"
)
type WeightedEntry struct {
Mult float64
Weight int
}
type LootGenerator struct {
Materials map[string]WeightedEntry `toml:"material"`
Quality map[string]WeightedEntry `toml:"quality"`
Items map[string]float64 `toml:"items"`
QualityChooser *wr.Chooser
MaterialChooser *wr.Chooser
TypeChooser *wr.Chooser
}
func NewLootGenerator(r io.Reader) (LootGenerator, error) {
lg := LootGenerator{}
err := lg.LoadReader(r)
if err != nil {
return lg, fmt.Errorf("error loading loot table from TOML: %w", err)
}
weightedMaterials := make([]wr.Choice, 0)
for k, v := range lg.Materials {
weightedMaterials = append(weightedMaterials, wr.Choice{
Item: k,
Weight: uint(v.Weight),
})
}
materialChooser, err := wr.NewChooser(weightedMaterials...)
if err != nil {
return lg, fmt.Errorf("error creating weighted Chooser for materials: %w", err)
}
lg.MaterialChooser = materialChooser
weightedQualities := make([]wr.Choice, 0)
for k, v := range lg.Quality {
weightedQualities = append(weightedQualities, wr.Choice{
Item: k,
Weight: uint(v.Weight),
})
}
qualityChooser, err := wr.NewChooser(weightedQualities...)
if err != nil {
return lg, fmt.Errorf("error creating weighted Chooser for quality: %w", err)
}
lg.QualityChooser = qualityChooser
weightedTypes := make([]wr.Choice, 0)
for k := range lg.Items {
weightedTypes = append(weightedTypes, wr.Choice{
Item: k,
Weight: 1,
})
}
typeChooser, err := wr.NewChooser(weightedTypes...)
if err != nil {
return lg, fmt.Errorf("error creating weighted Chooser for quality: %w", err)
}
lg.TypeChooser = typeChooser
return lg, nil
}
func (lg *LootGenerator) LoadReader(r io.Reader) error {
e := toml.NewDecoder(r)
_, err := e.Decode(lg)
return err
}
func (lg LootGenerator) Fill(target CashValue) []Item {
items := make([]Item, 0)
lootTotal := 0
for lootTotal < target.UnitValue() {
i := Item{}
i.Table = lg
i.Type = lg.TypeChooser.Pick().(string)
i.BaseValue = lg.Items[i.Type]
i.Material = lg.MaterialChooser.Pick().(string)
i.Quality = lg.QualityChooser.Pick().(string)
lootTotal += i.CashValue().UnitValue()
log.Printf("Generated item: %s\n", i)
items = append(items, i)
}
return items
}