Add item actions, targeting, bindings, and encumbrance

This commit is contained in:
dingo
2026-09-10 20:57:36 -04:00
parent 32955eca09
commit 9b01ee38e3
38 changed files with 1297 additions and 77 deletions
+5
View File
@@ -153,6 +153,11 @@ func (w *World) attack(c *Character, target string) error {
return errors.New("area effect limit reached")
}
power := c.View.Stats[a.Stat].Final * a.Multiplier
// Coatings add damage to this weapon attack, so they use the same server
// collision, defence and credit rules. Spells do not inherit weapon coatings.
if i := ownedItem(c, c.View.Equipment["weapon"]); a.Effect == "damage" && i != nil && i.Coating != nil && i.Coating.ExpiresAt > float64(w.now.UnixMilli())/1000 {
power += i.Coating.Damage
}
if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) {
power *= w.Balance.CriticalMultiplier
}
+3
View File
@@ -42,6 +42,9 @@ func (w *World) refreshCrafting(c *Character) {
}
}
func (w *World) restoreCrafting(c *Character) error {
if !finiteCraft(c.ItemReadyAt) {
return errors.New("invalid item cooldown")
}
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")
}
+12 -5
View File
@@ -133,6 +133,11 @@ 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 v := item.Coating; v != nil {
if item.Slot != "weapon" || item.HouseID != nil || item.Furniture != nil || v.Name == "" || len(v.Name) > 100 || v.Source == "" || len(v.Source) > 100 || !finiteCraft(v.ExpiresAt) || v.ExpiresAt <= 0 || !finiteCraft(v.Damage) || v.Damage <= 0 || v.Damage > 10000 {
return errors.New("invalid weapon coating")
}
}
if item.Provenance != nil && !validProvenance(*item.Provenance) {
return errors.New("invalid equipment provenance")
}
@@ -281,14 +286,16 @@ func (w *World) equip(c *Character, itemID, slot string) error {
if c.View.Equipment == nil {
c.View.Equipment = map[string]string{}
}
if c.View.Equipment[slot] != "" {
return errors.New("unequip the occupied slot first")
}
for _, id := range c.View.Equipment {
for equippedSlot, id := range c.View.Equipment {
if id == itemID {
return errors.New("item is already equipped")
if equippedSlot == slot {
return nil
}
delete(c.View.Equipment, equippedSlot)
}
}
// Both items remain owned. The displaced item is already in Items and returns
// to the bag when its equipment assignment is replaced.
c.View.Equipment[slot] = itemID
w.RefreshStats(c)
w.evaluateTitles(c)
+2 -2
View File
@@ -46,8 +46,8 @@ func TestEquipmentSlotsAndRequirements(t *testing.T) {
if w.equip(c, "missing", "weapon") == nil || w.equip(c, "slot_ring1", "ring9") == nil {
t.Fatal("invalid ownership/slot accepted")
}
if w.equip(c, "slot_ring1", "ring2") == nil {
t.Fatal("same instance equipped twice")
if w.equip(c, "slot_ring1", "ring2") != nil || c.View.Equipment["ring1"] != "" || c.View.Equipment["ring2"] != "slot_ring1" || ownedItem(c, "slot_ring2") == nil {
t.Fatal("ring swap duplicated assignment or lost displaced item")
}
if err := w.unequip(c, "helmet"); err != nil {
t.Fatal(err)
+11 -1
View File
@@ -121,7 +121,11 @@ func (w *World) refreshGathering(c *Character) {
for _, v := range w.Balance.Gathering.Consumables {
if c.View.Inventory[v.ID] > 0 {
c.View.StackNames[v.ID] = v.Name
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
var effect *p.ItemUseEffect
if v.UseEffect != nil {
effect = &p.ItemUseEffect{Kind: v.UseEffect.Kind, Amount: v.UseEffect.Amount}
}
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers), UseEffect: effect})
}
}
}
@@ -247,6 +251,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
}
for _, v := range w.Balance.Gathering.Consumables {
if v.ID == id {
if v.UseEffect != nil {
return errors.New("use this item through its targeted item action")
}
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")
}
@@ -261,6 +268,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
return errors.New("unknown gathering consumable")
}
func (w *World) jump(c *Character) error {
if w.EncumbranceFactor(c) == 0 {
return errors.New("too encumbered to jump")
}
ground := w.floorAt(c.View.Entity.Position.X, c.View.Entity.Position.Z, c.View.Entity.Position.Y)
if c.JumpVelocity != 0 || c.View.Entity.Position.Y > ground+0.05 {
return errors.New("already airborne")
+7 -3
View File
@@ -76,6 +76,9 @@ func (w *World) houseIntent(c *Character, i p.Intent) error {
c.LastMove = w.now
return nil
case "jump":
if w.EncumbranceFactor(c) == 0 {
return errors.New("too encumbered to jump")
}
if math.Abs(c.View.HousePosition.Y-roomGround(c.HouseRoom, *c.View.HousePosition)) > .02 || c.JumpVelocity != 0 {
return errors.New("already jumping")
}
@@ -94,8 +97,9 @@ func (w *World) moveHouse(c *Character, dt float64) {
old := *c.View.HousePosition
pos := old
r := w.Balance.Housing
speed := r.WalkSpeed * w.EncumbranceFactor(c)
// Small substeps prevent tunneling through narrow furniture on a delayed tick.
steps := max(1, int(math.Ceil(dt*r.WalkSpeed/.1)))
steps := max(1, int(math.Ceil(dt*speed/.1)))
step := dt / float64(steps)
for range steps {
if c.JumpVelocity != 0 || pos.Y > roomGround(room, pos) {
@@ -108,12 +112,12 @@ func (w *World) moveHouse(c *Character, dt float64) {
c.JumpVelocity = math.Min(0, c.JumpVelocity)
}
next := pos
next.X += c.MoveX * r.WalkSpeed * step
next.X += c.MoveX * speed * step
if w.HousePositionValid(room, next) {
pos.X = next.X
}
next = pos
next.Z += c.MoveZ * r.WalkSpeed * step
next.Z += c.MoveZ * speed * step
if w.HousePositionValid(room, next) {
pos.Z = next.Z
}
+242
View File
@@ -0,0 +1,242 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"strings"
)
func ValidItemAction(r p.ItemActionRequest) bool {
return len(r.ID) >= 32 && len(r.ID) <= 36 && strings.Trim(r.ID, "0123456789abcdef-") == "" && len(r.CharacterID) == 32 && strings.Trim(r.CharacterID, "0123456789abcdef") == "" && len(r.Item) > 0 && len(r.Item) <= 100 && len(r.Target) <= 100 && len(r.Slot) <= 64 && r.Quantity >= 1 && r.Quantity <= 1000 && slices.Contains([]string{"equip", "destroy", "breakdown", "consume", "use"}, r.Op)
}
// Invoked only on a staged world; the store commits the result and replay receipt
// together before returning it to the browser.
func (w *World) ItemAction(c *Character, r p.ItemActionRequest) (p.ItemActionResult, error) {
out := p.ItemActionResult{ID: r.ID, Returned: map[string]int64{}}
if !ValidItemAction(r) || c == nil || c.View.Entity.ID != r.CharacterID || !c.Online || c.Sheltered || HouseID(c) != "" || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
return out, errors.New("character cannot use items")
}
now := float64(w.now.UnixMilli()) / 1000
if now < c.ItemReadyAt {
return out, errors.New("item action cooldown")
}
item := ownedItem(c, r.Item)
if item == nil && c.View.Inventory[r.Item] < r.Quantity {
return out, errors.New("item not owned in that quantity")
}
if item != nil && r.Quantity != 1 {
return out, errors.New("equipment actions require one instance")
}
if r.Op != "use" && r.Target != "" || r.Op != "equip" && r.Slot != "" {
return out, errors.New("unexpected item target or slot")
}
var err error
switch r.Op {
case "equip":
if r.Quantity != 1 {
return out, errors.New("equip one item")
}
err = w.equip(c, r.Item, r.Slot)
out.Message = "Equipment updated"
case "destroy":
if item != nil {
if item.HouseID != nil {
return out, errors.New("house keys require the three-second key destruction action")
}
w.removeOwnedItem(c, item.ID)
} else {
TakeStack(c, r.Item, r.Quantity)
}
out.Message = "Item destroyed"
case "breakdown":
if item == nil {
return out, errors.New("only equipment can be broken down")
}
err = w.breakdown(c, *item, &out)
case "consume", "use":
if r.Quantity != 1 {
return out, errors.New("use one item at a time")
}
err = w.useItem(c, r.Item, r.Target, r.Op == "consume")
out.Message = "Item used"
}
if err != nil {
return out, err
}
c.ItemReadyAt = now + w.Balance.Inventory.ActionCooldown
w.RefreshStats(c)
c.Message = out.Message
w.dirty = true
return out, nil
}
func (w *World) removeOwnedItem(c *Character, id string) {
c.View.Items = slices.DeleteFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id })
for slot, item := range c.View.Equipment {
if item == id {
delete(c.View.Equipment, slot)
}
}
}
func (w *World) breakdownRecipe(item p.ItemInstance) *content.CraftRecipe {
if item.HouseID != nil || item.Furniture != nil || w.Balance.Crafting == nil {
return nil
}
if item.Provenance != nil {
for _, list := range [][]content.CraftRecipe{w.Balance.Crafting.Recipes, w.Balance.Crafting.RecipeHistory} {
for _, r := range list {
if r.ID == item.Provenance.RecipeID && r.Revision == item.Provenance.RecipeRevision && r.Outputs[item.DefinitionID] > 0 {
copy := r
return &copy
}
}
}
return nil // Never substitute a later recipe revision for the original.
}
var found *content.CraftRecipe
for _, r := range w.Balance.Crafting.Recipes {
if r.Outputs[item.DefinitionID] > 0 {
if found != nil {
return nil
}
copy := r
found = &copy
}
}
return found
}
func (w *World) breakdown(c *Character, item p.ItemInstance, out *p.ItemActionResult) error {
r := w.breakdownRecipe(item)
if r == nil {
return errors.New("no unambiguous original recipe is available for this item")
}
profession := r.Profession
if item.Slot == "weapon" {
profession = "weapon_smithing"
} else if slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "cape"}, item.Slot) {
profession = "armor_making"
}
w.refreshCrafting(c)
level := c.View.Crafting[profession].Level
if level < 1 {
return errors.New("breakdown profession unavailable")
}
rules := w.Balance.Inventory
gap := float64(level - max(r.Level, item.Requirements.Level))
rate := rules.BreakdownBase
if gap < 0 {
rate *= math.Exp(gap / rules.BreakdownLevelScale)
} else {
rate += (rules.BreakdownMax - rate) * (1 - math.Exp(-gap/rules.BreakdownLevelScale))
}
units := int64(0)
for _, n := range r.Outputs {
units += n
}
if units < 1 {
return errors.New("invalid original recipe")
}
for id, n := range r.Inputs {
// Divide by the complete output batch: breaking down each output cannot
// multiply the batch's inputs. Return material stacks only.
if slices.ContainsFunc(w.Balance.Items, func(i content.ItemDefinition) bool { return i.ID == id }) {
return errors.New("equipment ingredients cannot be recovered by breakdown")
}
amount := int64(math.Floor(float64(n) * rate / 100 / float64(units)))
if amount > 0 {
if c.View.Inventory[id] > math.MaxInt64-amount {
return errors.New("inventory overflow")
}
out.Returned[id] = amount
}
}
if len(c.View.DiscoveredRecipes) >= 512 {
if _, ok := c.View.DiscoveredRecipes[r.ID]; !ok {
return errors.New("recipe discovery capacity reached")
}
}
w.removeOwnedItem(c, item.ID)
for id, n := range out.Returned {
c.View.Inventory[id] += n
}
if w.roll(rules.RecipeChance) {
old, known := c.View.DiscoveredRecipes[r.ID]
if !known || old.Recipe.Revision < r.Revision {
raw, _ := json.Marshal(r)
var recipe p.CraftRecipe
_ = json.Unmarshal(raw, &recipe)
d := p.KnownRecipe{Recipe: recipe, DiscoveredAt: float64(w.now.UnixMilli()) / 1000}
c.View.DiscoveredRecipes[r.ID] = d
out.Recipe = &d
}
}
out.Message = fmt.Sprintf("Broke down %s (%.1f%% recovery, rounded down)", item.Name, rate)
if out.Recipe != nil {
out.Message += "; recipe discovered"
}
return nil
}
func (w *World) useItem(c *Character, id, target string, consume bool) error {
if target == "" || consume {
target = c.View.Entity.ID
}
if c.View.Inventory[id] < 1 {
return errors.New("this item has no supported use effect")
}
healing := float64(0)
if id == "bandage" {
healing = w.Balance.BandageHealing
}
for _, definition := range w.Balance.Gathering.Consumables {
if definition.ID != id || definition.UseEffect == nil {
continue
}
effect := definition.UseEffect
if effect.Kind == "heal" {
healing = effect.Amount
}
if effect.Kind == "weapon-coating" {
weapon := ownedItem(c, target)
if consume || weapon == nil || weapon.Slot != "weapon" || weapon.Furniture != nil || weapon.HouseID != nil || (weapon.Attack != nil && weapon.Attack.Effect != "damage") {
return errors.New("select one of your damage weapons to apply this coating")
}
TakeStack(c, id, 1)
weapon.Coating = &p.WeaponCoating{Source: id, Name: definition.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + definition.Seconds, Damage: effect.Amount}
return nil
}
}
if healing > 0 {
var entity *p.Entity
if other := w.Characters[target]; other != nil && other.Online && !other.Sheltered && HouseID(other) == "" && other.View.Entity.State == "alive" {
entity = &other.View.Entity
}
if mob := w.Mobs[target]; mob != nil && mob.Entity.HP > 0 && !w.IsHub() {
entity = &mob.Entity
}
if entity == nil || entity.HP >= entity.MaxHP {
return errors.New("target cannot be healed")
}
if length3(body(c.View.Entity.Position), body(entity.Position)) > w.Balance.GatherRange {
return errors.New("target out of reach")
}
if _, blocked := w.combatLine(body(c.View.Entity.Position), body(entity.Position), ""); blocked {
return errors.New("target obstructed")
}
TakeStack(c, id, 1)
entity.HP = math.Min(entity.MaxHP, entity.HP+healing)
return nil
}
if target != c.View.Entity.ID {
return errors.New("this item can only be used on yourself")
}
return w.consumeGathering(c, id)
}
+266
View File
@@ -0,0 +1,266 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"math"
"reflect"
"testing"
"time"
)
func itemRequest(c *Character, op, item string) p.ItemActionRequest {
return p.ItemActionRequest{ID: ID(), CharacterID: c.View.Entity.ID, Op: op, Item: item, Quantity: 1}
}
func TestDestroyConsumesCraftedStackWithoutLosingRemainingProvenance(t *testing.T) {
w, c := fixture(t)
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: "recipe_bandage", RecipeRevision: 1, Profession: "alchemist", Level: 1}
c.View.Inventory["bandage"] = 3
c.View.CraftedStacks = []p.CraftedStack{{ID: ID(), Item: "bandage", Quantity: 3, Provenance: provenance}}
req := itemRequest(c, "destroy", "bandage")
req.Quantity = 2
for _, mode := range []string{"offline", "sheltered", "dead", "capped"} {
c.Online = true
c.Sheltered = false
c.View.Entity.State = "alive"
c.View.RemainingSeconds = 100
switch mode {
case "offline":
c.Online = false
case "sheltered":
c.Sheltered = true
case "dead":
c.View.Entity.State = "dead"
case "capped":
c.View.RemainingSeconds = 0
}
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 3 {
t.Fatalf("accepted %s destruction", mode)
}
}
c.Online = true
c.Sheltered = false
c.View.Entity.State = "alive"
c.View.RemainingSeconds = 100
if _, err := w.ItemAction(c, req); err != nil {
t.Fatal(err)
}
if c.View.Inventory["bandage"] != 1 || len(c.View.CraftedStacks) != 1 || c.View.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Provenance != provenance {
t.Fatal("destroy corrupted retained crafted stack")
}
req = itemRequest(c, "destroy", "bandage")
req.Quantity = 2
c.ItemReadyAt = 0
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 1 {
t.Fatal("destroyed more than owned")
}
w.Balance.Inventory = nil
raw, _ := json.Marshal(w)
var old World
_ = json.Unmarshal(raw, &old)
if err := old.Restore(w.now); err != nil || old.Balance.Inventory == nil || old.Balance.Inventory.StopWeightRatio != 2 {
t.Fatal("old snapshot missing inventory migration", err)
}
}
func TestEncumbranceMovementRecoveryAndVictory(t *testing.T) {
w, c := fixture(t)
c.View.Inventory = map[string]int64{}
c.View.Items = nil
w.RefreshStats(c)
capacity := c.View.Stats["carryCapacity"].Final
for _, tt := range []struct{ ratio, factor float64 }{{0, 1}, {1, 1}, {1.1, .99}, {1.5, .75}, {2, 0}, {3, 0}} {
item := testGear("weight", "helmet")
item.Weight = capacity * tt.ratio
c.View.Items = []p.ItemInstance{item}
w.RefreshStats(c)
if math.Abs(w.playerSpeed(c)/c.View.Stats["moveSpeed"].Final-tt.factor) > 1e-8 || math.Abs(*c.View.MovementFactor-tt.factor) > 1e-8 {
t.Fatalf("wrong movement at %.1fx capacity", tt.ratio)
}
}
before := c.View.Entity.Position
c.MoveX = 1
w.moveCharacter(c, .1)
if c.View.Entity.Position.X != before.X || w.jump(c) == nil {
t.Fatal("immobilized player moved or jumped")
}
w.Kind = "hub"
w.Phase = "hub"
house := ID()
pos := p.Vec3{}
c.View.HouseID = &house
c.View.HousePosition = &pos
c.HouseRoom = &p.HouseScene{ID: house, Size: 20}
c.LastMove = w.now
w.moveHouse(c, .1)
if c.View.HousePosition.X != 0 || w.houseIntent(c, p.Intent{Op: "jump"}) == nil {
t.Fatal("house bypassed encumbrance")
}
c.View.HouseID = nil
c.View.HousePosition = nil
c.HouseRoom = nil
w.Kind = "survival"
w.Phase = "won"
c.View.Entity.State = "eligible"
if err := w.Intent(c.View.Entity.ID, p.Intent{Seq: 1, Op: "drop", Target: "weight"}); err != nil {
t.Fatal("winner cannot shed weight to reach portal", err)
}
if w.EncumbranceFactor(c) != 1 {
t.Fatal("dropping weight did not restore movement")
}
}
func TestItemActionsRejectWithoutConsumptionAndHealTargets(t *testing.T) {
w, c := fixture(t)
c.View.Inventory["bandage"] = 5
other, err := w.Join("other", "Other")
if err != nil {
t.Fatal(err)
}
_ = w.Connect(other.View.Entity.ID)
other.View.Entity.Position = c.View.Entity.Position
other.View.Entity.HP = 1
req := itemRequest(c, "use", "bandage")
req.Target = other.View.Entity.ID
for _, mode := range []string{"far", "dead", "sheltered", "house", "full"} {
other.View.Entity.Position = c.View.Entity.Position
other.View.Entity.State = "alive"
other.Sheltered = false
other.View.HouseID = nil
other.View.Entity.HP = 1
switch mode {
case "far":
other.View.Entity.Position.X += 100
case "dead":
other.View.Entity.State = "dead"
case "sheltered":
other.Sheltered = true
case "house":
other.View.HouseID = stringPtr(ID())
case "full":
other.View.Entity.HP = other.View.Entity.MaxHP
}
if _, err = w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 5 {
t.Fatalf("accepted invalid healing target %s", mode)
}
}
other.View.Entity.HP = 1
if _, err = w.ItemAction(c, req); err != nil || other.View.Entity.HP != math.Min(other.View.Entity.MaxHP, 1+w.Balance.BandageHealing) || c.View.Inventory["bandage"] != 4 {
t.Fatal("targeted healing failed", err)
}
if _, err = w.ItemAction(c, req); err == nil {
t.Fatal("item cooldown bypassed")
}
w.now = w.now.Add(2 * time.Second)
mob := &Mob{Entity: p.Entity{ID: "heal-target", Kind: "mob", State: "alive", HP: 1, MaxHP: 100, Position: c.View.Entity.Position}}
w.Mobs[mob.Entity.ID] = mob
req.Target = mob.Entity.ID
if _, err = w.ItemAction(c, req); err != nil || mob.Entity.HP <= 1 {
t.Fatal("mob healing failed", err)
}
w.now = w.now.Add(2 * time.Second)
key := testGear("key", "bag")
key.HouseID = stringPtr(ID())
c.View.Items = append(c.View.Items, key)
if _, err = w.ItemAction(c, itemRequest(c, "destroy", key.ID)); err == nil || ownedItem(c, key.ID) == nil {
t.Fatal("generic destruction bypassed key timer")
}
}
func TestBreakdownOriginalRecipeBatchAndDiscovery(t *testing.T) {
w, c := fixture(t)
c.View.Inventory = map[string]int64{}
old := content.CraftRecipe{ID: "original", Revision: 1, Name: "Old spear", Profession: "weapon_smithing", Level: 1, XP: 20, Inputs: map[string]int64{"wood": 100, "ore": 20}, Outputs: map[string]int64{"spear": 2}}
current := old
current.Revision = 2
current.Inputs = map[string]int64{"herb": 100}
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
w.Balance.Crafting.Recipes = []content.CraftRecipe{current}
item := testGear("old-spear", "weapon")
item.DefinitionID = "spear"
item.Provenance = &p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, Profession: old.Profession, Level: 1, RecipeID: old.ID, RecipeRevision: 1}
c.View.Items = []p.ItemInstance{item}
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
// Find a deterministic success for the actual 0.01% boundary, not a modified rule.
for w.randomUnit() >= .0001 {
}
w.RandomCounter--
result, err := w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
if err != nil || c.View.Inventory["wood"] != 12 || c.View.Inventory["ore"] != 2 || c.View.Inventory["herb"] != 0 || len(c.View.Items) != 0 {
t.Fatal("breakdown did not use original recipe divided by output batch", result, err)
}
if result.Recipe == nil || result.Recipe.Recipe.Revision != 1 || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != 0 {
t.Fatal("wrong discovery or unexpected experience")
}
w.now = w.now.Add(2 * time.Second)
c.View.Items = []p.ItemInstance{item}
w.Balance.Crafting.RecipeHistory = nil
if _, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID)); err == nil || len(c.View.Items) != 1 {
t.Fatal("missing historical recipe substituted current revision")
}
// In a hub, high crafting skill raises recovery but never awards XP.
w.Kind = "hub"
w.Phase = "hub"
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
cp := c.View.Crafting["weapon_smithing"]
cp.XP = 1000000
c.View.Crafting[cp.ID] = cp
result, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
if err != nil || result.Returned["wood"] <= 12 || result.Returned["wood"] >= 38 || c.View.Crafting[cp.ID].XP != cp.XP {
t.Fatal("higher skill recovery or hub XP changed", result, err)
}
}
func TestConsumableCoatingOwnershipExpiryAndRestore(t *testing.T) {
w, c := fixture(t)
definition := content.GatheringConsumable{ID: "poison", Name: "Weapon poison", Seconds: 10, UseEffect: &content.ItemUseEffect{Kind: "weapon-coating", Amount: 7}}
w.Balance.Gathering.Consumables = append(w.Balance.Gathering.Consumables, definition)
c.View.Inventory[definition.ID] = 2
weapon := testGear("coated", "weapon")
c.View.Items = append(c.View.Items, weapon)
req := itemRequest(c, "use", definition.ID)
req.Target = "not-owned"
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory[definition.ID] != 2 {
t.Fatal("coated unowned weapon")
}
req.Target = weapon.ID
if _, err := w.ItemAction(c, req); err != nil {
t.Fatal(err)
}
coating := ownedItem(c, weapon.ID).Coating
if coating == nil || coating.Damage != 7 || c.View.Inventory[definition.ID] != 1 {
t.Fatal("coating was not copied onto exact item")
}
if err := w.consumeGathering(c, definition.ID); err == nil {
t.Fatal("legacy consume bypassed target requirement")
}
raw, _ := json.Marshal(w)
var restored World
_ = json.Unmarshal(raw, &restored)
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ownedItem(restored.Characters[c.View.Entity.ID], weapon.ID).Coating, coating) {
t.Fatal("restore lost coating")
}
_ = w.equip(c, weapon.ID, "weapon")
w.Balance.CriticalMultiplier = 1
mob := &Mob{Entity: p.Entity{ID: "damage-target", Kind: "mob", State: "alive", HP: 1000, MaxHP: 1000, Position: c.View.Entity.Position}}
w.Mobs[mob.Entity.ID] = mob
w.now = w.now.Add(2 * time.Second)
if err := w.attack(c, mob.Entity.ID); err != nil {
t.Fatal(err)
}
coatedDamage := 1000 - mob.Entity.HP
w.now = w.now.Add(20 * time.Second)
mob.Entity.HP = 1000
if err := w.attack(c, mob.Entity.ID); err != nil {
t.Fatal(err)
}
normalDamage := 1000 - mob.Entity.HP
if math.Abs(coatedDamage-normalDamage-7) > 1e-8 {
t.Fatal("coating damage did not expire", coatedDamage, normalDamage)
}
}
+14 -1
View File
@@ -198,5 +198,18 @@ func (c *Character) titleEffects() p.TitleEffects {
}
func (w *World) playerSpeed(c *Character) float64 {
return c.View.Stats["moveSpeed"].Final
return c.View.Stats["moveSpeed"].Final * w.EncumbranceFactor(c)
}
// Apply after all speed/capacity modifiers, so gear cannot override immobilization.
func (w *World) EncumbranceFactor(c *Character) float64 {
capacity, weight := c.View.Stats["carryCapacity"].Final, c.View.CarryWeight
if weight <= capacity {
return 1
}
if capacity <= 0 {
return 0
}
excess := (weight/capacity - 1) / (w.Balance.Inventory.StopWeightRatio - 1)
return math.Max(0, 1-math.Pow(excess, w.Balance.Inventory.SlowdownExponent))
}
+2
View File
@@ -105,6 +105,8 @@ func (w *World) RefreshStats(c *Character) {
for _, n := range c.View.Inventory {
c.View.CarryWeight += float64(n)
}
factor := w.EncumbranceFactor(c)
c.View.MovementFactor = &factor
}
func (w *World) initializeStats(c *Character) error {
newResources := c.View.Stats == nil
+13 -1
View File
@@ -14,6 +14,7 @@ import (
)
type Character struct {
ItemReadyAt float64 `json:"itemReadyAt"`
HouseRoom *p.HouseScene `json:"-"`
XPCurveVersion int `json:"xpCurveVersion"`
PendingCast *PendingCast `json:"pendingCast,omitempty"`
@@ -124,6 +125,17 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World {
return w
}
func (w *World) Restore(now time.Time) error {
if w.Balance.Inventory == nil {
defaults, err := content.Load()
if err != nil {
return err
}
w.Balance.Inventory = defaults.Inventory
w.dirty = true
}
if err := w.Balance.Inventory.Validate(); err != nil {
return err
}
if w.Kind == "" {
w.Kind = "survival"
}
@@ -533,7 +545,7 @@ func (w *World) Intent(id string, i p.Intent) error {
c.Sheltered = false
w.dirty = true
}
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" {
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" && i.Op != "drop" {
return errors.New("use the victory portal to continue")
}
if w.IsHub() && (i.Op == "attack" || i.Op == "gather") {