pushing current
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
var equipmentSlots = []string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring1", "ring2", "ring3", "ring4", "ring5", "ring6", "ring7", "ring8", "weapon", "offhand", "cape", "bag"}
|
||||
func validEquipmentSlot(slot string) bool {
|
||||
for _, candidate := range equipmentSlots { if slot == candidate { return true } }; return false
|
||||
}
|
||||
func itemFitsSlot(item p.ItemInstance, slot string) bool {
|
||||
if !validEquipmentSlot(slot) { return false }
|
||||
if item.Slot == "ring" { return len(slot) == 5 && slot[:4] == "ring" }; return item.Slot == slot
|
||||
}
|
||||
func ownedItem(c *Character, id string) *p.ItemInstance {
|
||||
for i := range c.View.Items { if c.View.Items[i].ID == id { return &c.View.Items[i] } }; return nil
|
||||
}
|
||||
// Definitions are copied at acquisition; passage cannot replace an owned item.
|
||||
func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemInstance, name string, quantity int64) error {
|
||||
if quantity < 1 { return errors.New("invalid item quantity") }
|
||||
if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} }
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name { continue }
|
||||
if quantity > 100000 { return errors.New("equipment quantity exceeds migration limit") }
|
||||
created := make([]p.ItemInstance, 0, int(quantity))
|
||||
for n := int64(0); n < quantity; n++ {
|
||||
item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight,
|
||||
Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}}
|
||||
for stat, value := range definition.Requirements.Stats { item.Requirements.Stats[stat] = value }
|
||||
for _, modifier := range definition.Modifiers { item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent}) }
|
||||
created = append(created, item)
|
||||
}
|
||||
*items = append(*items, created...); return nil
|
||||
}
|
||||
if (*inventory)[name] > math.MaxInt64-quantity { return errors.New("item quantity overflow") }
|
||||
(*inventory)[name] += quantity; return nil
|
||||
}
|
||||
func (w *World) grantItems(c *Character, name string, quantity int64) error {
|
||||
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, name, quantity); err != nil { return err }
|
||||
w.RefreshStats(c); w.dirty = true; return nil
|
||||
}
|
||||
func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemInstance) error {
|
||||
if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} }
|
||||
names := make([]string, 0, len(*inventory))
|
||||
for name, quantity := range *inventory { if quantity < 0 { return errors.New("negative persisted inventory") }; names = append(names, name) }; sort.Strings(names)
|
||||
for _, name := range names {
|
||||
quantity := (*inventory)[name]
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name { continue }
|
||||
if quantity > 0 { if err := w.addInventoryItems(inventory, items, name, quantity); err != nil { return err } }
|
||||
delete(*inventory, name); w.dirty = true; break
|
||||
}
|
||||
}; return nil
|
||||
}
|
||||
func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
for _, item := range items {
|
||||
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")
|
||||
}
|
||||
seen[item.ID] = true
|
||||
for _, value := range item.Requirements.Stats { if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { return errors.New("invalid equipment requirement") } }
|
||||
for _, modifier := range item.Modifiers { if modifier.Stat == "" || math.IsNaN(modifier.Flat) || math.IsInf(modifier.Flat, 0) || math.IsNaN(modifier.Percent) || math.IsInf(modifier.Percent, 0) { return errors.New("invalid equipment modifier") } }
|
||||
}; return nil
|
||||
}
|
||||
func (w *World) restoreEquipment(c *Character) error {
|
||||
if err := w.migrateEquipment(&c.View.Inventory, &c.View.Items); err != nil { return err }
|
||||
if c.View.Equipment == nil { c.View.Equipment = map[string]string{} }
|
||||
if err := validateOwnedItems(c.View.Items, map[string]bool{}); err != nil { return err }
|
||||
seen := map[string]bool{}
|
||||
for slot, id := range c.View.Equipment {
|
||||
item := ownedItem(c, id)
|
||||
if item == nil || !itemFitsSlot(*item, slot) || seen[id] { return errors.New("invalid persisted equipment assignment") }; seen[id] = true
|
||||
}
|
||||
if c.View.Entity.State == "dead" && (len(c.View.Items) != 0 || len(c.View.Equipment) != 0) { return errors.New("dead character still owns equipment") }; return nil
|
||||
}
|
||||
func (w *World) restoreCorpseEquipment() error {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range w.Characters { if err := validateOwnedItems(c.View.Items, seen); err != nil { return err } }
|
||||
for _, corpse := range w.Corpses {
|
||||
if err := w.migrateEquipment(&corpse.Inventory, &corpse.Items); err != nil { return err }
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil { return err }
|
||||
}; return nil
|
||||
}
|
||||
@@ -31,10 +31,26 @@ func (w *World) orderedCharacters() []*Character {
|
||||
}
|
||||
|
||||
func (w *World) restoreProgression(c *Character) error {
|
||||
if c.View.Level == 0 {
|
||||
c.View.Level = 1
|
||||
}
|
||||
if c.Progression == nil {
|
||||
rules := *w.Balance.Progression
|
||||
c.Progression = &rules
|
||||
}
|
||||
if c.StatsVersion == 0 {
|
||||
rules := *c.Progression
|
||||
if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel {
|
||||
c.View.StatPoints += (c.View.Level - 1) * (w.Balance.Progression.StatPointsPerLevel - rules.StatPointsPerLevel)
|
||||
}
|
||||
rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel
|
||||
rules.StaminaPerLevel = w.Balance.Progression.StaminaPerLevel
|
||||
rules.VitalPointsPerChoice = w.Balance.Progression.VitalPointsPerChoice
|
||||
c.Progression = &rules
|
||||
c.View.PendingVitalChoices = c.View.Level - 1
|
||||
c.StatsVersion = 1
|
||||
w.dirty = true
|
||||
}
|
||||
if err := c.Progression.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -65,13 +81,16 @@ func (w *World) grantXP(c *Character, amount int64) {
|
||||
if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel {
|
||||
return
|
||||
}
|
||||
amount = int64(math.Min(1000000000, math.Floor(float64(amount)*c.View.Stats["xpGain"].Final/100)))
|
||||
c.View.Experience += amount
|
||||
before := c.View.Level
|
||||
for c.View.Level < c.Progression.MaxLevel && c.View.Experience >= c.nextLevelXP() {
|
||||
c.View.Experience -= c.nextLevelXP()
|
||||
c.View.Level++
|
||||
c.View.StatPoints += c.Progression.StatPointsPerLevel
|
||||
c.View.PendingVitalChoices++
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
c.View.ExperienceToNextLevel = c.nextLevelXP()
|
||||
if c.View.ExperienceToNextLevel == 0 {
|
||||
c.View.Experience = 0
|
||||
@@ -101,6 +120,9 @@ func (w *World) evaluateTitles(c *Character) {
|
||||
}
|
||||
return 0
|
||||
default:
|
||||
if value, ok := c.View.Stats[name]; ok {
|
||||
return int64(math.Floor(value.Final))
|
||||
}
|
||||
return c.View.Skills[name]
|
||||
}
|
||||
}
|
||||
@@ -136,7 +158,7 @@ func (w *World) evaluateTitles(c *Character) {
|
||||
}
|
||||
w.PendingTitles = append(w.PendingTitles, TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{
|
||||
ID: title.ID, Name: title.Name, Description: title.Description, Scope: title.Scope, WorldID: w.ID,
|
||||
EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed},
|
||||
EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed, Modifiers: protocolModifiers(title.Effects.Modifiers)},
|
||||
}})
|
||||
w.dirty = true
|
||||
}
|
||||
@@ -158,5 +180,5 @@ func (c *Character) titleEffects() p.TitleEffects {
|
||||
}
|
||||
|
||||
func (w *World) playerSpeed(c *Character) float64 {
|
||||
return math.Max(0, w.Balance.PlayerSpeed+c.titleEffects().MoveSpeed)
|
||||
return c.View.Stats["moveSpeed"].Final
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func protocolModifiers(in []content.StatModifier) []p.StatModifier {
|
||||
out := make([]p.StatModifier, 0, len(in))
|
||||
for _, m := range in {
|
||||
out = append(out, p.StatModifier{Stat: m.Stat, Flat: m.Flat, Percent: m.Percent})
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (w *World) statValues(c *Character, equipment bool) map[string]p.StatValue {
|
||||
modifiers := []p.StatModifier{}
|
||||
seen := map[string]bool{}
|
||||
for _, title := range c.View.Titles {
|
||||
if seen[title.ID] {
|
||||
continue
|
||||
}
|
||||
seen[title.ID] = true
|
||||
modifiers = append(modifiers, title.Effects.Modifiers...)
|
||||
modifiers = append(modifiers, p.StatModifier{Stat: "meleeDamage", Flat: title.Effects.Damage}, p.StatModifier{Stat: "moveSpeed", Flat: title.Effects.MoveSpeed})
|
||||
}
|
||||
if equipment {
|
||||
ids := map[string]bool{}
|
||||
for _, id := range c.View.Equipment {
|
||||
ids[id] = true
|
||||
}
|
||||
for _, item := range c.View.Items {
|
||||
if ids[item.ID] {
|
||||
modifiers = append(modifiers, item.Modifiers...)
|
||||
}
|
||||
}
|
||||
}
|
||||
values := map[string]p.StatValue{}
|
||||
finish := func(key string, base float64) {
|
||||
v := p.StatValue{Base: base}
|
||||
for _, m := range modifiers {
|
||||
if m.Stat == key {
|
||||
v.Flat += m.Flat
|
||||
v.Percent += m.Percent
|
||||
}
|
||||
}
|
||||
v.Final = math.Max(0, (v.Base+v.Flat)*math.Max(0, 1+v.Percent/100))
|
||||
if key == "healthPoints" {
|
||||
v.Final = math.Max(50, v.Final)
|
||||
}
|
||||
if key == "criticalChance" || key == "dodgeChance" {
|
||||
v.Final = math.Min(100, v.Final)
|
||||
}
|
||||
values[key] = v
|
||||
}
|
||||
for _, key := range content.PrimaryStats {
|
||||
finish(key, w.Balance.Stats.Base[key]+float64(c.View.AllocatedStats[key]))
|
||||
}
|
||||
for _, key := range content.DerivedStats {
|
||||
base := w.Balance.Stats.Base[key]
|
||||
for _, primary := range content.PrimaryStats {
|
||||
base += values[primary].Final * w.Balance.Stats.Coefficients[primary][key]
|
||||
}
|
||||
switch key {
|
||||
case "healthPoints":
|
||||
base += float64(c.View.HealthChoices * c.Progression.VitalPointsPerChoice)
|
||||
case "manaPoints":
|
||||
base += float64(c.View.ManaChoices * c.Progression.VitalPointsPerChoice)
|
||||
case "stamina":
|
||||
base += float64((c.View.Level - 1) * c.Progression.StaminaPerLevel)
|
||||
}
|
||||
finish(key, base)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// Requirements exclude every equipment bonus to prevent self/cyclic enabling.
|
||||
func (w *World) RequirementStats(c *Character) map[string]p.StatValue { return w.statValues(c, false) }
|
||||
func (w *World) RefreshStats(c *Character) {
|
||||
if c.View.Entity.State == "dead" && len(c.View.Stats) > 0 {
|
||||
return
|
||||
}
|
||||
w.revalidateEquipment(c)
|
||||
c.View.Stats = w.statValues(c, true)
|
||||
c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.HP, c.View.Entity.MaxHP)
|
||||
c.View.Mana = math.Max(0, math.Min(c.View.Mana, c.View.Stats["manaPoints"].Final))
|
||||
c.View.Stamina = math.Max(0, math.Min(c.View.Stamina, c.View.Stats["stamina"].Final))
|
||||
c.View.CarryWeight = 0
|
||||
for _, item := range c.View.Items {
|
||||
c.View.CarryWeight += item.Weight
|
||||
}
|
||||
// Stack quantities have unit weight in this first inventory version.
|
||||
for _, n := range c.View.Inventory {
|
||||
c.View.CarryWeight += float64(n)
|
||||
}
|
||||
}
|
||||
func (w *World) initializeStats(c *Character) error {
|
||||
newResources := c.View.Stats == nil
|
||||
if c.View.AllocatedStats == nil {
|
||||
c.View.AllocatedStats = map[string]int64{}
|
||||
}
|
||||
spent := int64(0)
|
||||
for key, n := range c.View.AllocatedStats {
|
||||
if !slices.Contains(content.PrimaryStats, key) || n < 0 || n > 10000000 {
|
||||
return errors.New("invalid allocated stats")
|
||||
}
|
||||
}
|
||||
for _, n := range c.View.AllocatedStats {
|
||||
spent += n
|
||||
}
|
||||
if spent+c.View.StatPoints != (c.View.Level-1)*c.Progression.StatPointsPerLevel {
|
||||
return errors.New("allocated and unspent points do not match earned levels")
|
||||
}
|
||||
if c.View.PendingVitalChoices < 0 || c.View.HealthChoices < 0 || c.View.ManaChoices < 0 || c.View.PendingVitalChoices+c.View.HealthChoices+c.View.ManaChoices != c.View.Level-1 {
|
||||
return errors.New("invalid level reward choices")
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
if newResources && c.View.Entity.State != "dead" {
|
||||
c.View.Mana = c.View.Stats["manaPoints"].Final
|
||||
c.View.Stamina = c.View.Stats["stamina"].Final
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) allocateStat(c *Character, key string) error {
|
||||
if !slices.Contains(content.PrimaryStats, key) || c.View.StatPoints < 1 {
|
||||
return errors.New("choose a primary stat with an available point")
|
||||
}
|
||||
c.View.AllocatedStats[key]++
|
||||
c.View.StatPoints--
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) chooseVital(c *Character, key string) error {
|
||||
if c.View.PendingVitalChoices < 1 || (key != "health" && key != "mana") {
|
||||
return errors.New("no pending health or mana choice")
|
||||
}
|
||||
if key == "health" {
|
||||
c.View.HealthChoices++
|
||||
} else {
|
||||
c.View.ManaChoices++
|
||||
}
|
||||
c.View.PendingVitalChoices--
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) ApplyCatalog(catalog content.Catalog) error {
|
||||
if catalog.Version <= w.CatalogVersion {
|
||||
return nil
|
||||
}
|
||||
if err := catalog.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.Titles = catalog.Titles
|
||||
w.Balance.Items = catalog.Items
|
||||
w.Balance.Stats = &catalog.Stats
|
||||
w.CatalogVersion = catalog.Version
|
||||
for _, c := range w.orderedCharacters() {
|
||||
w.RefreshStats(c)
|
||||
}
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) roll(chance float64) bool {
|
||||
if chance <= 0 {
|
||||
return false
|
||||
}
|
||||
if chance >= 100 {
|
||||
return true
|
||||
}
|
||||
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
|
||||
}
|
||||
func (w *World) yieldAmount(rate float64) int64 {
|
||||
amount := math.Max(0, math.Min(100, rate/100))
|
||||
n := int64(math.Floor(amount))
|
||||
if w.roll((amount - float64(n)) * 100) {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
func (w *World) damageCharacter(c *Character, amount float64) {
|
||||
if w.roll(c.View.Stats["dodgeChance"].Final) {
|
||||
return
|
||||
}
|
||||
c.View.Entity.HP -= math.Max(0, amount-c.View.Stats["defence"].Final)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func TestLevelRewardsAndPrimaryAllocation(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
w.grantXP(c,100)
|
||||
if c.View.Level!=2||c.View.StatPoints!=10||c.View.PendingVitalChoices!=1||c.View.Stats["stamina"].Final!=105{t.Fatalf("wrong level rewards: %+v",c.View)}
|
||||
for i:=0;i<3;i++{if err:=w.allocateStat(c,"constitution");err!=nil{t.Fatal(err)}}
|
||||
if c.View.StatPoints!=7||c.View.Stats["constitution"].Final!=3||c.View.Entity.MaxHP!=115{t.Fatal("constitution did not update derived health")}
|
||||
if err:=w.chooseVital(c,"health");err!=nil{t.Fatal(err)}
|
||||
if c.View.Entity.MaxHP!=120||c.View.HealthChoices!=1||c.View.PendingVitalChoices!=0{t.Fatal("health choice not applied")}
|
||||
if w.chooseVital(c,"mana")==nil||w.allocateStat(c,"healthPoints")==nil{t.Fatal("duplicate vital or direct derived allocation accepted")}
|
||||
w.grantXP(c,150)
|
||||
if err:=w.chooseVital(c,"mana");err!=nil{t.Fatal(err)}
|
||||
if c.View.Stats["manaPoints"].Final!=55||c.View.Stats["stamina"].Final!=110||c.View.StatPoints!=17{t.Fatal("second level rewards incorrect")}
|
||||
for c.View.StatPoints>0 {if err:=w.allocateStat(c,"dexterity");err!=nil{t.Fatal(err)}}
|
||||
before:=c.View.Stats["dexterity"].Final
|
||||
if w.allocateStat(c,"dexterity")==nil||c.View.Stats["dexterity"].Final!=before{t.Fatal("overspent banked points")}
|
||||
}
|
||||
|
||||
func TestStatBreakdownUsesEffectivePrimaryThenFlatAndPercent(t *testing.T) {
|
||||
w,c:=fixture(t);w.grantXP(c,100)
|
||||
for i:=0;i<4;i++{if err:=w.allocateStat(c,"strength");err!=nil{t.Fatal(err)}}
|
||||
c.View.Titles=[]p.TitleAward{{ID:"mixed",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"strength",Flat:2,Percent:50},{Stat:"meleeDamage",Flat:3,Percent:20},{Stat:"moveSpeed",Percent:-25}}}}}
|
||||
w.RefreshStats(c)
|
||||
strength:=c.View.Stats["strength"]
|
||||
if strength.Base!=4||strength.Flat!=2||strength.Percent!=50||strength.Final!=9{t.Fatalf("bad primary breakdown: %+v",strength)}
|
||||
damage:=c.View.Stats["meleeDamage"]
|
||||
if damage.Base!=27||damage.Flat!=3||damage.Percent!=20||math.Abs(damage.Final-36)>1e-8{t.Fatalf("bad derived breakdown: %+v",damage)}
|
||||
if w.playerSpeed(c)!=9{t.Fatal("negative percentage movement not applied")}
|
||||
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"curse",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"healthPoints",Percent:-100},{Stat:"moveSpeed",Percent:-100}}}})
|
||||
w.RefreshStats(c)
|
||||
if c.View.Entity.MaxHP!=50||w.playerSpeed(c)!=0{t.Fatal("vital safety floor or zero speed bound failed")}
|
||||
}
|
||||
|
||||
func TestStatsMigrationAndTransferPreserveEarnedRewards(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
c.View.Level=3;c.View.Experience=25;c.View.StatPoints=10;c.StatsVersion=0
|
||||
c.View.AllocatedStats=nil;c.View.Stats=nil;c.View.PendingVitalChoices=0
|
||||
old:=*c.Progression;old.StatPointsPerLevel=5;old.StaminaPerLevel=0;old.VitalPointsPerChoice=0;c.Progression=&old
|
||||
w.Balance.Stats=nil
|
||||
c.DailySeconds=321
|
||||
raw,err:=json.Marshal(w);if err!=nil{t.Fatal(err)}
|
||||
var restored World;if err=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)}
|
||||
if err=restored.Restore(w.now);err!=nil{t.Fatal(err)}
|
||||
migrated:=restored.Characters[c.View.Entity.ID]
|
||||
if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2||migrated.View.Stats["stamina"].Final!=110||migrated.DailySeconds!=321{t.Fatal("legacy level rewards not migrated once")}
|
||||
if err=restored.Restore(w.now);err!=nil{t.Fatal(err)}
|
||||
if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2{t.Fatal("repeated restore duplicated rewards")}
|
||||
if err=restored.allocateStat(migrated,"wisdom");err!=nil{t.Fatal(err)}
|
||||
if err=restored.chooseVital(migrated,"mana");err!=nil{t.Fatal(err)}
|
||||
migrated.View.Entity.State="eligible"
|
||||
next:=New("stats-next",999,w.now,restored.Balance)
|
||||
if err=next.Import(migrated);err!=nil{t.Fatal(err)}
|
||||
if migrated.View.StatPoints!=19||migrated.View.AllocatedStats["wisdom"]!=1||migrated.View.PendingVitalChoices!=1||migrated.View.ManaChoices!=1||migrated.DailySeconds!=321{t.Fatal("transfer altered rewards or daily budget")}
|
||||
next.kill(migrated,"test")
|
||||
if next.Connect(migrated.View.Entity.ID)==nil{t.Fatal("stat feature resurrected a life")}
|
||||
if next.Intent(migrated.View.Entity.ID,p.Intent{Op:"allocate-stat",Target:"strength",Seq:1})==nil{t.Fatal("dead life allocated a point")}
|
||||
}
|
||||
|
||||
func TestCatalogChangesDoNotHealOrRewriteDeadStats(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
dead,err:=w.Join("dead-stats","Dead");if err!=nil{t.Fatal(err)}
|
||||
w.kill(dead,"test")
|
||||
prior:=dead.View.Stats["healthPoints"].Final
|
||||
c.View.Entity.HP=20;c.DailySeconds=123
|
||||
catalog,err:=content.DefaultCatalog();if err!=nil{t.Fatal(err)}
|
||||
catalog.Version=2;catalog.Stats.Base["healthPoints"]=200
|
||||
if err=w.ApplyCatalog(catalog);err!=nil{t.Fatal(err)}
|
||||
if c.View.Entity.MaxHP!=200||c.View.Entity.HP!=20||c.DailySeconds!=123||dead.View.Entity.State!="dead"||dead.View.Stats["healthPoints"].Final!=prior{t.Fatal("catalog changed life/budget/history")}
|
||||
w.Balance.DailyPlaySeconds=124
|
||||
w.Advance(w.now.Add(2*time.Second),2)
|
||||
if c.Online||c.View.RemainingSeconds!=0||c.View.Entity.HP!=50{t.Fatal("expanded stats weakened daily cap")}
|
||||
}
|
||||
@@ -34,10 +34,12 @@ type Character struct {
|
||||
WorldKills int64 `json:"worldKills"`
|
||||
BossKills int64 `json:"bossKills"`
|
||||
WorldsSurvived int64 `json:"worldsSurvived"`
|
||||
StatsVersion int `json:"statsVersion"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
}
|
||||
type Mob struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
@@ -63,6 +65,8 @@ type World struct {
|
||||
Mobs map[string]*Mob `json:"mobs"`
|
||||
Balance content.Balance `json:"balance"`
|
||||
PendingTitles []TitleCandidate `json:"-"`
|
||||
CatalogVersion int64 `json:"catalogVersion"`
|
||||
RandomCounter uint64 `json:"randomCounter"`
|
||||
terrain *Terrain
|
||||
chunks map[string]p.Chunk
|
||||
now time.Time
|
||||
@@ -98,6 +102,26 @@ func (w *World) Restore(now time.Time) error {
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Balance.Stats == nil {
|
||||
defaults, err := content.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.Stats = defaults.Stats
|
||||
w.Balance.Items = defaults.Items
|
||||
rules := *w.Balance.Progression
|
||||
rules.StatPointsPerLevel = defaults.Progression.StatPointsPerLevel
|
||||
rules.StaminaPerLevel = defaults.Progression.StaminaPerLevel
|
||||
rules.VitalPointsPerChoice = defaults.Progression.VitalPointsPerChoice
|
||||
w.Balance.Progression = &rules
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Balance.CriticalMultiplier == 0 {
|
||||
defaults, err := content.Load()
|
||||
if err != nil { return err }
|
||||
w.Balance.CriticalMultiplier = defaults.CriticalMultiplier
|
||||
w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -112,6 +136,12 @@ func (w *World) Restore(now time.Time) error {
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.initializeStats(c); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
@@ -205,6 +235,8 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
for k, v := range w.Balance.StartingKit {
|
||||
c.View.Inventory[k] = v
|
||||
}
|
||||
if err := w.restoreEquipment(c); err != nil { return nil, err }
|
||||
if err := w.initializeStats(c); err != nil { return nil, err }
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
c.BornAt = w.now
|
||||
w.evaluateTitles(c)
|
||||
@@ -221,6 +253,8 @@ func (w *World) Import(c *Character) error {
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreEquipment(c); err != nil { return err }
|
||||
if err := w.initializeStats(c); err != nil { return err }
|
||||
pos, err := w.spawn("")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -307,15 +341,25 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
|
||||
return errors.New("invalid input sequence")
|
||||
}
|
||||
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 {
|
||||
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 || len(i.Slot) > 30 {
|
||||
return errors.New("invalid intent")
|
||||
}
|
||||
c.View.ACK = i.Seq
|
||||
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) {
|
||||
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal" && i.Op != "allocate-stat" && i.Op != "choose-vital" && i.Op != "equip" && i.Op != "unequip" && i.Op != "drop")) {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
}
|
||||
switch i.Op {
|
||||
case "allocate-stat":
|
||||
return w.allocateStat(c, i.Target)
|
||||
case "choose-vital":
|
||||
return w.chooseVital(c, i.Target)
|
||||
case "equip":
|
||||
return w.equip(c, i.Target, i.Slot)
|
||||
case "unequip":
|
||||
return w.unequip(c, i.Target)
|
||||
case "drop":
|
||||
return w.dropItem(c, i.Target)
|
||||
case "move":
|
||||
n := math.Max(1, math.Hypot(i.X, i.Z))
|
||||
c.MoveX = i.X / n
|
||||
@@ -333,6 +377,7 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
return errors.New("no bandage needed or available")
|
||||
}
|
||||
c.View.Inventory["bandage"]--
|
||||
w.RefreshStats(c)
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
|
||||
w.dirty = true
|
||||
case "return":
|
||||
@@ -347,15 +392,7 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
c.View.HasKeystone = false
|
||||
w.dirty = true
|
||||
case "loot":
|
||||
corpse := w.Corpses[i.Target]
|
||||
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
|
||||
return errors.New("corpse out of reach")
|
||||
}
|
||||
for k, v := range corpse.Inventory {
|
||||
c.View.Inventory[k] += v
|
||||
}
|
||||
delete(w.Corpses, i.Target)
|
||||
w.dirty = true
|
||||
return w.lootCorpse(c, i.Target)
|
||||
default:
|
||||
return errors.New("unknown intent")
|
||||
}
|
||||
@@ -380,7 +417,7 @@ func (w *World) gather(c *Character, target string) error {
|
||||
if item == "" {
|
||||
return errors.New("not gatherable")
|
||||
}
|
||||
c.View.Inventory[item]++
|
||||
c.View.Inventory[item] += w.yieldAmount(c.View.Stats["gatherRate"].Final)
|
||||
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
|
||||
c.LastGather = w.Age()
|
||||
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
|
||||
@@ -407,8 +444,9 @@ func (w *World) craft(c *Character, name string) error {
|
||||
c.View.Inventory[k] -= v
|
||||
}
|
||||
for k, v := range r.Outputs {
|
||||
c.View.Inventory[k] += v
|
||||
if err := w.grantItems(c, k, v); err != nil { return err }
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
c.Message = "Crafted " + name
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
@@ -420,15 +458,14 @@ func (w *World) attack(c *Character, target string) error {
|
||||
if w.Age()-c.LastAttack < w.Balance.AttackCooldown {
|
||||
return errors.New("attack cooldown")
|
||||
}
|
||||
damage := w.Balance.PlayerDamage
|
||||
if c.View.Inventory["spear"] > 0 {
|
||||
damage = w.Balance.SpearDamage
|
||||
}
|
||||
damage = math.Max(0, damage+c.titleEffects().Damage)
|
||||
damage := c.View.Stats["meleeDamage"].Final
|
||||
if target == "boss" {
|
||||
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
|
||||
return errors.New("boss out of reach")
|
||||
}
|
||||
if w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
damage *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
c.BossKills++
|
||||
@@ -454,13 +491,21 @@ func (w *World) attack(c *Character, target string) error {
|
||||
if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
if w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
damage *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
m.Entity.HP = math.Max(0, m.Entity.HP-damage)
|
||||
if m.Entity.HP == 0 {
|
||||
m.Entity.State = "dead"
|
||||
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
|
||||
c.View.Kills++
|
||||
c.WorldKills++
|
||||
c.View.Inventory["herb"]++
|
||||
c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final)
|
||||
for _, item := range w.Balance.Items {
|
||||
if w.roll(item.DropChance*c.View.Stats["dropRate"].Final/100) {
|
||||
if err := w.grantItems(c, item.ID, 1); err != nil { return err }
|
||||
}
|
||||
}
|
||||
w.grantXP(c, w.Balance.Progression.MobKillXP)
|
||||
}
|
||||
}
|
||||
@@ -479,8 +524,11 @@ 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}
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items}
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Items = []p.ItemInstance{}
|
||||
c.View.Equipment = map[string]string{}
|
||||
c.View.CarryWeight = 0
|
||||
c.View.Entity.HP = 0
|
||||
c.View.Entity.State = "dead"
|
||||
c.MoveX = 0
|
||||
@@ -579,6 +627,9 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
}
|
||||
if c.Online {
|
||||
if c.View.Entity.HP > 0 { c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+c.View.Stats["healthRecovery"].Final*dt) }
|
||||
c.View.Mana = math.Min(c.View.Stats["manaPoints"].Final, c.View.Mana+c.View.Stats["manaRecovery"].Final*dt)
|
||||
c.View.Stamina = math.Min(c.View.Stats["stamina"].Final, c.View.Stamina+c.View.Stats["staminaRecovery"].Final*dt)
|
||||
// A generous window: the client resends its move intent well under this on every
|
||||
// rendered frame, but a slow/throttled frame (e.g. software-rendered CI) shouldn't
|
||||
// zero out in-flight movement and strand a walk-to-target action mid-course.
|
||||
@@ -610,7 +661,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
||||
for _, c := range characters {
|
||||
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
|
||||
c.View.Entity.HP -= w.Balance.BossDamage
|
||||
w.damageCharacter(c, w.Balance.BossDamage)
|
||||
w.dirty = true
|
||||
if c.View.Entity.HP <= 0 {
|
||||
w.kill(c, "The Harbinger ended this character's journey.")
|
||||
@@ -700,7 +751,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
}
|
||||
if nearest <= w.Balance.MobAttackRange {
|
||||
if w.Age()-m.LastAttack >= w.Balance.MobCooldown {
|
||||
target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
w.damageCharacter(target, w.Balance.MobDamage*(1+w.Age()/86400*w.Balance.MobScalePerDay))
|
||||
m.LastAttack = w.Age()
|
||||
w.dirty = true
|
||||
if target.View.Entity.HP <= 0 {
|
||||
|
||||
@@ -9,6 +9,7 @@ type Protocol struct {
|
||||
type Intent struct {
|
||||
Op string `json:"op"`
|
||||
Seq int64 `json:"seq"`
|
||||
Slot string `json:"slot"`
|
||||
Target string `json:"target"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
@@ -55,19 +56,61 @@ type Vec3 struct {
|
||||
}
|
||||
|
||||
type Character struct {
|
||||
ACK int64 `json:"ack"`
|
||||
Entity Entity `json:"entity"`
|
||||
Experience int64 `json:"experience"`
|
||||
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Kills int64 `json:"kills"`
|
||||
Level int64 `json:"level"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
RemainingSeconds float64 `json:"remainingSeconds"`
|
||||
Skills map[string]int64 `json:"skills"`
|
||||
StatPoints int64 `json:"statPoints"`
|
||||
Titles []TitleAward `json:"titles"`
|
||||
ACK int64 `json:"ack"`
|
||||
AllocatedStats map[string]int64 `json:"allocatedStats"`
|
||||
CarryWeight float64 `json:"carryWeight"`
|
||||
Entity Entity `json:"entity"`
|
||||
Equipment map[string]string `json:"equipment"`
|
||||
Experience int64 `json:"experience"`
|
||||
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
HealthChoices int64 `json:"healthChoices"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []ItemInstance `json:"items"`
|
||||
Kills int64 `json:"kills"`
|
||||
Level int64 `json:"level"`
|
||||
Mana float64 `json:"mana"`
|
||||
ManaChoices int64 `json:"manaChoices"`
|
||||
PendingVitalChoices int64 `json:"pendingVitalChoices"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
RemainingSeconds float64 `json:"remainingSeconds"`
|
||||
Skills map[string]int64 `json:"skills"`
|
||||
Stamina float64 `json:"stamina"`
|
||||
StatPoints int64 `json:"statPoints"`
|
||||
Stats map[string]StatValue `json:"stats"`
|
||||
Titles []TitleAward `json:"titles"`
|
||||
}
|
||||
|
||||
type ItemInstance struct {
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
RequirementMessage string `json:"requirementMessage"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type StatModifier struct {
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
}
|
||||
|
||||
type StatValue struct {
|
||||
Base float64 `json:"base"`
|
||||
Final float64 `json:"final"`
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
}
|
||||
|
||||
type TitleAward struct {
|
||||
@@ -81,8 +124,9 @@ type TitleAward struct {
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
Damage float64 `json:"damage"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type WorldInfo struct {
|
||||
|
||||
@@ -217,7 +217,7 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
|
||||
}
|
||||
l.Revision++
|
||||
for id, c := range w.Characters {
|
||||
live.Characters[id].View.Titles = c.View.Titles
|
||||
live.Characters[id].View = c.View
|
||||
}
|
||||
live.PendingTitles = nil
|
||||
live.Saved()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"sort"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
@@ -19,6 +20,10 @@ func stageTitleWorld(w *game.World) *game.World {
|
||||
for id, c := range w.Characters {
|
||||
copy := *c
|
||||
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
|
||||
copy.View.Items = append([]p.ItemInstance{}, c.View.Items...)
|
||||
copy.View.Equipment = maps.Clone(c.View.Equipment)
|
||||
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
|
||||
copy.View.Stats = maps.Clone(c.View.Stats)
|
||||
staged.Characters[id] = ©
|
||||
}
|
||||
return &staged
|
||||
@@ -96,6 +101,7 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
}
|
||||
if c.View.Entity.State != "dead" {
|
||||
c.View.Titles = append([]p.TitleAward{}, awards...)
|
||||
w.RefreshStats(c)
|
||||
continue
|
||||
}
|
||||
// A historical dead life keeps its own record. Only awards from its death
|
||||
|
||||
@@ -178,6 +178,10 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
view.Inventory = maps.Clone(view.Inventory)
|
||||
view.Skills = maps.Clone(view.Skills)
|
||||
view.Titles = append([]p.TitleAward{}, view.Titles...)
|
||||
view.Items = append([]p.ItemInstance{}, view.Items...)
|
||||
view.Equipment = maps.Clone(view.Equipment)
|
||||
view.Stats = maps.Clone(view.Stats)
|
||||
view.AllocatedStats = maps.Clone(view.AllocatedStats)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user