tiny-adventure / commits / c711fe0
Pick up loot on the way, avoid guarded POIs, retreat to nearest camp, add POI levels and gentler difficulty curve
Co-Authored-By: Claude Sonnet 5.5
@@ -30,7 +30,7 @@ Every endpoint except `/api/seed` and `/api/combat/log` returns a full `GameStat
3030 "width": 1,
3131 "height": 1,
3232 "tiles": [[{"terrain": "grass", "walkable": true}]],
33- "pois": [{"id": "poi1", "kind": "mine", "name": "Dark Mine", "x": 0, "y": 0, "faction": "f1", "cleared": false}],
33+ "pois": [{"id": "poi1", "kind": "mine", "name": "Dark Mine", "x": 0, "y": 0, "faction": "f1", "level": 1, "cleared": false}],
3434 "spawns": [{"id": "sp1", "kind": "inn", "x": 0, "y": 0, "hint": "Ask the innkeeper"}],
3535 "loot": [{"id": "l1", "x": 0, "y": 0, "item": {"id": "i1", "name": "Rusty Sword", "slot": "weapon", "rarity": "common", "bonus": {"hp": 0, "maxHp": 0, "attack": 2, "defense": 0, "magic": 0, "speed": 0, "crit": 0}}, "collected": false}]
3636 },
@@ -55,9 +55,11 @@ Every endpoint except `/api/seed` and `/api/combat/log` returns a full `GameStat
5555 }
5656 ```
5757
58-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. A lost fight sets `phase: "defeat"`, grants a quarter of the XP, and returns the party to the first spawn; the next action resumes `explore`. `summary.seconds` is the elapsed play time, frozen at victory. The boss POI only starts its fight once all other main steps are done. A `retrieve` step completes once its POI is cleare …
58+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. A lost fight sets `phase: "defeat"`, grants a quarter of the XP, and returns the party to the nearest spawn or cleared POI; the next action resumes `explore`. `summary.seconds` is the elapsed play time, frozen at victory. The boss POI only starts its fight once all other main steps are done. A `retrieve` step completes once …
5959
60-Optional fields: `encounter` (`Encounter`, present after a fight), `rewards` (`Rewards`, present after a won fight), `winner` (player id, set at `victory`).
60+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), `winner` (player id, set at `victory`).
61+
62+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.
6163
6264 Item slots: `weapon`, `armor`, `helm`, `trinket`. `gear` maps slot to `Item`.
6365
@@ -83,7 +85,7 @@ Response: `GameState` with a fresh campaign.
8385
8486 ## POST /api/move
8587
86-Moves the party toward tile `x,y`. The server paths over walkable tiles, may trigger an encounter on arrival, and returns the new state. Walking onto an uncleared POI tile stops the party there and starts its fight. Rejected with 400 for an unreachable tile or after victory.
88+Moves the party toward tile `x,y`. The server paths over walkable tiles, may trigger an encounter on arrival, and returns the new state. The route avoids other uncleared POI tiles unless they block the only way. Walking onto an uncleared POI tile stops the party there and starts its fight. Loot on any tile the party walks over is picked up automatically and listed in `found`; key items on a POI tile are picked up when the POI is cleared. Rejected with 400 for an unreachable tile or after victory …
8789
8890 ```json
8991 {"x": 12, "y": 7}
@@ -93,7 +95,7 @@ Response: `GameState` with updated `party.x`, `party.y`, and possibly `phase: "c
9395
9496 ## POST /api/interact
9597
96-Interacts with a POI, loot node, or spawn structure by id (`poi1`, `l1`, `sp1`). Collects loot, advances mission steps, or starts the POI encounter.
98+Interacts with a POI, loot node, or spawn structure by id (`poi1`, `l1`, `sp1`). Collects loot, advances mission steps, or starts the POI 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.
9799
98100 ```json
99101 {"id": "l1"}
@@ -57,12 +57,14 @@ func Generate(seed model.Seed) World {
5757
5858 er := sub(seed, "encounters")
5959 var encs []model.Encounter
60- for _, p := range pois {
60+ for i, p := range pois {
6161 b := ""
6262 if p.ID == boss.ID {
6363 b = name
6464 }
65- encs = append(encs, buildEncounter(er, p, byID[p.Faction], levelAt(spawns[0], maxDist, p.X, p.Y), b))
65+ lv := levelAt(spawns[0], maxDist, p.X, p.Y)
66+ m.POIs[i].Level = lv
67+ encs = append(encs, buildEncounter(er, p, byID[p.Faction], lv, b))
6668 }
6769 return World{Campaign: camp, Map: m, Party: rollParty(sub(seed, "party"), spawns[0]), Encounters: encs}
6870 }
@@ -91,5 +91,5 @@ func uniqueName(r *rand.Rand, pois []model.POI, kind string) string {
9191 }
9292
9393 func levelAt(origin model.SpawnPoint, maxDist, x, y int) int {
94- return 1 + (abs(x-origin.X)+abs(y-origin.Y))*6/max(1, maxDist)
94+ return 1 + (abs(x-origin.X)+abs(y-origin.Y))*4/max(1, maxDist)
9595 }
@@ -18,6 +18,7 @@ type GameState struct {
1818 Encounter *Encounter `json:"encounter,omitempty"`
1919 Log []CombatEvent `json:"log"`
2020 Rewards *Rewards `json:"rewards,omitempty"`
21+ Found []Item `json:"found,omitempty"`
2122 Phase string `json:"phase"`
2223 Winner string `json:"winner,omitempty"`
2324 Summary Summary `json:"summary"`
@@ -12,6 +12,7 @@ type POI struct {
1212 X int `json:"x"`
1313 Y int `json:"y"`
1414 Faction string `json:"faction,omitempty"`
15+ Level int `json:"level"`
1516 Cleared bool `json:"cleared"`
1617 }
1718
@@ -0,0 +1,48 @@
1+package server
2+
3+import "tinyadventure/internal/model"
4+
5+func (g *game) camp(from *model.POI) (int, int) {
6+ bx, by := g.spawn.X, g.spawn.Y
7+ best := dist(bx, by, from.X, from.Y)
8+ try := func(x, y int) {
9+ if d := dist(x, y, from.X, from.Y); d < best {
10+ bx, by, best = x, y, d
11+ }
12+ }
13+ for _, s := range g.state.Map.Spawns {
14+ try(s.X, s.Y)
15+ }
16+ for _, p := range g.state.Map.POIs {
17+ if p.Cleared {
18+ try(p.X, p.Y)
19+ }
20+ }
21+ return bx, by
22+}
23+
24+func dist(ax, ay, bx, by int) int {
25+ dx, dy := ax-bx, ay-by
26+ if dx < 0 {
27+ dx = -dx
28+ }
29+ if dy < 0 {
30+ dy = -dy
31+ }
32+ return dx + dy
33+}
34+
35+func (g *game) pickup(x, y int) {
36+ if p := g.poiAt(x, y); p != nil && !p.Cleared {
37+ return
38+ }
39+ for i := range g.state.Map.Loot {
40+ l := &g.state.Map.Loot[i]
41+ if l.X == x && l.Y == y && !l.Collected {
42+ l.Collected = true
43+ g.state.Party.Inventory = append(g.state.Party.Inventory, l.Item)
44+ g.state.Found = append(g.state.Found, l.Item)
45+ g.state.Summary.Loot++
46+ }
47+ }
48+}
@@ -51,6 +51,7 @@ func (g *game) finished() bool { return g.state.Phase == "victory" }
5151 func (g *game) begin() {
5252 g.state.Encounter = nil
5353 g.state.Rewards = nil
54+ g.state.Found = nil
5455 g.state.Log = []model.CombatEvent{}
5556 if g.state.Phase == "defeat" {
5657 g.state.Phase = "explore"
@@ -140,13 +141,14 @@ func (g *game) fight(p *model.POI) {
140141 for i := range g.state.Party.Units {
141142 sim.Grant(&g.state.Party.Units[i], max(1, xp))
142143 }
143- g.state.Party.X, g.state.Party.Y = g.spawn.X, g.spawn.Y
144+ g.state.Party.X, g.state.Party.Y = g.camp(p)
144145 return
145146 }
146147 g.state.Rewards = &res.Rewards
147148 g.state.Summary.Kills += len(enc.Enemies)
148149 g.state.Summary.Loot += len(res.Rewards.Items)
149150 p.Cleared = true
151+ g.pickup(p.X, p.Y)
150152 g.advance()
151153 if enc.Boss {
152154 g.state.Phase = "victory"
@@ -5,6 +5,18 @@ import "errors"
55 var dirs = [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
66
77 func (g *game) path(tx, ty int) ([][2]int, error) {
8+ if out, err := g.route(tx, ty, true); err == nil {
9+ return out, nil
10+ }
11+ return g.route(tx, ty, false)
12+}
13+
14+func (g *game) guarded(x, y int) bool {
15+ p := g.poiAt(x, y)
16+ return p != nil && !p.Cleared
17+}
18+
19+func (g *game) route(tx, ty int, avoid bool) ([][2]int, error) {
820 m := &g.state.Map
921 if tx < 0 || ty < 0 || tx >= m.Width || ty >= m.Height || !m.Tiles[ty][tx].Walkable {
1022 return nil, errors.New("tile is not walkable")
@@ -24,7 +36,7 @@ func (g *game) path(tx, ty int) ([][2]int, error) {
2436 }
2537 for _, d := range dirs {
2638 n := [2]int{c[0] + d[0], c[1] + d[1]}
27- if _, seen := prev[n]; seen || n[0] < 0 || n[1] < 0 || n[0] >= m.Width || n[1] >= m.Height || !m.Tiles[n[1]][n[0]].Walkable {
39+ if _, seen := prev[n]; seen || n[0] < 0 || n[1] < 0 || n[0] >= m.Width || n[1] >= m.Height || !m.Tiles[n[1]][n[0]].Walkable || (avoid && n != [2]int{tx, ty} && g.guarded(n[0], n[1])) {
2840 continue
2941 }
3042 prev[n] = c
@@ -45,6 +57,7 @@ func (g *game) move(tx, ty int) error {
4557 }
4658 for _, s := range steps {
4759 g.state.Party.X, g.state.Party.Y = s[0], s[1]
60+ g.pickup(s[0], s[1])
4861 if p := g.poiAt(s[0], s[1]); p != nil && !p.Cleared && g.bossGate(p) {
4962 g.fight(p)
5063 break
@@ -0,0 +1,128 @@
1+package server
2+
3+import (
4+ "testing"
5+
6+ "tinyadventure/internal/model"
7+)
8+
9+func openGame(w, h int) *game {
10+ tiles := make([][]model.Tile, h)
11+ for y := range tiles {
12+ tiles[y] = make([]model.Tile, w)
13+ for x := range tiles[y] {
14+ tiles[y][x] = model.Tile{Terrain: "grass", Walkable: true}
15+ }
16+ }
17+ return &game{state: model.GameState{Map: model.Map{Width: w, Height: h, Tiles: tiles}}}
18+}
19+
20+func TestMovePicksUpLootOnTheWay(t *testing.T) {
21+ g := openGame(5, 1)
22+ g.state.Map.Loot = []model.LootNode{{ID: "l1", X: 2, Y: 0, Item: model.Item{ID: "i1", Name: "Sword"}}}
23+ if err := g.move(4, 0); err != nil {
24+ t.Fatal(err)
25+ }
26+ if len(g.state.Party.Inventory) != 1 || len(g.state.Found) != 1 || !g.state.Map.Loot[0].Collected || g.state.Summary.Loot != 1 {
27+ t.Fatalf("loot not picked up: %+v", g.state)
28+ }
29+ g.begin()
30+ if g.state.Found != nil {
31+ t.Fatal("found must reset on the next action")
32+ }
33+}
34+
35+func TestRouteAvoidsOtherUncleared(t *testing.T) {
36+ g := openGame(5, 3)
37+ g.state.Party.Y = 1
38+ g.state.Map.POIs = []model.POI{{ID: "p1", X: 2, Y: 1}}
39+ steps, err := g.path(4, 1)
40+ if err != nil {
41+ t.Fatal(err)
42+ }
43+ for _, s := range steps {
44+ if s == [2]int{2, 1} {
45+ t.Fatal("route crosses an uncleared POI")
46+ }
47+ }
48+ steps, _ = g.path(2, 1)
49+ if steps[len(steps)-1] != [2]int{2, 1} {
50+ t.Fatal("route must still reach the POI itself")
51+ }
52+}
53+
54+func TestRouteFallsBackThroughPOIInCorridor(t *testing.T) {
55+ g := openGame(5, 1)
56+ g.state.Map.POIs = []model.POI{{ID: "p1", X: 2, Y: 0}}
57+ if _, err := g.path(4, 0); err != nil {
58+ t.Fatal(err)
59+ }
60+}
61+
62+func TestDefeatFallsBackToNearestCamp(t *testing.T) {
63+ g := openGame(30, 3)
64+ g.spawn = model.SpawnPoint{X: 0, Y: 0}
65+ g.state.Map.Spawns = []model.SpawnPoint{g.spawn}
66+ g.state.Map.POIs = []model.POI{{ID: "p1", X: 20, Y: 0, Cleared: true}, {ID: "p2", X: 25, Y: 0}}
67+ x, y := g.camp(&g.state.Map.POIs[1])
68+ if x != 20 || y != 0 {
69+ t.Fatalf("camp %d,%d", x, y)
70+ }
71+ g.state.Map.POIs[0].Cleared = false
72+ if x, _ := g.camp(&g.state.Map.POIs[1]); x != 0 {
73+ t.Fatalf("camp %d", x)
74+ }
75+}
76+
77+func equipAll(g *game) {
78+ score := func(it model.Item) int {
79+ b := it.Bonus
80+ return b.MaxHP/3 + b.Attack + b.Defense + b.Magic + b.Speed/2
81+ }
82+ for _, u := range g.state.Party.Units {
83+ for _, it := range g.state.Party.Inventory {
84+ if it.Key || it.Slot == "" {
85+ continue
86+ }
87+ if old := u.Gear[it.Slot]; old == nil || score(*old) < score(it) {
88+ g.equip(model.EquipRequest{Unit: u.ID, Item: it.ID})
89+ break
90+ }
91+ }
92+ }
93+}
94+
95+func TestMainRouteIsWinnableWithoutGrinding(t *testing.T) {
96+ for seed := model.Seed(1); seed <= 40; seed++ {
97+ g := newGame("local", seed)
98+ defeats := 0
99+ for moves := 0; moves < 60 && !g.finished(); moves++ {
100+ equipAll(g)
101+ var poi *model.POI
102+ for _, s := range g.state.Campaign.Main.Steps {
103+ if !s.Done {
104+ poi = g.poi(s.POI)
105+ break
106+ }
107+ }
108+ if err := g.move(poi.X, poi.Y); err != nil {
109+ t.Fatalf("seed %d: %v", seed, err)
110+ }
111+ if g.state.Phase == "defeat" {
112+ defeats++
113+ }
114+ }
115+ if !g.finished() || defeats > 12 {
116+ t.Fatalf("seed %d: finished=%v defeats=%d", seed, g.finished(), defeats)
117+ }
118+ }
119+}
120+
121+func TestPOILevelsGrowTowardTheBoss(t *testing.T) {
122+ g := newGame("local", 5)
123+ steps := g.state.Campaign.Main.Steps
124+ first, last := g.poi(steps[0].POI), g.poi(steps[len(steps)-1].POI)
125+ if first.Level < 1 || last.Level <= first.Level {
126+ t.Fatalf("levels %d -> %d", first.Level, last.Level)
127+ }
128+}
@@ -50,12 +50,19 @@ func New(seed model.Seed, webDir string) *Server {
5050 }))
5151 s.mux.HandleFunc("GET /api/combat/log", s.handleLog)
5252 s.mux.HandleFunc("GET /api/seed", s.handleSeed)
53- s.mux.Handle("/", http.FileServer(http.Dir(webDir)))
53+ s.mux.Handle("/", noCache(http.FileServer(http.Dir(webDir))))
5454 return s
5555 }
5656
5757 func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) }
5858
59+func noCache(h http.Handler) http.Handler {
60+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
61+ w.Header().Set("Cache-Control", "no-cache")
62+ h.ServeHTTP(w, r)
63+ })
64+}
65+
5966 func decode(r *http.Request, v any) error {
6067 return json.NewDecoder(r.Body).Decode(v)
6168 }
@@ -34,13 +34,22 @@ func (c client) call(method, path string, body any, want int) model.GameState {
3434 return st
3535 }
3636
37+func lootNode(st model.GameState, id string) model.LootNode {
38+ for _, l := range st.Map.Loot {
39+ if l.ID == id {
40+ return l
41+ }
42+ }
43+ return model.LootNode{}
44+}
45+
3746 func (c client) collectAt(st model.GameState, x, y int) model.GameState {
3847 for _, l := range st.Map.Loot {
3948 if l.X != x || l.Y != y || l.Collected {
4049 continue
4150 }
4251 st = c.call("POST", "/api/move", model.MoveRequest{X: x, Y: y}, 200)
43- if st.Party.X == x && st.Party.Y == y {
52+ if st.Party.X == x && st.Party.Y == y && !lootNode(st, l.ID).Collected {
4453 st = c.call("POST", "/api/interact", model.InteractRequest{ID: l.ID}, 200)
4554 }
4655 }