Add durable recipe discovery and profession crafting
This commit is contained in:
@@ -47,6 +47,13 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
if w.Balance.Crafting != nil {
|
||||
for _, m := range w.Balance.Crafting.Materials {
|
||||
if m.ID == id {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID == id {
|
||||
known = true
|
||||
@@ -79,7 +86,7 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
if c.View.Inventory[id] < n {
|
||||
return errors.New("player no longer holds that item quantity")
|
||||
}
|
||||
c.View.Inventory[id] -= n
|
||||
TakeStack(c, id, n)
|
||||
if c.View.Inventory[id] == 0 {
|
||||
delete(c.View.Inventory, id)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (w *World) refreshCrafting(c *Character) {
|
||||
if c.View.Crafting == nil {
|
||||
c.View.Crafting = map[string]p.CraftProgress{}
|
||||
}
|
||||
if c.View.DiscoveredRecipes == nil {
|
||||
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
|
||||
}
|
||||
if w.Balance.Crafting == nil {
|
||||
return
|
||||
}
|
||||
for _, s := range w.Balance.Crafting.Professions {
|
||||
v := c.View.Crafting[s.ID]
|
||||
v.ID = s.ID
|
||||
v.Name = s.Name
|
||||
v.Level, v.XPToNextLevel = content.SkillLevel(s, v.XP)
|
||||
v.LossPercent = w.Balance.Crafting.Rules.Loss(v.Level)
|
||||
c.View.Crafting[s.ID] = v
|
||||
}
|
||||
for _, m := range w.Balance.Crafting.Materials {
|
||||
if c.View.Inventory[m.ID] > 0 {
|
||||
c.View.StackNames[m.ID] = m.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) restoreCrafting(c *Character) error {
|
||||
if len(c.View.Crafting) > 64 || len(c.View.DiscoveredRecipes) > 512 || math.IsNaN(c.CraftReadyAt) || math.IsInf(c.CraftReadyAt, 0) || c.CraftReadyAt < 0 {
|
||||
return errors.New("invalid crafting history")
|
||||
}
|
||||
for _, v := range c.View.Crafting {
|
||||
if v.XP < 0 || v.XP > 1000000000000 {
|
||||
return errors.New("invalid crafting experience")
|
||||
}
|
||||
}
|
||||
for id, r := range c.View.DiscoveredRecipes {
|
||||
if id != r.Recipe.ID || r.Recipe.Revision < 1 || len(r.Recipe.Inputs) > 16 || len(r.Recipe.Outputs) > 8 || len(r.Recipe.Name) > 80 {
|
||||
return errors.New("invalid discovered recipe")
|
||||
}
|
||||
}
|
||||
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{})
|
||||
}
|
||||
|
||||
func ValidateCraftedStacks(inventory map[string]int64, batches []p.CraftedStack, seen map[string]bool) error {
|
||||
if len(batches) > 2048 {
|
||||
return errors.New("too many crafted batches")
|
||||
}
|
||||
totals := map[string]int64{}
|
||||
for _, b := range batches {
|
||||
if b.ID == "" || len(b.ID) > 100 || seen[b.ID] || b.Item == "" || b.Quantity < 1 || b.Quantity > 1000000000000 || !validProvenance(b.Provenance) {
|
||||
return errors.New("invalid crafted provenance or batch")
|
||||
}
|
||||
seen[b.ID] = true
|
||||
totals[b.Item] += b.Quantity
|
||||
if totals[b.Item] > inventory[b.Item] {
|
||||
return errors.New("crafted batches exceed inventory")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func finiteCraft(n float64) bool { return !math.IsNaN(n) && !math.IsInf(n, 0) && n >= 0 }
|
||||
func validProvenance(v p.CraftProvenance) bool {
|
||||
return len(v.CharacterID) == 32 && v.CrafterName != "" && len(v.CrafterName) <= 80 && v.WorldID != "" && len(v.WorldID) <= 128 && v.RecipeID != "" && len(v.RecipeID) <= 64 && v.RecipeRevision >= 1 && v.Profession != "" && len(v.Profession) <= 64 && v.Level >= 1 && v.Level <= 1000 && finiteCraft(v.At)
|
||||
}
|
||||
|
||||
// Consume unmarked units first, then crafted batches in acquisition order.
|
||||
// Splits receive a new batch identity; surviving units retain their provenance.
|
||||
func TakeStack(c *Character, item string, quantity int64) []p.CraftedStack {
|
||||
crafted := int64(0)
|
||||
for _, b := range c.View.CraftedStacks {
|
||||
if b.Item == item {
|
||||
crafted += b.Quantity
|
||||
}
|
||||
}
|
||||
remaining := quantity - min(quantity, max(0, c.View.Inventory[item]-crafted))
|
||||
taken := []p.CraftedStack{}
|
||||
kept := []p.CraftedStack{}
|
||||
for _, b := range c.View.CraftedStacks {
|
||||
if b.Item == item && remaining > 0 {
|
||||
n := min(remaining, b.Quantity)
|
||||
part := b
|
||||
part.Quantity = n
|
||||
if n < b.Quantity {
|
||||
part.ID = ID()
|
||||
}
|
||||
taken = append(taken, part)
|
||||
b.Quantity -= n
|
||||
remaining -= n
|
||||
}
|
||||
if b.Quantity > 0 {
|
||||
kept = append(kept, b)
|
||||
}
|
||||
}
|
||||
c.View.CraftedStacks = kept
|
||||
c.View.Inventory[item] -= quantity
|
||||
if c.View.Inventory[item] == 0 {
|
||||
delete(c.View.Inventory, item)
|
||||
}
|
||||
return taken
|
||||
}
|
||||
func (w *World) checkCraftedWorld(c *Character) error {
|
||||
seen := map[string]bool{}
|
||||
for _, existing := range w.Characters {
|
||||
if existing.View.Entity.ID == c.View.Entity.ID {
|
||||
continue
|
||||
}
|
||||
if e := ValidateCraftedStacks(existing.View.Inventory, existing.View.CraftedStacks, seen); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, seen); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, seen)
|
||||
}
|
||||
func (w *World) CraftProfessions(c *Character) []p.CraftProgress {
|
||||
w.refreshCrafting(c)
|
||||
out := []p.CraftProgress{}
|
||||
for _, s := range w.Balance.Crafting.Professions {
|
||||
out = append(out, c.View.Crafting[s.ID])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The browser offers quantities, never a secret recipe ID. Invalid inventory or
|
||||
// requirement requests do not consume materials or advance the random stream.
|
||||
func (w *World) AttemptCraft(c *Character, req p.CraftRequest) (p.CraftResult, error) {
|
||||
result := p.CraftResult{ID: req.ID, Consumed: map[string]int64{}, Created: []string{}}
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
return result, errors.New("character cannot craft")
|
||||
}
|
||||
now := float64(w.now.UnixMilli()) / 1000
|
||||
if now < c.CraftReadyAt {
|
||||
return result, errors.New("crafting cooldown")
|
||||
}
|
||||
if len(req.Ingredients) < 1 || len(req.Ingredients) > 16 {
|
||||
return result, errors.New("offer 1-16 distinct ingredients")
|
||||
}
|
||||
v := w.Balance.Crafting
|
||||
profession := slices.IndexFunc(v.Professions, func(s content.GatheringSkill) bool { return s.ID == req.Profession })
|
||||
if profession < 0 {
|
||||
return result, errors.New("unknown crafting profession")
|
||||
}
|
||||
for id, n := range req.Ingredients {
|
||||
if id == "" || len(id) > 64 || n < 1 || n > 1000 || c.View.Inventory[id] < n {
|
||||
return result, errors.New("invalid or missing ingredients")
|
||||
}
|
||||
}
|
||||
w.refreshCrafting(c)
|
||||
progress := c.View.Crafting[req.Profession]
|
||||
var recipe *content.CraftRecipe
|
||||
for _, r := range v.Recipes {
|
||||
if r.Profession == req.Profession && maps.Equal(r.Inputs, req.Ingredients) {
|
||||
copy := r
|
||||
recipe = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
if recipe != nil {
|
||||
stats := w.statValues(c, false)
|
||||
for key, n := range recipe.Stats {
|
||||
if stats[key].Final < n {
|
||||
return result, fmt.Errorf("valid recipe; requires %s %.0f (without equipment bonuses); no ingredients spent", key, n)
|
||||
}
|
||||
}
|
||||
for _, id := range recipe.Titles {
|
||||
if !slices.ContainsFunc(c.View.Titles, func(t p.TitleAward) bool { return t.ID == id }) {
|
||||
return result, errors.New("valid recipe; required title missing; no ingredients spent")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Results are constructed on a staged world; persistence failures never publish
|
||||
// this random result or partially spend the live player's ingredients.
|
||||
result.Valid = recipe != nil
|
||||
if recipe != nil {
|
||||
result.Success = !w.roll(v.Rules.Failure(progress.Level, recipe.Level))
|
||||
}
|
||||
rate := v.Rules.Loss(progress.Level)
|
||||
if result.Success {
|
||||
rate = 100
|
||||
}
|
||||
keys := slices.Sorted(maps.Keys(req.Ingredients))
|
||||
for _, id := range keys {
|
||||
n := int64(math.Ceil(float64(req.Ingredients[id]) * rate / 100))
|
||||
n = min(req.Ingredients[id], max(1, n))
|
||||
TakeStack(c, id, n)
|
||||
result.Consumed[id] = n
|
||||
}
|
||||
if recipe != nil {
|
||||
var known p.CraftRecipe
|
||||
raw, _ := json.Marshal(recipe)
|
||||
_ = json.Unmarshal(raw, &known)
|
||||
discovered := p.KnownRecipe{Recipe: known, DiscoveredAt: now}
|
||||
if old, ok := c.View.DiscoveredRecipes[recipe.ID]; ok && old.Recipe.Revision == recipe.Revision {
|
||||
discovered.DiscoveredAt = old.DiscoveredAt
|
||||
}
|
||||
c.View.DiscoveredRecipes[recipe.ID] = discovered
|
||||
result.Recipe = &discovered
|
||||
}
|
||||
if result.Success {
|
||||
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: recipe.ID, RecipeRevision: recipe.Revision, Profession: req.Profession, Level: progress.Level, At: now}
|
||||
for _, id := range slices.Sorted(maps.Keys(recipe.Outputs)) {
|
||||
n := recipe.Outputs[id]
|
||||
before := len(c.View.Items)
|
||||
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, id, n); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if len(c.View.Items) > before {
|
||||
var definition content.ItemDefinition
|
||||
for _, d := range w.Balance.Items {
|
||||
if d.ID == id {
|
||||
definition = d
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := before; i < len(c.View.Items); i++ {
|
||||
item := &c.View.Items[i]
|
||||
copy := provenance
|
||||
item.Provenance = ©
|
||||
item.Modifiers = append(item.Modifiers, w.craftModifiers(definition, progress.Level)...)
|
||||
result.Created = append(result.Created, item.ID)
|
||||
}
|
||||
} else {
|
||||
batch := p.CraftedStack{ID: ID(), Item: id, Quantity: n, Provenance: provenance}
|
||||
c.View.CraftedStacks = append(c.View.CraftedStacks, batch)
|
||||
result.Created = append(result.Created, batch.ID)
|
||||
}
|
||||
}
|
||||
if w.AllowsXP() {
|
||||
progress.XP = min(int64(1000000000000), progress.XP+recipe.XP)
|
||||
c.View.Crafting[req.Profession] = progress
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
}
|
||||
result.Message = "Crafted " + recipe.Name
|
||||
} else if recipe != nil {
|
||||
result.Message = "Valid recipe discovered: " + recipe.Name + ". Craft failed; some ingredients were lost."
|
||||
} else {
|
||||
result.Message = "No recipe matches this combination. Some ingredients were lost."
|
||||
}
|
||||
if err := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{}); err != nil {
|
||||
return result, err
|
||||
}
|
||||
c.CraftReadyAt = now + v.Rules.Cooldown
|
||||
c.Message = result.Message
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return result, nil
|
||||
}
|
||||
func (w *World) craftModifiers(item content.ItemDefinition, level int64) []p.StatModifier {
|
||||
pool := slices.Clone(item.CraftPool)
|
||||
out := []p.StatModifier{}
|
||||
bias := math.Min(w.Balance.Crafting.Rules.MaxQualityBias, 1+float64(level-1)*w.Balance.Crafting.Rules.QualityPerLevel)
|
||||
for range item.CraftRolls {
|
||||
total := float64(0)
|
||||
for _, s := range pool {
|
||||
total += s.Weight
|
||||
}
|
||||
pick := w.randomUnit() * total
|
||||
index := len(pool) - 1
|
||||
for i, s := range pool {
|
||||
pick -= s.Weight
|
||||
if pick < 0 {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
s := pool[index]
|
||||
pool = append(pool[:index], pool[index+1:]...)
|
||||
value := math.Round((s.Min+(s.Max-s.Min)*math.Pow(w.randomUnit(), 1/bias))*100) / 100
|
||||
m := p.StatModifier{Stat: s.Stat}
|
||||
if s.Percent {
|
||||
m.Percent = value
|
||||
} else {
|
||||
m.Flat = value
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ValidCraftRequest(r p.CraftRequest) bool {
|
||||
if len(r.ID) < 32 || len(r.ID) > 36 || len(r.CharacterID) != 32 || len(r.Profession) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, id := range []string{r.ID, r.CharacterID} {
|
||||
if strings.Trim(id, "0123456789abcdef-") != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Existing action regressions use the new ingredient path with a certain success
|
||||
// roll. A staged copy also exercises failure rollback without a transport fixture.
|
||||
func (w *World) craft(c *Character, name string) error {
|
||||
staged := *w
|
||||
staged.Characters = maps.Clone(w.Characters)
|
||||
copy := *c
|
||||
raw, _ := json.Marshal(c.View)
|
||||
var view p.Character
|
||||
_ = json.Unmarshal(raw, &view)
|
||||
copy.View = view
|
||||
staged.Characters[c.View.Entity.ID] = ©
|
||||
content := *w.Balance.Crafting
|
||||
content.Rules.BaseFailure = 0
|
||||
content.Rules.MinFailure = 0
|
||||
content.Rules.MaxFailure = 0
|
||||
staged.Balance.Crafting = &content
|
||||
for _, r := range content.Recipes {
|
||||
if r.ID == "recipe_"+name {
|
||||
_, e := staged.AttemptCraft(©, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: r.Profession, Ingredients: r.Inputs})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
*c = copy
|
||||
w.RandomCounter = staged.RandomCounter
|
||||
w.PendingTitles = staged.PendingTitles
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unknown test recipe %s", name)
|
||||
}
|
||||
|
||||
func TestCraftFailureDiscoveryAndHubRules(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
v := w.Balance.Crafting
|
||||
v.Rules.BaseFailure = 100
|
||||
v.Rules.MinFailure = 100
|
||||
v.Rules.MaxFailure = 100
|
||||
c.View.Inventory["wood"] = 20
|
||||
c.View.Inventory["ore"] = 20
|
||||
req := p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}}
|
||||
beforeXP := c.View.Experience
|
||||
result, e := w.AttemptCraft(c, req)
|
||||
if e != nil || !result.Valid || result.Success || result.Recipe == nil {
|
||||
t.Fatal("valid failed craft was not discovered", result, e)
|
||||
}
|
||||
if c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != beforeXP || c.View.Inventory["wood"] != 17 || c.View.Inventory["ore"] != 18 {
|
||||
t.Fatal("failed craft XP/loss mismatch")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
req.Ingredients = map[string]int64{"wood": 1}
|
||||
result, e = w.AttemptCraft(c, req)
|
||||
if e != nil || result.Valid || result.Success || len(c.View.DiscoveredRecipes) != 1 {
|
||||
t.Fatal("unknown recipe gave discovery", e)
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
v.Rules.BaseFailure = 0
|
||||
v.Rules.MinFailure = 0
|
||||
v.Rules.MaxFailure = 0
|
||||
req.Ingredients = map[string]int64{"wood": 3, "ore": 2}
|
||||
result, e = w.AttemptCraft(c, req)
|
||||
if e != nil || !result.Success {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if c.View.Experience != beforeXP || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Skills["crafting"] != 0 {
|
||||
t.Fatal("hub craft gained XP")
|
||||
}
|
||||
var crafted *p.ItemInstance
|
||||
for i := range c.View.Items {
|
||||
if c.View.Items[i].DefinitionID == "spear" {
|
||||
crafted = &c.View.Items[i]
|
||||
}
|
||||
}
|
||||
fixed := 0
|
||||
for _, item := range w.Balance.Items {
|
||||
if item.ID == "spear" {
|
||||
fixed = len(item.Modifiers)
|
||||
}
|
||||
}
|
||||
if crafted == nil || crafted.Provenance == nil || crafted.Provenance.CrafterName != "Traveler" || crafted.Provenance.WorldID != w.ID || len(crafted.Modifiers) != fixed+1 {
|
||||
t.Fatal("crafted gear missing provenance or stat roll")
|
||||
}
|
||||
before := len(c.View.Items)
|
||||
if _, e = w.AttemptCraft(c, req); e == nil || len(c.View.Items) != before {
|
||||
t.Fatal("cooldown bypass")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCraftedStackSplitDeathLootAndReplacement(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.Crafting.Rules.BaseFailure = 0
|
||||
w.Balance.Crafting.Rules.MinFailure = 0
|
||||
w.Balance.Crafting.Rules.MaxFailure = 0
|
||||
c.View.Inventory["herb"] = 8
|
||||
for i := range w.Balance.Crafting.Recipes {
|
||||
if w.Balance.Crafting.Recipes[i].ID == "recipe_bandage" {
|
||||
w.Balance.Crafting.Recipes[i].Outputs["bandage"] = 3
|
||||
}
|
||||
}
|
||||
if e := w.craft(c, "bandage"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
before := c.View.CraftedStacks[0].Provenance
|
||||
batchID := c.View.CraftedStacks[0].ID
|
||||
if e := w.dropItem(c, "bandage"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var drop *Corpse
|
||||
for _, v := range w.Corpses {
|
||||
drop = v
|
||||
}
|
||||
if drop == nil || drop.CraftedStacks[0].ID == batchID || drop.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Quantity != 2 || !reflect.DeepEqual(drop.CraftedStacks[0].Provenance, before) {
|
||||
t.Fatal("partial drop lost/duplicated provenance")
|
||||
}
|
||||
other, _ := w.Join("other", "Other")
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
if e := w.lootCorpse(other, drop.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !reflect.DeepEqual(other.View.CraftedStacks[0].Provenance, before) {
|
||||
t.Fatal("pickup changed crafter")
|
||||
}
|
||||
w.kill(c, "test")
|
||||
corpse := w.Corpses["corpse:"+c.View.Entity.ID]
|
||||
if len(c.View.CraftedStacks) != 0 || len(corpse.CraftedStacks) != 1 {
|
||||
t.Fatal("death duplicated crafted stock")
|
||||
}
|
||||
if e := w.lootCorpse(other, corpse.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
TakeStack(other, "bandage", 2)
|
||||
if other.View.Inventory["bandage"] != 1 || len(other.View.CraftedStacks) != 1 || other.View.CraftedStacks[0].Quantity != 1 {
|
||||
t.Fatal("consumption left invalid provenance")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
if e := json.Unmarshal(raw, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := restored.Restore(w.now); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement, e := restored.Join(c.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(replacement.View.DiscoveredRecipes) != 0 || replacement.View.Crafting["alchemist"].XP != 0 {
|
||||
t.Fatal("replacement inherited crafting progression")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCraftRequirementsAndQuality(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
for i := range w.Balance.Crafting.Recipes {
|
||||
if w.Balance.Crafting.Recipes[i].ID == "recipe_spear" {
|
||||
w.Balance.Crafting.Recipes[i].Stats = map[string]float64{"strength": 10000}
|
||||
}
|
||||
}
|
||||
counter := w.RandomCounter
|
||||
_, e := w.AttemptCraft(c, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}})
|
||||
if e == nil || w.RandomCounter != counter || c.View.Inventory["wood"] != 3 || len(c.View.DiscoveredRecipes) != 0 {
|
||||
t.Fatal("unmet requirements consumed materials or rolled")
|
||||
}
|
||||
item := w.Balance.Items[1]
|
||||
sumLow, sumHigh := float64(0), float64(0)
|
||||
for range 200 {
|
||||
start := w.RandomCounter
|
||||
low := w.craftModifiers(item, 1)
|
||||
w.RandomCounter = start
|
||||
high := w.craftModifiers(item, 100)
|
||||
if len(low) != 1 || len(high) != 1 || low[0].Stat != high[0].Stat {
|
||||
t.Fatal("pool selection not preserved")
|
||||
}
|
||||
if high[0].Flat < low[0].Flat || math.IsNaN(high[0].Flat) {
|
||||
t.Fatal("higher proficiency worsened corresponding roll")
|
||||
}
|
||||
sumLow += low[0].Flat
|
||||
sumHigh += high[0].Flat
|
||||
}
|
||||
if sumHigh <= sumLow {
|
||||
t.Fatal("quality distribution did not improve")
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,9 @@ func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemIns
|
||||
}
|
||||
func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
for _, item := range items {
|
||||
if item.Provenance != nil && !validProvenance(*item.Provenance) {
|
||||
return errors.New("invalid equipment provenance")
|
||||
}
|
||||
if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 {
|
||||
return errors.New("invalid or duplicate persisted equipment")
|
||||
}
|
||||
@@ -167,6 +170,17 @@ func (w *World) restoreEquipment(c *Character) error {
|
||||
return nil
|
||||
}
|
||||
func (w *World) restoreCorpseEquipment() error {
|
||||
batches := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, c := range w.Corpses {
|
||||
if e := ValidateCraftedStacks(c.Inventory, c.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if err := validateOwnedItems(c.View.Items, seen); err != nil {
|
||||
@@ -294,7 +308,7 @@ func (w *World) dropItem(c *Character, target string) error {
|
||||
if c.View.Inventory[target] < 1 {
|
||||
return errors.New("item not owned")
|
||||
}
|
||||
c.View.Inventory[target]--
|
||||
dropped.CraftedStacks = TakeStack(c, target, 1)
|
||||
if c.View.Inventory[target] == 0 {
|
||||
delete(c.View.Inventory, target)
|
||||
}
|
||||
@@ -318,11 +332,22 @@ func (w *World) lootCorpse(c *Character, target string) error {
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
batches := map[string]bool{}
|
||||
if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
for name, quantity := range corpse.Inventory {
|
||||
if quantity < 0 || c.View.Inventory[name] > math.MaxInt64-quantity {
|
||||
return errors.New("invalid loot quantity")
|
||||
}
|
||||
}
|
||||
if len(c.View.CraftedStacks)+len(corpse.CraftedStacks) > 2048 {
|
||||
return errors.New("crafted batch capacity reached")
|
||||
}
|
||||
c.View.CraftedStacks = append(c.View.CraftedStacks, corpse.CraftedStacks...)
|
||||
for name, quantity := range corpse.Inventory {
|
||||
c.View.Inventory[name] += quantity
|
||||
}
|
||||
@@ -333,6 +358,9 @@ func (w *World) lootCorpse(c *Character, target string) error {
|
||||
return nil
|
||||
}
|
||||
func (w *World) checkImportedEquipment(c *Character) error {
|
||||
if e := w.checkCraftedWorld(c); e != nil {
|
||||
return e
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, existing := range w.Characters {
|
||||
if err := validateOwnedItems(existing.View.Items, seen); err != nil {
|
||||
|
||||
@@ -166,7 +166,7 @@ func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T) {
|
||||
delete(w.Corpses, "legacy")
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
w.Balance.Recipes["spear"] = content.Recipe{Inputs: map[string]int64{"wood": 3, "ore": 2}, Outputs: map[string]int64{"spear": 100001}}
|
||||
w.Balance.Crafting.Recipes[0].Outputs = map[string]int64{"spear": 100001}
|
||||
if w.craft(c, "spear") == nil || c.View.Inventory["wood"] != 3 || c.View.Inventory["ore"] != 2 {
|
||||
t.Fatal("failed craft consumed materials")
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) {
|
||||
return errors.New("too many active gathering effects")
|
||||
}
|
||||
c.View.Inventory[id]--
|
||||
TakeStack(c, id, 1)
|
||||
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: id, Name: v.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
|
||||
w.RefreshStats(c)
|
||||
c.Message = "Used " + v.Name
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestOnlySuccessfulActionsGrantXP(t *testing.T) {
|
||||
t.Fatal("failed gather gained XP")
|
||||
}
|
||||
c.View.Inventory["herb"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 11, Target: "bandage"}); err != nil {
|
||||
if err := w.craft(c, "bandage"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := c.View.Experience
|
||||
|
||||
@@ -89,6 +89,7 @@ func (w *World) RefreshStats(c *Character) {
|
||||
w.revalidateEquipment(c)
|
||||
c.View.Stats = w.statValues(c, true)
|
||||
w.refreshGathering(c)
|
||||
w.refreshCrafting(c)
|
||||
attack := w.playerAttack(c)
|
||||
c.View.Attack = &attack
|
||||
c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final
|
||||
@@ -171,6 +172,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error {
|
||||
if catalog.Combat != nil {
|
||||
w.Balance.Combat = catalog.Combat
|
||||
}
|
||||
if catalog.Crafting != nil {
|
||||
w.Balance.Crafting = catalog.Crafting
|
||||
}
|
||||
w.Balance.Titles = catalog.Titles
|
||||
w.Balance.Items = catalog.Items
|
||||
w.Balance.Stats = &catalog.Stats
|
||||
@@ -188,9 +192,12 @@ func (w *World) roll(chance float64) bool {
|
||||
if chance >= 100 {
|
||||
return true
|
||||
}
|
||||
return w.randomUnit()*100 < chance
|
||||
}
|
||||
func (w *World) randomUnit() float64 {
|
||||
w.RandomCounter++
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%d:%d", w.Seed, w.RandomCounter)))
|
||||
return float64(binary.LittleEndian.Uint64(sum[:8])>>11)/float64(uint64(1)<<53)*100 < chance
|
||||
return float64(binary.LittleEndian.Uint64(sum[:8])>>11) / float64(uint64(1)<<53)
|
||||
}
|
||||
func (w *World) yieldAmount(rate float64) int64 {
|
||||
amount := math.Max(0, math.Min(float64(w.Balance.MaxYieldPerAction), rate/100))
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
CraftReadyAt float64 `json:"craftReadyAt"`
|
||||
AttackReadyAt float64 `json:"attackReadyAt"`
|
||||
JumpVelocity float64 `json:"jumpVelocity"`
|
||||
GatherReadyAt float64 `json:"gatherReadyAt"`
|
||||
@@ -42,9 +42,10 @@ type Character struct {
|
||||
StatsVersion int `json:"statsVersion"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
CraftedStacks []p.CraftedStack `json:"craftedStacks,omitempty"`
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
}
|
||||
type Mob struct {
|
||||
Definition *content.MobDefinition `json:"definition,omitempty"`
|
||||
@@ -186,6 +187,16 @@ func (w *World) Restore(now time.Time) error {
|
||||
if w.ResourceLayouts == nil {
|
||||
w.ResourceLayouts = map[string]ResourceLayout{}
|
||||
}
|
||||
if w.Balance.Crafting == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
cat := content.Catalog{Items: w.Balance.Items}
|
||||
cat.RestoreCrafting(b)
|
||||
w.Balance.Crafting = cat.Crafting
|
||||
w.Balance.Items = cat.Items
|
||||
}
|
||||
if w.Balance.Combat == nil || w.Balance.CombatRules == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
@@ -217,6 +228,9 @@ func (w *World) Restore(now time.Time) error {
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -328,6 +342,9 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -356,6 +373,9 @@ func (w *World) Import(c *Character) error {
|
||||
if err := w.checkImportedEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -501,14 +521,14 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
case "gather":
|
||||
return w.gather(c, i.Target)
|
||||
case "craft":
|
||||
return w.craft(c, i.Target)
|
||||
return errors.New("use the crafting workbench to offer ingredients")
|
||||
case "attack":
|
||||
return w.attack(c, i.Target)
|
||||
case "heal":
|
||||
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
|
||||
return errors.New("no bandage needed or available")
|
||||
}
|
||||
c.View.Inventory["bandage"]--
|
||||
TakeStack(c, "bandage", 1)
|
||||
w.RefreshStats(c)
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
|
||||
w.dirty = true
|
||||
@@ -531,37 +551,6 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) craft(c *Character, name string) error {
|
||||
r, ok := w.Balance.Recipes[name]
|
||||
if !ok {
|
||||
return errors.New("unknown recipe")
|
||||
}
|
||||
for k, v := range r.Inputs {
|
||||
if c.View.Inventory[k] < v {
|
||||
return errors.New("missing crafting materials")
|
||||
}
|
||||
}
|
||||
inventory := maps.Clone(c.View.Inventory)
|
||||
items := append([]p.ItemInstance{}, c.View.Items...)
|
||||
for k, v := range r.Inputs {
|
||||
inventory[k] -= v
|
||||
}
|
||||
for k, v := range r.Outputs {
|
||||
if err := w.addInventoryItems(&inventory, &items, k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.View.Inventory, c.View.Items = inventory, items
|
||||
w.RefreshStats(c)
|
||||
if w.AllowsXP() {
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
}
|
||||
c.Message = "Crafted " + name
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) damageBoss(c *Character, damage float64) {
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
@@ -595,7 +584,8 @@ func (w *World) kill(c *Character, reason string) {
|
||||
e.Kind = "corpse"
|
||||
e.State = "dead"
|
||||
e.HP = 0
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items}
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks}
|
||||
c.View.CraftedStacks = nil
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Items = []p.ItemInstance{}
|
||||
c.View.Equipment = map[string]string{}
|
||||
|
||||
@@ -119,7 +119,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
}
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
|
||||
if err := w.craft(c, "spear"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gearCount(c.View.Items, "spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
|
||||
|
||||
Reference in New Issue
Block a user