tiny-adventure / commits / 9cd98bf
Longer days, scarcer loot, item bases with their own stats, and keys that open the boss
A day is now 140 time with a 40 time night, and a fight costs 8. Chests drop from 10 to 14 down to 6 to 9, and the per-enemy drop chance from 35% to 20%. Enemies hit harder. Each item base has its own stat profile with flat penalties, and each rarity has one prefix, so two items with the same name have the same stats. Quest items are now boss keys in party.keys. Every main step after the first recovers one, and a barred boss lists the missing keys in threat.needs. /api/move takes steps to stop after N hexes, and GET /api/path previews a walk. The careful bot weighs expected wounds and saves the boss for last. It wins 19 of 20 seeds in about 9 days, and the Go balance guard now expects 70%. Co-Authored-By: Claude Opus 5.5
@@ -49,18 +49,19 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
4949 }
5050 ],
5151 "inventory": [],
52+ "keys": [],
5253 "x": 0,
5354 "y": 0,
5455 "gold": 0
5556 },
5657 "log": [],
5758 "phase": "explore",
58- "clock": {"day": 1, "time": 0, "dayLength": 60, "nightLength": 30},
59+ "clock": {"day": 1, "time": 0, "dayLength": 140, "nightLength": 40},
5960 "summary": {"battles": 0, "kills": 0, "loot": 0, "steps": 0, "seconds": 0}
6061 }
6162 ```
6263
63-Combat resolves instantly on the server, so `phase` is never left at `combat`. After a fight `encounter` (`Encounter`) and `log` describe it until the next move or interact. `summary.seconds` is the elapsed play time, frozen at victory or defeat. The boss POI only starts its fight once all other main steps are done. A `retrieve` step completes once its POI is cleared and the key item is in the inventory.
64+Combat resolves instantly on the server, so `phase` is never left at `combat`. After a fight `encounter` (`Encounter`) and `log` describe it until the next move or interact. `summary.seconds` is the elapsed play time, frozen at victory or defeat. The boss POI only starts its fight once all other main steps are done. Every main step after the first is a `retrieve` step. It completes once its POI is cleared and its key is in `party.keys`. Keys never enter the inventory and cannot be equipped or so …
6465
6566 Optional fields: `encounter` (`Encounter`, present after a fight), `rewards` (`Rewards`, present after a won fight), `found` (items auto-collected by the latest move or interact, cleared on the next action), `threat` (`Threat`, see `/api/move`), `shop` (`Shop`, present while the party stands where a trader works), `winner` (player id, set at `victory`).
6667
@@ -68,7 +69,7 @@ A lost fight sets `phase: "defeat"` and every hero's `hp` to 0. The campaign is
6869
6970 ## Clock
7071
71-`clock.time` counts from 0 at dawn. Walking a hex spends its walking cost, and a fight spends 6. Night starts at `dayLength` and lasts `nightLength`. Dawn after a night with no rest starts the next `day` without healing. At night roaming bands move on every step and chase from farther away.
72+`clock.time` counts from 0 at dawn. Walking a hex spends its walking cost, and a fight spends 8. Night starts at `dayLength` and lasts `nightLength`. Dawn after a night with no rest starts the next `day` without healing. At night roaming bands move on every step and chase from farther away.
7273
7374 Each POI has a `level`, the enemy level of its fight. The boss is one level higher. Levels rise with the distance from the spawn, up to about 5 at the boss.
7475
@@ -141,14 +142,22 @@ Moves the party toward hex `x,y`. The server paths over walkable hexes and retur
141142 {"band": "band1", "enemies": [], "odds": 64, "wounds": 50, "edge": {"hits": [], "blunted": ["frost (Cael)"]}}
142143 ```
143144
144-`odds` is the percent of 40 simulated fights the party wins as it stands now. `wounds` is the average percent of the party's current health lost in those fights. `barred` is true for the boss until every other main step is done. `edge` names each hero whose element or pierce hits an enemy weakness, and each whose element the enemies resist. Start the fight with `POST /api/interact` on the POI or band id. Any other action clears `threat`. Loot on any tile the party walks over is picked up automat …
145+`odds` is the percent of 40 simulated fights the party wins as it stands now. `wounds` is the average percent of the party's current health lost in those fights. `barred` is true for the boss until every other main step is done, and `needs` then lists the names of the keys still missing. `edge` names each hero whose element or pierce hits an enemy weakness, and each whose element the enemies resist. Start the fight with `POST /api/interact` on the POI or band id. Any other action clears `threat` …
145146
146147 ```json
147-{"x": 12, "y": 7}
148+{"x": 12, "y": 7, "steps": 1}
148149 ```
149150
150151 Response: `GameState` with updated `party.x`, `party.y`, and possibly `threat`.
151152
153+## GET /api/path
154+
155+Previews the walk to `?x=&y=` without taking it. It does not change the state and returns a `Route`, not a `GameState`. `path` lists the hexes the party would walk, stopping before the first uncleared POI or band, which `blocked` names. `time` is the daylight the walk spends, and `dusk` is true when night falls on the way. Roaming bands move during a real walk, so the route can still change. Rejected with 400 for a bad query or an unreachable tile.
156+
157+```json
158+{"path": [[12, 7], [13, 7]], "time": 5, "dusk": false}
159+```
160+
152161 ## POST /api/interact
153162
154163 Interacts with a POI, band, loot node, or spawn structure by id (`poi1`, `band1`, `chest1`, `sp1`). Collects loot, advances mission steps, or starts the POI or band encounter. Moving already collects loot on the path, so this is only needed for loot the party stands on and has not collected, and it fails with 400 for loot already collected.
@@ -23,7 +23,7 @@ Needs `go`, `node`, `ffmpeg` (for the recording), `python3`, and `agent-browser`
2323 scripts/playthrough.sh <outdir> <seed> [width height name]
2424 ```
2525
26-Plays one full campaign on `<seed>` through input only, with the careful bot from `scripts/bot.mjs`: it fights a threat at 80% odds or better and backs off otherwise, levels up on easier places and bands, drinks or buys potions by day, and walks until dusk to make camp when hurt. On the first threat card it clicks Prepare and clicks pack items that beat the equipped ones. It records `<name>.webm`, saves screenshots and `<name>.md`/`<name>.json`, and exits non-zero on any failed step, a client an …
26+Plays one full campaign on `<seed>` through input only, with the careful bot from `scripts/bot.mjs`: it fights a threat at 80% odds or better and backs off otherwise, also backs off from a fight that would cost over half its health while hurt, saves the boss until nothing else is left or the party is at full health, levels up on easier places and bands, drinks or buys potions by day, and walks until dusk to make camp when hurt. On the first threat card it clicks Prepare and clicks pack items tha …
2727
2828 ## Output
2929
@@ -32,7 +32,7 @@ func enemy(r *rand.Rand, id string, l look, f model.Faction, level int, hpMult,
3232 }
3333
3434 const (
35- hpBase, hpGrow, atkBase, atkGrow = 22, 9, 9, 4
35+ hpBase, hpGrow, atkBase, atkGrow = 22, 11, 11, 5
3636 bossHP, bossAtk = 1.7, 1.1
3737 swarmHP, swarmAtk = 0.65, 0.8
3838 )
@@ -16,7 +16,7 @@ const (
1616
1717 func placeLoot(p *placer, maxDist int, byPower []model.Faction) []model.Band {
1818 var bands []model.Band
19- for _, c := range p.take(rng.Between(p.r, 10, 14), 4, func([2]int) bool { return true }) {
19+ for _, c := range p.take(rng.Between(p.r, 6, 9), 4, func([2]int) bool { return true }) {
2020 lv := levelAt(p.origin, maxDist, c[0], c[1])
2121 id := fmt.Sprintf("chest%d", len(p.m.Loot)+1)
2222 roll := p.r.IntN(100)
@@ -13,14 +13,10 @@ var mainTemplates = []string{"hunt", "relic", "siege"}
1313 var sideNames = []string{"A Favor for the Hamlet", "Lost and Found", "Bounty Posted", "The Quiet Errand"}
1414
1515 func kindsFor(sys Systems) []string {
16- k := []string{"reach"}
1716 if sys.Factions {
18- k = append(k, "defeat")
17+ return []string{"reach", "defeat"}
1918 }
20- if sys.KeyItems {
21- k = append(k, "retrieve")
22- }
23- return k
19+ return []string{"reach"}
2420 }
2521
2622 type questBuilder struct {
@@ -40,7 +36,7 @@ func (q *questBuilder) step(id string, kind string, poi model.POI) model.Mission
4036 s.Text = fmt.Sprintf("Drive the %s out of %s", f.Name, poi.Name)
4137 case "retrieve":
4238 q.n++
43- it := makeKeyItem(q.r, q.n, q.names[q.n%len(q.names)])
39+ it := makeKeyItem(q.n, q.names[q.n%len(q.names)])
4440 q.keys = append(q.keys, it)
4541 s.Slots.Item = it.ID
4642 s.Text = fmt.Sprintf("Recover the %s from %s", it.Name, poi.Name)
@@ -56,7 +52,10 @@ func (q *questBuilder) main(pois []model.POI, boss string) model.Mission {
5652 steps := make([]model.MissionStep, 0, len(pois))
5753 for i, p := range pois[:len(pois)-1] {
5854 kind := "reach"
59- if i > 0 {
55+ switch {
56+ case i > 0 && q.sys.KeyItems:
57+ kind = "retrieve"
58+ case i > 0:
6059 kind = rng.Pick(q.r, kinds)
6160 }
6261 steps = append(steps, q.step(fmt.Sprintf("m%d", i+1), kind, p))
@@ -83,11 +82,8 @@ func (q *questBuilder) side(i int, pois []model.POI) model.Mission {
8382
8483 var keyNames = []string{"Sunken Crown", "Bone Key", "Moonstone Sigil", "Ember Seal", "Gilded Chalice", "Black Lantern", "Serpent Idol"}
8584
86-func makeKeyItem(r *rand.Rand, n int, name string) model.Item {
87- return model.Item{
88- ID: fmt.Sprintf("key%d", n), Name: name, Slot: model.SlotTrinket, Rarity: "rare",
89- Bonus: model.Stats{Magic: 2 + r.IntN(3)}, Key: true,
90- }
85+func makeKeyItem(n int, name string) model.Item {
86+ return model.Item{ID: fmt.Sprintf("key%d", n), Name: name, Rarity: "rare", Key: true}
9187 }
9288
9389 func rollKeyNames(r *rand.Rand) []string {
@@ -27,7 +27,7 @@ var heroNames = []string{"Ayla", "Brom", "Cael", "Dara", "Edrin", "Fenna", "Garr
2727 func rollParty(r *rand.Rand, spawn model.SpawnPoint) model.Party {
2828 cs := rng.Shuffled(r, sim.Classes)[:rng.Between(r, 3, 4)]
2929 names := rng.Shuffled(r, heroNames)
30- p := model.Party{X: spawn.X, Y: spawn.Y, Gold: rng.Between(r, 10, 40)}
30+ p := model.Party{X: spawn.X, Y: spawn.Y, Gold: rng.Between(r, 10, 40), Inventory: []model.Item{}, Keys: []model.Item{}}
3131 for i, c := range cs {
3232 rc := rng.Pick(r, races)
3333 b := c.Base
@@ -4,9 +4,17 @@ type NewRequest struct {
44 Seed *Seed `json:"seed,omitempty"`
55 }
66
7+type Route struct {
8+ Path [][2]int `json:"path"`
9+ Time int `json:"time"`
10+ Dusk bool `json:"dusk"`
11+ Blocked string `json:"blocked,omitempty"`
12+}
13+
714 type MoveRequest struct {
8- X int `json:"x"`
9- Y int `json:"y"`
15+ X int `json:"x"`
16+ Y int `json:"y"`
17+ Steps int `json:"steps,omitempty"`
1018 }
1119
1220 type InteractRequest struct {
@@ -8,13 +8,14 @@ type Encounter struct {
88 }
99
1010 type Threat struct {
11- POI string `json:"poi,omitempty"`
12- Band string `json:"band,omitempty"`
13- Enemies []Unit `json:"enemies"`
14- Odds int `json:"odds"`
15- Wounds int `json:"wounds"`
16- Barred bool `json:"barred,omitempty"`
17- Edge Edge `json:"edge"`
11+ POI string `json:"poi,omitempty"`
12+ Band string `json:"band,omitempty"`
13+ Enemies []Unit `json:"enemies"`
14+ Odds int `json:"odds"`
15+ Wounds int `json:"wounds"`
16+ Barred bool `json:"barred,omitempty"`
17+ Needs []string `json:"needs,omitempty"`
18+ Edge Edge `json:"edge"`
1819 }
1920
2021 type Edge struct {
@@ -24,9 +24,6 @@ type Item struct {
2424 var rarityWorth = map[string]int{"common": 4, "uncommon": 6, "rare": 9, "epic": 13, "legendary": 18}
2525
2626 func Price(it Item) int {
27- if it.Key {
28- return 0
29- }
3027 b := it.Bonus
3128 worth := b.MaxHP/3 + b.Attack + b.Defense + b.Magic + (b.Speed+b.Crit)/2
3229 if it.Trait != "" {
@@ -20,6 +20,7 @@ type Party struct {
2020 PlayerID string `json:"playerId"`
2121 Units []Unit `json:"units"`
2222 Inventory []Item `json:"inventory"`
23+ Keys []Item `json:"keys"`
2324 X int `json:"x"`
2425 Y int `json:"y"`
2526 Gold int `json:"gold"`
@@ -8,9 +8,9 @@ import (
88 )
99
1010 const (
11- dayLength = 60
12- nightLength = 30
13- fightTime = 6
11+ dayLength = 140
12+ nightLength = 40
13+ fightTime = 8
1414 )
1515
1616 func newClock() model.Clock {
@@ -22,7 +22,7 @@ func TestRoamingBandInterceptsTheParty(t *testing.T) {
2222 g.state.Party.Y = 1
2323 g.state.Map.Bands = []model.Band{{ID: "b1", Kind: "roam", X: 10, Y: 1, HomeX: 10, HomeY: 1}}
2424 g.encs = map[string]model.Encounter{"b1": {ID: "enc-b1", POI: "b1"}}
25- if err := g.move(29, 1); err != nil {
25+ if err := g.move(29, 1, 0); err != nil {
2626 t.Fatal(err)
2727 }
2828 b := g.band("b1")
@@ -40,7 +40,7 @@ func TestGuardBlocksItsChest(t *testing.T) {
4040 g.state.Map.Loot = []model.LootNode{{ID: "c1", X: 4, Y: 0, Item: model.Item{ID: "i1"}}}
4141 g.state.Map.Bands = []model.Band{{ID: "b1", Kind: "guard", X: 4, Y: 0}}
4242 g.encs = map[string]model.Encounter{"b1": {ID: "enc-b1", POI: "b1"}}
43- g.move(7, 0)
43+ g.move(7, 0, 0)
4444 if g.threat != "b1" || g.state.Party.X != 3 || g.state.Map.Loot[0].Collected {
4545 t.Fatalf("threat %q party %d collected %v", g.threat, g.state.Party.X, g.state.Map.Loot[0].Collected)
4646 }
@@ -53,7 +53,7 @@ func TestHazardsSapButNeverKill(t *testing.T) {
5353 }
5454 g.state.Party = party("fighter", "mage")
5555 g.state.Party.Units[1].Gear = model.Gear{model.SlotArmor: &model.Item{ID: "w", Trait: "ward"}}
56- g.move(39, 0)
56+ g.move(39, 0, 0)
5757 f, m := g.state.Party.Units[0], g.state.Party.Units[1]
5858 if f.Stats.HP >= 100 || f.Stats.HP < 1 || m.Stats.HP != 100 || len(g.state.Notes) == 0 {
5959 t.Fatalf("fighter %d mage %d notes %v", f.Stats.HP, m.Stats.HP, g.state.Notes)
@@ -66,20 +66,20 @@ func TestLandmarksAndTraps(t *testing.T) {
6666 g.state.Party.Units[0].Stats.HP = 10
6767 g.state.Map.Landmarks = []model.Landmark{{ID: "s", Kind: "shrine", X: 2}, {ID: "c", Kind: "cache", X: 4}}
6868 g.state.Map.Loot = []model.LootNode{{ID: "t", X: 6, Trap: true, Item: model.Item{ID: "i"}}}
69- g.move(5, 0)
69+ g.move(5, 0, 0)
7070 u := g.state.Party.Units[0]
7171 if u.Stats.HP != sim.Effective(u).MaxHP || u.XP == 0 && u.Level == 1 || !g.state.Map.Landmarks[0].Used {
7272 t.Fatalf("hp %d xp %d level %d", u.Stats.HP, u.XP, u.Level)
7373 }
7474 before := u.Stats.HP
75- g.move(6, 0)
75+ g.move(6, 0, 0)
7676 if g.state.Party.Units[0].Stats.HP >= before {
7777 t.Fatal("trap did not wound a party without a rogue")
7878 }
7979 g = openGame(10, 1)
8080 g.state.Party = party("rogue")
8181 g.state.Map.Loot = []model.LootNode{{ID: "t", X: 3, Trap: true, Item: model.Item{ID: "i"}}}
82- g.move(3, 0)
82+ g.move(3, 0, 0)
8383 if g.state.Party.Units[0].Stats.HP != 100 {
8484 t.Fatal("rogue failed to disarm")
8585 }
@@ -92,7 +92,7 @@ func TestBackingOffShakesABandOff(t *testing.T) {
9292 g.state.Map.Bands = []model.Band{{ID: "b1", Kind: "roam", X: 11, Y: 1, HomeX: 11, HomeY: 1}}
9393 g.encs = map[string]model.Encounter{"b1": {ID: "enc-b1", POI: "b1"}}
9494 g.threat = "b1"
95- if err := g.move(2, 1); err != nil {
95+ if err := g.move(2, 1, 0); err != nil {
9696 t.Fatal(err)
9797 }
9898 if g.threat != "" || g.state.Party.X > 5 {
@@ -33,7 +33,7 @@ func (g *game) equip(req model.EquipRequest) error {
3333 return errors.New("item not in inventory")
3434 }
3535 it := (*inv)[i]
36- if it.Key || it.Slot == "" {
36+ if it.Slot == "" {
3737 return errors.New("item cannot be equipped")
3838 }
3939 *inv = slices.Delete(*inv, i, i+1)
@@ -1,6 +1,7 @@
11 package server
22
33 import (
4+ "slices"
45 "time"
56
67 "tinyadventure/internal/gen"
@@ -84,13 +85,33 @@ func (g *game) poiAt(x, y int) *model.POI {
8485 return nil
8586 }
8687
87-func (g *game) hasItem(id string) bool {
88- for _, it := range g.state.Party.Inventory {
89- if it.ID == id {
90- return true
88+func (g *game) take(it model.Item) {
89+ p := &g.state.Party
90+ if it.Key {
91+ p.Keys = append(p.Keys, it)
92+ } else {
93+ p.Inventory = append(p.Inventory, it)
94+ g.state.Summary.Loot++
95+ }
96+}
97+
98+func (g *game) hasKey(id string) bool {
99+ return slices.ContainsFunc(g.state.Party.Keys, func(it model.Item) bool { return it.ID == id })
100+}
101+
102+func (g *game) missingKeys() []string {
103+ out := []string{}
104+ for _, s := range g.state.Campaign.Main.Steps {
105+ if s.Slots.Item == "" || g.hasKey(s.Slots.Item) {
106+ continue
107+ }
108+ for _, l := range g.state.Map.Loot {
109+ if l.Item.ID == s.Slots.Item {
110+ out = append(out, l.Item.Name)
111+ }
91112 }
92113 }
93- return false
114+ return out
94115 }
95116
96117 func (g *game) missions() []*model.Mission {
@@ -107,7 +128,7 @@ func (g *game) advance() {
107128 for i := range m.Steps {
108129 s := &m.Steps[i]
109130 p := g.poi(s.POI)
110- if !s.Done && p != nil && p.Cleared && (s.Slots.Item == "" || g.hasItem(s.Slots.Item)) {
131+ if !s.Done && p != nil && p.Cleared && (s.Slots.Item == "" || g.hasKey(s.Slots.Item)) {
111132 s.Done = true
112133 }
113134 if s.Done {
@@ -46,8 +46,7 @@ func (g *game) interact(id string) error {
4646 return errors.New("too far away")
4747 }
4848 l.Collected = true
49- g.state.Party.Inventory = append(g.state.Party.Inventory, l.Item)
50- g.state.Summary.Loot++
49+ g.take(l.Item)
5150 g.advance()
5251 return nil
5352 }
@@ -3,6 +3,7 @@ package server
33 import (
44 "errors"
55
6+ "tinyadventure/internal/model"
67 "tinyadventure/internal/world"
78 )
89
@@ -36,13 +37,16 @@ func (g *game) blocker(x, y int) string {
3637 return ""
3738 }
3839
39-func (g *game) move(tx, ty int) error {
40+func (g *game) move(tx, ty, limit int) error {
4041 g.shake()
4142 g.begin()
4243 steps, err := g.path(tx, ty)
4344 if err != nil {
4445 return err
4546 }
47+ if limit > 0 && len(steps) > limit {
48+ steps = steps[:limit]
49+ }
4650 lost := map[string]int{}
4751 for _, s := range steps {
4852 if id := g.blocker(s[0], s[1]); id != "" {
@@ -64,3 +68,18 @@ func (g *game) move(tx, ty int) error {
6468 g.noteHazards(lost)
6569 return nil
6670 }
71+
72+func (g *game) route(tx, ty int) (model.Route, error) {
73+ steps, err := g.path(tx, ty)
74+ out := model.Route{Path: [][2]int{}}
75+ for _, s := range steps {
76+ if out.Blocked = g.blocker(s[0], s[1]); out.Blocked != "" {
77+ break
78+ }
79+ out.Path = append(out.Path, s)
80+ out.Time += g.state.Map.Cost(s[0], s[1])
81+ }
82+ c := g.state.Clock
83+ out.Dusk = !c.Night() && c.Time+out.Time >= c.DayLength
84+ return out, err
85+}
@@ -1,6 +1,7 @@
11 package server
22
33 import (
4+ "slices"
45 "testing"
56
67 "tinyadventure/internal/model"
@@ -19,7 +20,7 @@ func openGame(w, h int) *game {
1920 func TestMovePicksUpLootOnTheWay(t *testing.T) {
2021 g := openGame(5, 1)
2122 g.state.Map.Loot = []model.LootNode{{ID: "l1", X: 2, Y: 0, Item: model.Item{ID: "i1", Name: "Sword"}}}
22- if err := g.move(4, 0); err != nil {
23+ if err := g.move(4, 0, 0); err != nil {
2324 t.Fatal(err)
2425 }
2526 if len(g.state.Party.Inventory) != 1 || len(g.state.Found) != 1 || !g.state.Map.Loot[0].Collected || g.state.Summary.Loot != 1 {
@@ -75,14 +76,14 @@ func TestDefeatEndsTheCampaign(t *testing.T) {
7576 }
7677
7778 func TestCampOnlyAtNightOncePerDay(t *testing.T) {
78- g := openGame(80, 1)
79+ g := openGame(200, 1)
7980 g.state.Party = party("fighter")
8081 g.state.Party.Units[0].Stats.HP = 10
8182 g.state.Clock = newClock()
8283 if g.rest() == nil {
8384 t.Fatal("made camp in daylight")
8485 }
85- if err := g.move(31, 0); err != nil || !g.state.Clock.Night() || len(g.state.Notes) == 0 {
86+ if err := g.move(75, 0, 0); err != nil || !g.state.Clock.Night() || len(g.state.Notes) == 0 {
8687 t.Fatalf("clock %+v notes %v err %v", g.state.Clock, g.state.Notes, err)
8788 }
8889 if err := g.rest(); err != nil {
@@ -95,7 +96,7 @@ func TestCampOnlyAtNightOncePerDay(t *testing.T) {
9596 if g.rest() == nil {
9697 t.Fatal("made camp twice")
9798 }
98- g.move(79, 0)
99+ g.move(199, 0, 0)
99100 if g.state.Clock.Day != 3 {
100101 t.Fatalf("a night without camp must still end the day: %+v", g.state.Clock)
101102 }
@@ -108,7 +109,7 @@ func equipAll(g *game) {
108109 }
109110 for _, u := range g.state.Party.Units {
110111 for _, it := range g.state.Party.Inventory {
111- if it.Key || it.Slot == "" {
112+ if it.Slot == "" {
112113 continue
113114 }
114115 if old := u.Gear[it.Slot]; old == nil || score(*old) < score(it) {
@@ -126,7 +127,7 @@ func TestCarefulPlayWinsMostCampaigns(t *testing.T) {
126127 wins++
127128 }
128129 }
129- if wins*100/total < 90 {
130+ if wins*100/total < 70 {
130131 t.Fatalf("careful play won %d of %d", wins, total)
131132 }
132133 }
@@ -144,7 +145,7 @@ func careful(g *game) bool {
144145 return false
145146 }
146147 }
147- g.move(x, y)
148+ g.move(x, y, 0)
148149 if g.threat == "" {
149150 continue
150151 }
@@ -202,7 +203,7 @@ func (g *game) waitForCamp() error {
202203 for y := py - 3; y <= py+3; y++ {
203204 for x := px - 3; x <= px+3; x++ {
204205 if d := world.Distance(x, y, px, py); d >= 2 && d <= 3 && g.state.Map.In(x, y) && g.state.Map.Walkable(x, y) && g.blocker(x, y) == "" && g.calm(x, y) {
205- g.move(x, y)
206+ g.move(x, y, 0)
206207 y = py + 4
207208 break
208209 }
@@ -235,7 +236,7 @@ func TestPOILevelsGrowTowardTheBoss(t *testing.T) {
235236
236237 func (g *game) engage(p *model.POI) error {
237238 for range 12 {
238- if err := g.move(p.X, p.Y); err != nil {
239+ if err := g.move(p.X, p.Y, 0); err != nil {
239240 return err
240241 }
241242 id := g.threat
@@ -279,7 +280,7 @@ func (g *game) recover() {
279280 func TestThreatStopsBeforePOIAndOffersOdds(t *testing.T) {
280281 g := newGame("local", 7)
281282 p := g.poi(g.state.Campaign.Main.Steps[0].POI)
282- if err := g.move(p.X, p.Y); err != nil {
283+ if err := g.move(p.X, p.Y, 0); err != nil {
283284 t.Fatal(err)
284285 }
285286 st := g.snapshot()
@@ -305,7 +306,7 @@ func TestBarredBossShowsAsBarred(t *testing.T) {
305306 g.state.Map.Bands = nil
306307 steps := g.state.Campaign.Main.Steps
307308 boss := g.poi(steps[len(steps)-1].POI)
308- if err := g.move(boss.X, boss.Y); err != nil {
309+ if err := g.move(boss.X, boss.Y, 0); err != nil {
309310 t.Fatal(err)
310311 }
311312 if st := g.snapshot(); st.Threat == nil || !st.Threat.Barred {
@@ -323,7 +324,7 @@ func TestHPCarriesBetweenFights(t *testing.T) {
323324 t.Fatalf("not at full health at start: %d", full)
324325 }
325326 p := g.poi(g.state.Campaign.Main.Steps[0].POI)
326- if err := g.move(p.X, p.Y); err != nil {
327+ if err := g.move(p.X, p.Y, 0); err != nil {
327328 t.Fatal(err)
328329 }
329330 before := g.state.Clock.Time
@@ -340,7 +341,7 @@ func TestHPCarriesBetweenFights(t *testing.T) {
340341 if total == 0 {
341342 t.Skip("party took no damage")
342343 }
343- g.move(p.X+1, p.Y)
344+ g.move(p.X+1, p.Y, 0)
344345 for _, u := range g.state.Party.Units {
345346 if u.Stats.HP > sim.Effective(u).MaxHP {
346347 t.Fatal("hp above max")
@@ -391,3 +392,35 @@ func TestShopTradeAndPotions(t *testing.T) {
391392 t.Fatal("trade away from camp")
392393 }
393394 }
395+
396+func TestMoveStepsLimitsTheWalk(t *testing.T) {
397+ g := openGame(5, 1)
398+ if err := g.move(4, 0, 1); err != nil || g.state.Party.X != 1 {
399+ t.Fatalf("one step should reach x=1, at %d err %v", g.state.Party.X, err)
400+ }
401+ if err := g.move(4, 0, 0); err != nil || g.state.Party.X != 4 {
402+ t.Fatalf("full walk should reach x=4, at %d", g.state.Party.X)
403+ }
404+}
405+
406+func TestKeysGoToTheKeyRingAndOpenTheBoss(t *testing.T) {
407+ g := openGame(6, 1)
408+ g.state.Party = party("fighter")
409+ g.state.Map.POIs = []model.POI{{ID: "p1", X: 2, Y: 0, Cleared: true}, {ID: "boss", X: 5, Y: 0}}
410+ g.state.Map.Loot = []model.LootNode{{ID: "loot-key1", X: 2, Y: 0, Item: model.Item{ID: "key1", Name: "Bone Key", Key: true}}}
411+ g.state.Campaign.Main.Steps = []model.MissionStep{{ID: "m1", POI: "p1", Slots: model.Slots{Item: "key1"}}, {ID: "m2", POI: "boss"}}
412+ g.encs = map[string]model.Encounter{"boss": {ID: "e", POI: "boss"}}
413+ g.threat = "boss"
414+ if v := g.threatView(); !v.Barred || !slices.Equal(v.Needs, []string{"Bone Key"}) {
415+ t.Fatalf("barred %v needs %v", v.Barred, v.Needs)
416+ }
417+ g.move(3, 0, 0)
418+ g.advance()
419+ if len(g.state.Party.Keys) != 1 || len(g.state.Party.Inventory) != 0 || !g.state.Campaign.Main.Steps[0].Done {
420+ t.Fatalf("keys %v inventory %v", g.state.Party.Keys, g.state.Party.Inventory)
421+ }
422+ g.threat = "boss"
423+ if v := g.threatView(); v.Barred || len(v.Needs) != 0 {
424+ t.Fatalf("boss still barred: %+v", v)
425+ }
426+}
@@ -4,6 +4,7 @@ import (
44 "encoding/json"
55 "errors"
66 "net/http"
7+ "strconv"
78 "sync"
89
910 "tinyadventure/internal/model"
@@ -21,12 +22,13 @@ func New(seed model.Seed, webDir string) *Server {
2122 s := &Server{players: map[string]*game{}, first: seed, mux: http.NewServeMux()}
2223 s.mux.HandleFunc("GET /api/state", s.act(func(g *game, r *http.Request) error { return nil }))
2324 s.mux.HandleFunc("POST /api/new", s.handleNew)
25+ s.mux.HandleFunc("GET /api/path", s.handlePath)
2426 s.mux.HandleFunc("POST /api/move", s.act(func(g *game, r *http.Request) error {
2527 var req model.MoveRequest
2628 if err := decode(r, &req); err != nil {
2729 return err
2830 }
29- return g.move(req.X, req.Y)
31+ return g.move(req.X, req.Y, req.Steps)
3032 }))
3133 s.mux.HandleFunc("POST /api/interact", s.act(func(g *game, r *http.Request) error {
3234 var req model.InteractRequest
@@ -124,6 +126,23 @@ func (s *Server) act(fn func(*game, *http.Request) error) http.HandlerFunc {
124126 }
125127 }
126128
129+func (s *Server) handlePath(w http.ResponseWriter, r *http.Request) {
130+ x, ex := strconv.Atoi(r.URL.Query().Get("x"))
131+ y, ey := strconv.Atoi(r.URL.Query().Get("y"))
132+ if err := errors.Join(ex, ey); err != nil {
133+ fail(w, http.StatusBadRequest, err)
134+ return
135+ }
136+ s.mu.Lock()
137+ defer s.mu.Unlock()
138+ route, err := s.get(player(r)).route(x, y)
139+ if err != nil {
140+ fail(w, http.StatusBadRequest, err)
141+ return
142+ }
143+ reply(w, http.StatusOK, route)
144+}
145+
127146 func (s *Server) handleNew(w http.ResponseWriter, r *http.Request) {
128147 var req model.NewRequest
129148 if r.ContentLength != 0 {
@@ -5,6 +5,7 @@ import (
55 "encoding/json"
66 "net/http"
77 "net/http/httptest"
8+ "strconv"
89 "testing"
910
1011 "tinyadventure/internal/model"
@@ -101,3 +102,27 @@ func TestFinishedCampaignRejectsActions(t *testing.T) {
101102 }
102103 c.call("POST", "/api/new", nil, 200)
103104 }
105+
106+func TestPathPreviewMatchesTheWalk(t *testing.T) {
107+ srv := New(7, t.TempDir())
108+ ts := httptest.NewServer(srv)
109+ defer ts.Close()
110+ g := srv.get("local")
111+ tx, ty := g.state.Party.X+3, g.state.Party.Y
112+ for !g.state.Map.Walkable(tx, ty) || g.blocker(tx, ty) != "" {
113+ tx++
114+ }
115+ res, err := http.Get(ts.URL + "/api/path?x=" + strconv.Itoa(tx) + "&y=" + strconv.Itoa(ty))
116+ if err != nil {
117+ t.Fatal(err)
118+ }
119+ var route model.Route
120+ json.NewDecoder(res.Body).Decode(&route)
121+ want, _ := g.path(tx, ty)
122+ if len(route.Path) == 0 || route.Time <= 0 || route.Path[len(route.Path)-1] != want[len(route.Path)-1] {
123+ t.Fatalf("route %+v want %v", route, want)
124+ }
125+ if res, _ := http.Get(ts.URL + "/api/path?x=a&y=1"); res.StatusCode != 400 {
126+ t.Fatalf("bad query gave %d", res.StatusCode)
127+ }
128+}
@@ -122,9 +122,6 @@ func (g *game) sell(id string) error {
122122 if i < 0 {
123123 return errors.New("item not in inventory")
124124 }
125- if p.Inventory[i].Key {
126- return errors.New("quest items cannot be sold")
127- }
128125 p.Gold += SellPrice(p.Inventory[i])
129126 p.Inventory = slices.Delete(p.Inventory, i, i+1)
130127 return nil
@@ -160,9 +157,8 @@ func (g *game) pickup(x, y int) {
160157 g.spring()
161158 }
162159 l.Collected = true
163- g.state.Party.Inventory = append(g.state.Party.Inventory, l.Item)
160+ g.take(l.Item)
164161 g.state.Found = append(g.state.Found, l.Item)
165- g.state.Summary.Loot++
166162 }
167163 }
168164 }
@@ -18,6 +18,9 @@ func (g *game) threatView() *model.Threat {
1818 t := &model.Threat{Enemies: enc.Enemies, Odds: odds, Wounds: wounds, Edge: sim.EdgeOf(g.state.Party.Units, enc.Enemies)}
1919 if p := g.poi(g.threat); p != nil {
2020 t.POI, t.Barred = p.ID, !g.bossGate(p)
21+ if t.Barred {
22+ t.Needs = g.missingKeys()
23+ }
2124 } else {
2225 t.Band = g.threat
2326 }
@@ -354,12 +354,12 @@ func Rewards(r *rand.Rand, enc model.Encounter, nodeTier int) model.Rewards {
354354 rw.XP += enemyXP(e, enc.Boss && e.Class == "boss")
355355 rw.Gold += 3*e.Level + r.IntN(4)
356356 tier = max(tier, e.Level)
357- if r.IntN(100) < 35 {
357+ if r.IntN(100) < 20 {
358358 rw.Items = append(rw.Items, RollItem(r, max(e.Level, nodeTier)))
359359 }
360360 }
361361 if enc.Boss {
362- rw.Items = append(rw.Items, RollLoot(r, tier+1, nodeTier, 2)...)
362+ rw.Items = append(rw.Items, RollItem(r, max(tier+1, nodeTier)), RollItem(r, max(tier+1, nodeTier)))
363363 }
364364 return rw
365365 }
@@ -10,26 +10,40 @@ import (
1010
1111 var Rarities = []string{"common", "uncommon", "rare", "epic", "legendary"}
1212
13-var rarityMult = map[string]float64{"common": 1.0, "uncommon": 1.3, "rare": 1.7, "epic": 2.2, "legendary": 3.0}
13+var rarityMult = map[string]float64{"common": 1.0, "uncommon": 1.25, "rare": 1.5, "epic": 1.8, "legendary": 2.2}
1414
1515 var rarityWeights = [5]int{60, 25, 10, 4, 1}
1616
17-var slotBase = map[model.Slot]model.Stats{
18- model.SlotWeapon: {Attack: 3, Crit: 2},
19- model.SlotArmor: {Defense: 3, MaxHP: 6},
20- model.SlotHelm: {Defense: 1, MaxHP: 4, Magic: 1},
21- model.SlotTrinket: {Magic: 2, Speed: 1, Crit: 1},
22-}
17+var rarityPrefix = map[string]string{"common": "Plain", "uncommon": "Fine", "rare": "Runed", "epic": "Moonlit", "legendary": "Ancient"}
2318
24-var Slots = []model.Slot{model.SlotWeapon, model.SlotArmor, model.SlotHelm, model.SlotTrinket}
19+type base struct {
20+ name string
21+ slot model.Slot
22+ s model.Stats
23+}
2524
26-var slotNames = map[model.Slot][]string{
27- model.SlotWeapon: {"Sword", "Axe", "Mace", "Dagger", "Staff"},
28- model.SlotArmor: {"Mail", "Jerkin", "Robe", "Plate"},
29- model.SlotHelm: {"Cap", "Helm", "Hood", "Circlet"},
30- model.SlotTrinket: {"Amulet", "Ring", "Charm", "Idol"},
25+var bases = []base{
26+ {"Sword", model.SlotWeapon, model.Stats{Attack: 3, Crit: 2}},
27+ {"Axe", model.SlotWeapon, model.Stats{Attack: 4, Crit: 3, Defense: -1}},
28+ {"Mace", model.SlotWeapon, model.Stats{Attack: 3, Defense: 1}},
29+ {"Dagger", model.SlotWeapon, model.Stats{Attack: 2, Speed: 2, Crit: 4}},
30+ {"Staff", model.SlotWeapon, model.Stats{Magic: 4, Attack: 1}},
31+ {"Plate", model.SlotArmor, model.Stats{Defense: 5, MaxHP: 8, Speed: -2}},
32+ {"Mail", model.SlotArmor, model.Stats{Defense: 3, MaxHP: 6}},
33+ {"Jerkin", model.SlotArmor, model.Stats{Defense: 2, MaxHP: 4, Speed: 2}},
34+ {"Robe", model.SlotArmor, model.Stats{Defense: 1, MaxHP: 4, Magic: 3}},
35+ {"Helm", model.SlotHelm, model.Stats{Defense: 2, MaxHP: 5}},
36+ {"Cap", model.SlotHelm, model.Stats{Defense: 1, MaxHP: 3, Speed: 1}},
37+ {"Hood", model.SlotHelm, model.Stats{MaxHP: 3, Crit: 3}},
38+ {"Circlet", model.SlotHelm, model.Stats{MaxHP: 2, Magic: 3}},
39+ {"Amulet", model.SlotTrinket, model.Stats{Magic: 2, MaxHP: 5}},
40+ {"Ring", model.SlotTrinket, model.Stats{Attack: 1, Crit: 4}},
41+ {"Charm", model.SlotTrinket, model.Stats{Defense: 1, Speed: 2}},
42+ {"Idol", model.SlotTrinket, model.Stats{Magic: 4, Speed: -1}},
3143 }
3244
45+var Slots = []model.Slot{model.SlotWeapon, model.SlotArmor, model.SlotHelm, model.SlotTrinket}
46+
3347 var slotAbilities = map[model.Slot][]string{
3448 model.SlotWeapon: {"cleave", "power-strike", "backstab"},
3549 model.SlotArmor: {"rally"},
@@ -37,19 +51,11 @@ var slotAbilities = map[model.Slot][]string{
3751 model.SlotTrinket: {"firebolt", "heal", "fireball"},
3852 }
3953
40-var rarityPrefix = map[string][]string{
41- "common": {"Worn", "Plain", "Sturdy"},
42- "uncommon": {"Fine", "Keen", "Hardy"},
43- "rare": {"Runed", "Gilded", "Elven"},
44- "epic": {"Dragonbone", "Moonlit", "Stormforged"},
45- "legendary": {"Ancient", "Godsworn", "Wyrmslayer's"},
46-}
47-
48-func tierScale(tier int) float64 { return 1 + 0.35*float64(max(tier, 1)-1) }
54+func tierScale(tier int) float64 { return 1 + 0.3*float64(max(tier, 1)-1) }
4955
5056 func scaleStat(v int, f float64) int {
51- if v == 0 {
52- return 0
57+ if v <= 0 {
58+ return v
5359 }
5460 return max(1, int(float64(v)*f+0.5))
5561 }
@@ -76,20 +82,26 @@ func rollRarity(r *rand.Rand, tier int) string {
7682 }
7783
7884 func BuildItem(r *rand.Rand, slot model.Slot, rarity string, tier int) model.Item {
85+ var pool []base
86+ for _, b := range bases {
87+ if b.slot == slot {
88+ pool = append(pool, b)
89+ }
90+ }
91+ b := rng.Pick(r, pool)
7992 f := tierScale(tier) * rarityMult[rarity]
80- b := slotBase[slot]
8193 it := model.Item{
8294 ID: fmt.Sprintf("it-%08x", r.Uint32()),
83- Name: rng.Pick(r, rarityPrefix[rarity]) + " " + rng.Pick(r, slotNames[slot]),
95+ Name: rarityPrefix[rarity] + " " + b.name,
8496 Slot: slot,
8597 Rarity: rarity,
8698 Bonus: model.Stats{
87- MaxHP: scaleStat(b.MaxHP, f),
88- Attack: scaleStat(b.Attack, f),
89- Defense: scaleStat(b.Defense, f),
90- Magic: scaleStat(b.Magic, f),
91- Speed: scaleStat(b.Speed, f/2),
92- Crit: scaleStat(b.Crit, f),
99+ MaxHP: scaleStat(b.s.MaxHP, f),
100+ Attack: scaleStat(b.s.Attack, f),
101+ Defense: scaleStat(b.s.Defense, f),
102+ Magic: scaleStat(b.s.Magic, f),
103+ Speed: scaleStat(b.s.Speed, f/2),
104+ Crit: scaleStat(b.s.Crit, f),
93105 },
94106 }
95107 if rarityMult[rarity] >= rarityMult["rare"] {
@@ -104,15 +116,6 @@ func RollItem(r *rand.Rand, tier int) model.Item {
104116 return BuildItem(r, rng.Pick(r, Slots), rollRarity(r, tier), tier)
105117 }
106118
107-func RollLoot(r *rand.Rand, enemyTier, nodeTier int, drops int) []model.Item {
108- tier := max(enemyTier, nodeTier)
109- items := make([]model.Item, 0, drops)
110- for range drops {
111- items = append(items, RollItem(r, tier))
112- }
113- return items
114-}
115-
116119 func Effective(u model.Unit) model.Stats {
117120 s := u.Stats
118121 for _, it := range u.Gear {
@@ -37,7 +37,7 @@ var Elements = []string{"fire", "frost", "holy", "shadow"}
3737 var abilityElement = map[string]string{"firebolt": "fire", "fireball": "fire", "frost-nova": "frost", "smite": "holy"}
3838
3939 func Imbue(roll func(n int) int, it *model.Item) {
40- if it.Key || roll(100) >= traitChance[it.Rarity] {
40+ if roll(100) >= traitChance[it.Rarity] {
4141 return
4242 }
4343 var fits []string
@@ -3,6 +3,7 @@ import { maxHp } from '../web/js/stats.js';
33
44 const SAFE = 80;
55 const FLOOR = 50;
6+const WOUNDS = 50;
67 const SHOP_KINDS = ['camp', 'village'];
78
89 const score = (it) => it.bonus.maxHp / 3 + it.bonus.attack + it.bonus.defense + it.bonus.magic + it.bonus.speed / 2;
@@ -11,7 +12,7 @@ export function upgrades(s) {
1112 const taken = new Set();
1213 for (const u of s.party.units) {
1314 for (const it of s.party.inventory || []) {
14- if (it.key || !it.slot || taken.has(it.id)) continue;
15+ if (!it.slot || taken.has(it.id)) continue;
1516 const old = u.gear?.[it.slot];
1617 if (!old || score(old) < score(it)) {
1718 out.push({ unit: u.id, item: it.id });
@@ -37,12 +38,13 @@ function target(s, seen) {
3738 const main = s.campaign.main.steps;
3839 const open = main.filter((q) => !q.done);
3940 const boss = main.at(-1).poi;
40- const fresh = (id) => seen[id] !== lv;
41+ const fresh = (id) => seen[id]?.lv !== lv;
4142 const next = s.map.pois.find((p) => p.id === open[0]?.poi);
42- if (next && fresh(next.id) && (next.id !== boss || open.length === 1)) return next;
43+ if (next && fresh(next.id) && next.id !== boss) return next;
4344 const pois = s.map.pois.filter((p) => !p.cleared && fresh(p.id) && p.id !== boss);
4445 const bands = (s.map.bands || []).filter((b) => !b.cleared && fresh(b.id));
45- return [...pois, ...bands].sort((a, b) => a.level - b.level || away(s)(a) - away(s)(b))[0] || null;
46+ const other = [...pois, ...bands].sort((a, b) => a.level - b.level || away(s)(a) - away(s)(b))[0];
47+ return (next && fresh(next.id) && open.length === 1 && (!other || full(s)) ? next : other) || null;
4648 }
4749
4850 export function createBot(io, { safe = SAFE, note = () => {} } = {}) {
@@ -53,14 +55,15 @@ export function createBot(io, { safe = SAFE, note = () => {} } = {}) {
5355 const t = s.threat;
5456 const id = t.poi || t.band;
5557 const boss = id === s.campaign.main.steps.at(-1).poi;
56- if (!t.barred && t.odds >= (boss ? Math.min(95, bar + 10) : bar)) {
58+ const costly = t.wounds > WOUNDS && !full(s);
59+ if (!t.barred && !costly && t.odds >= (boss ? Math.min(95, bar + 10) : bar)) {
5760 note('fight', `${id} at ${t.odds}% odds, ${t.wounds}% wounds`);
5861 const after = await io.fight(s);
5962 if (after.phase !== 'defeat') bar = safe;
6063 return after;
6164 }
62- seen[id] = levels(s);
63- note('back off', `${id} at ${t.odds}% odds${t.barred ? ', barred' : ''}`);
65+ seen[id] = { lv: levels(s), hurt: !full(s) };
66+ note('back off', `${id} at ${t.odds}% odds, ${t.wounds}% wounds${t.barred ? ', barred' : ''}`);
6467 return io.back(s);
6568 }
6669
@@ -85,7 +88,7 @@ export function createBot(io, { safe = SAFE, note = () => {} } = {}) {
8588 const r = await io.camp(s);
8689 if (r.ok) {
8790 note('camp', `day ${r.state.clock.day} begins`);
88- for (const k of Object.keys(seen)) delete seen[k];
91+ for (const k of Object.keys(seen)) if (seen[k].hurt) delete seen[k];
8992 return r.state;
9093 }
9194 s = r.state;