xonecas.ioDon't click! Sean Caetano Martin Sign in

tiny-adventure / commits / 9084a03

Effects last one turn of the unit they land on, buffs are cast only when they pay back, the route preview counts hazard hp, and a rules update starts players on a fresh board

Rage readied nothing before: it expired at the start of the caster's next turn and only halved their defense. Now Rage doubles the caster's next attack, Rally boosts each ally's next attack, Taunt is a debuff that decides each foe's next attack, and Mark holds until the marked foe has acted. A unit casts Rage, Rally, Mark or Haste only when the damage it adds beats the attack it gives up, which cut buffs from a third of hero turns to a fifth. The permanent taunt trait is gone. /api/path returns the hp the route's hazards would cost. Saved boards carry the rules version, and a board from another version, or one that no longer replays, gives its player a new campaign instead of a 500. Key names no longer repeat within a campaign. The careful bot wins 19 of 20 seeds in 11.7 days on average.

Co-Authored-By: Claude Opus 5.5

sacenox1 day ago9084a03fd40c06c8cab3a92b4b64b7bfb0f651dcparent f35dceb20 files changed

CLAUDE.md+2-1
@@ -32,6 +32,7 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
3232 - Colours come from roles in `theme.js`: a grey ramp, one amber accent for state and the primary action, red only for danger. Radius at most 4. No gradients.
3333 - The one exception to canvas-only UI is the hidden `textarea` in `feedback.js`. It takes the typing, including paste, IME and mobile keyboards, and the form is drawn on canvas. Add no other DOM.
3434 - A game is its seed plus its action log. Every rule must give the same result when the log is replayed: no wall clock, no `math/rand` outside `rng`, no map iteration order in rules. The action's own time is `g.now`.
35+- Bump `model.Version` in any change that alters what a seed generates or how an action resolves. Saved boards from another version, and any log that fails to replay, give the player a fresh campaign. The old log stays on disk.
3536 - `window.__game` (`web/js/debug.js`) must keep working: `mode`, `busy`, `state()`, `rects()` via `setRects`, `tileScreen`, `focusTile`, `pickAt`, `perf()`. The harness reads layout only from `rects()`.
3637 - Scripts import `web/js/stats.js` and `web/js/hex.js`; keep those free of browser APIs.
3738 - Generated art: the `openrouter` skill can make images when a texture or icon is needed.
@@ -42,7 +43,7 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
4243 - Defeat ends the campaign. Any harness setup that fights through the API can end the run; pin the seed and check `phase`.
4344 - Never kill processes with `pkill -f`; it matches the agent's own shell. Find a server by port: `ss -ltnpH 'sport = :PORT'`.
4445 - Seeds above 2^53 lose precision in JS. `rng.NewSeed` stays below a million.
45-- Balance is measured with the careful bot over seeds 1 to 20 through the API. Expect about 17 wins in about 13 days. `TestCarefulPlayWinsMostCampaigns` is the fast Go guard.
46+- Balance is measured with the careful bot over seeds 1 to 20 through the API. Expect about 19 wins in about 12 days. `TestCarefulPlayWinsMostCampaigns` is the fast Go guard.
4647 - The client walks one hex per `/api/move {steps: 1}` so the player can change course. Keep `track.busy` true for the whole walk; the harness waits on it.
4748 - Every request without a player id gets a new board. The harness sends one id per process as `X-Player` from node and plants it as the `ta` cookie in the browser (`driver.mjs`). A script that calls the API without it plays alone.
4849 - The client reads each combat event's `kind` from the server. Never classify an event from the unit's own ability list: gear grants abilities too, and a heal played as damage shows a hero hit by a teammate.
README.md+3-3
@@ -37,7 +37,7 @@ Beating the boss ends the campaign with a victory screen. If the whole party fal
3737
3838 ## Playing
3939
40-- Click a hex to walk there. Roads are fast, hills, shallows and forest are slow. Hovering a hex marks the route and its length, and warns when night would fall on the way. Click another hex while walking to change course, or Esc or a click on the party to stop. Right-drag or Q/E rotates, the wheel zooms.
40+- Click a hex to walk there. Roads are fast, hills, shallows and forest are slow. Hovering a hex marks the route and its length, warns when night would fall on the way, and shows the hp its hazards would cost. Click another hex while walking to change course, or Esc or a click on the party to stop. Right-drag or Q/E rotates, the wheel zooms.
4141 - The next main objective is always marked with a light beam and labelled with its level (`Lv N`), even in the fog. J opens the journal, which marks the next step.
4242 - Walking toward a place that is still held stops you next to it and shows its defenders, your chance to win, and how much health the fight should cost. Fight (Enter) or back off (Esc).
4343 - Every hex walked spends daylight, and fights take time too. A day is long enough for several fights, so wounds pile up and potions carry you between camps. After dusk, make camp (C) once to heal everyone and start a new day, away from enemies. Shallows, mountains and harsh biomes wear the party down as it walks. P drinks a potion on the selected hero.
@@ -45,7 +45,7 @@ Beating the boss ends the campaign with a victory screen. If the whole party fal
4545 - Roaming bands chase a party that comes near, from farther away at night. Backing off from a band shakes it off for a few moves. Some chests are guarded, trapped, or mimics. Lookouts reveal the land, shrines heal, and old caches grant XP.
4646 - The main quest asks you to recover keys from the places it names. The top bar counts them, and the boss stays sealed until you hold them all.
4747 - Walking over loot picks it up. Each base item has its own stats: daggers trade attack for speed and crit, plate trades speed for defense. The inventory and the trader compare every item with the selected hero's gear. Items may carry a trait, paid for with a lower stat, and rare items also grant an ability. Enemies show their abilities, traits, weaknesses and resistances on the threat card. Prepare (G) opens the inventory with live odds, so you can gear for the fight in front of you.
48-- Fights play out one turn at a time, and you don't control them. Each hero and enemy has a role: tanks hit whoever hurt them last, strikers go for the weakest foe, casters and supports pick at random. Every unit heals, taunts, dodges and buffs when it makes sense, and otherwise uses its strongest attack against the enemies in front of it. Space or a click speeds them up. Heroes who level up hop on the board, and their gains rise above their cards. A lost fight ends the campaign.
48+- Fights play out one turn at a time, and you don't control them. Each hero and enemy has a role: tanks hit whoever hurt them last, strikers go for the weakest foe, casters and supports pick at random. Every unit heals, taunts and dodges when it makes sense, buffs only when the buff adds more damage than the attack it costs, and otherwise uses its strongest attack against the enemies in front of it. Space or a click speeds them up. Heroes who level up hop on the board, and their gains rise above …
4949 - A hero who drops to 0 hp falls and lies on the board, greyed out. They sit out fights and earn no XP until a potion (P) gets them up at half health, or a night at camp brings everyone back.
5050 - After a fight and a gear change, Give feedback? opens a short form. The note goes in with the game's anonymous log.
5151 - M toggles sound.
@@ -57,7 +57,7 @@ Beating the boss ends the campaign with a victory screen. If the whole party fal
5757 - Enemies take 1.5 times damage from the types they are weak to, and their defense covers the types they resist.
5858 - A weapon edge, such as of Embers, turns the wielder's physical abilities into that type.
5959 - Each class has a pool: fighters tank or bruise, rogues hit hard and are hard to hit, mages blast and support, clerics heal, rangers mark and shoot lightning.
60-- Effects like Taunt, Rage, Sneak, Dodge, Ward, Rally, Mark and Haste last until the caster's next turn.
60+- Effects like Taunt, Rage, Sneak, Dodge, Ward, Rally, Mark and Haste take the caster's action and last one turn of the unit they land on. Rage readies the caster's next attack, and Taunt decides each foe's next attack.
6161
6262 The full rules and numbers are in `docs/api.md`, under Combat.
6363
docs/api.md+11-11
@@ -139,20 +139,20 @@ Single-target abilities have power 1.5 and cooldown 2. Abilities that hit every
139139
140140 ### Effects
141141
142-Effects last until the caster's next turn. Nothing outlasts it: there are no stuns and no damage over time.
142+Casting an effect takes the caster's action. An effect lasts until the unit it lands on finishes its next turn, then it is gone: Rage and Rally boost that unit's next attack, Taunt decides each foe's next attack, and Mark holds until the marked foe has acted. There are no stuns and no damage over time.
143143
144144 | Ability | Kind | Effect | Cooldown |
145145 |---|---|---|---|
146146 | Heal | heal | Restores magic × 1.6 hp to the most hurt ally. | 1 |
147147 | Prayer | heal | Restores magic × 0.6 hp to every ally. | 3 |
148-| Taunt | buff | Foes must target the caster. | 2 |
149-| Rage | buff | The caster deals 60% more damage, and their defense is halved. | 2 |
148+| Taunt | debuff | Every foe's next attack must target the caster. | 2 |
149+| Rage | buff | The caster's next attack deals double damage. | 2 |
150150 | Sneak | buff | The caster can't be targeted, and their next hit is a crit. | 3 |
151151 | Dodge | buff | The caster avoids the next hit aimed at them. | 2 |
152152 | Ward | buff | Every ally guards every damage type. | 3 |
153-| Rally | buff | Every ally deals 30% more damage. | 3 |
153+| Rally | buff | Every ally's next attack deals 30% more damage. | 3 |
154154 | Haste | buff | The ally with the highest attack or magic acts at once. | 3 |
155-| Mark | debuff | One foe takes 30% more damage. | 2 |
155+| Mark | debuff | One foe takes 30% more damage until its next turn ends. | 2 |
156156
157157 ### Classes, roles and choices
158158
@@ -168,9 +168,9 @@ Each hero draws 3 abilities from their class pool when the seed is built, and at
168168
169169 Enemies draw 2 abilities from their role, and bosses 3. Tanks draw from Taunt, Rage, Heavy Strike and Cleave. Strikers draw from Sneak, Dodge, Heavy Strike and Envenom. Casters draw from their faction's single and area attacks and Ward. Supports draw from Heal, Prayer, Rally and their faction's single attack. Vampires and witches deal shadow, cultists fire, undead frost, lizardfolk and goblins poison, and the rest physical.
170170
171-Every unit chooses the same way. It uses the first of these that is ready and useful: Prayer when two allies are below 70% hp, Heal when an ally is below half, Taunt when another ally is below half and the caster is not, Dodge or Sneak when the caster is below half, Ward when the foes deal a type an ally doesn't guard, Rage when the caster is above half, then Rally, Mark and Haste. Otherwise it uses the attack with the most expected damage, counting weakness, guards and the number of foes.
171+Every unit chooses the same way. It uses the first of these that is ready and useful: Prayer when two allies are below 70% hp, Heal when an ally is below half, Taunt when another ally is below half and the caster is not, Dodge or Sneak when the caster is below half, Ward when the foes deal a type an ally doesn't guard. Rage, Rally, Mark and Haste only when the damage they add beats the attack the caster gives up: Rage counts the caster's next attack, Rally the whole party's next attacks, Mark th …
172172
173-Units pick targets by role. Sneaking units can't be picked, and taunting units must be. Tanks hit whoever last hurt them, strikers the foe with the least hp, and casters and supports a random foe.
173+Units pick targets by role. Sneaking units can't be picked, and a taunted unit attacks its taunter. Tanks hit whoever last hurt them, strikers the foe with the least hp, and casters and supports a random foe.
174174
175175 ### Traits
176176
@@ -178,7 +178,7 @@ Units pick targets by role. Sneaking units can't be picked, and taunting units m
178178 - `sweep` (weapon) splashes single-target hits onto a second foe for half. `pierce` (weapon) ignores defense.
179179 - `poison`, `fire`, `frost`, `lightning`, `holy` and `shadow` on a weapon or trinket turn the wielder's physical abilities into that type. They still scale with attack.
180180 - `guard-poison`, `guard-fire`, `guard-frost`, `guard-lightning`, `guard-holy` and `guard-shadow` on armor, a helm or a trinket let defense cut that type, and spare the hero that type's hazards.
181-- `thorns` returns 25% of a single physical or poison hit to the attacker. `taunt` makes foes target the wearer. `armored` adds 3 defense. `swarm` factions bring more, weaker enemies.
181+- `thorns` returns 25% of a single physical or poison hit to the attacker. `armored` adds 3 defense. `swarm` factions bring more, weaker enemies.
182182
183183 Gear abilities: weapons grant a single-target attack, armor Taunt, Dodge or Rage, helms Heal, Ward or Mark, and trinkets an area attack, Rally, Haste, Prayer or Sneak. `units[].abilities` lists only the hero's drawn abilities. A unit fights with those plus its gear's.
184184
@@ -224,10 +224,10 @@ Response: `GameState` with updated `party.x`, `party.y`, and possibly `threat`.
224224
225225 ## GET /api/path
226226
227-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.
227+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, `dusk` is true when night falls on the way, and `hazard` is the hp the party's hazards would cost, summed over the heroes, omitted when 0. Roaming bands move during a real walk, so the route can still change. Rejected with …
228228
229229 ```json
230-{"path": [[12, 7], [13, 7]], "time": 5, "dusk": false}
230+{"path": [[12, 7], [13, 7]], "time": 5, "dusk": false, "hazard": 4}
231231 ```
232232
233233 ## POST /api/interact
@@ -316,7 +316,7 @@ The 1200 by 630 preview image of the run, drawn with the vendored fonts and cach
316316
317317 ## Storage
318318
319-With `--data <dir>` every game is an append-only log at `games/<game>.jsonl`. The first line is a `Header` (`game`, `seed`, `started`, `version`). Each later line is an `Entry`: the action `kind`, its time `t` in Unix milliseconds, its fields, and `err` when the server rejected it. The server rebuilds a game by replaying the accepted actions on the seed, so the log is both the save and the anonymous record of play. `players/<player>` holds the id of the player's current game. `feedback.jsonl` ho …
319+With `--data <dir>` every game is an append-only log at `games/<game>.jsonl`. The first line is a `Header` (`game`, `seed`, `started`, `version`). Each later line is an `Entry`: the action `kind`, its time `t` in Unix milliseconds, its fields, and `err` when the server rejected it. The server rebuilds a game by replaying the accepted actions on the seed, so the log is both the save and the anonymous record of play. A game saved under another rules `version`, or one whose log no longer replays, i …
320320
321321 ## Limits
322322
docs/deploy.md+1-1
@@ -32,7 +32,7 @@ The game runs as a systemd user service behind Caddy. The Go server serves the p
3232 go build -o bin/server ./cmd/server
3333 systemctl --user restart tiny-adventure
3434
35-A restart keeps every game. Each player's board is rebuilt from its log on their next request.
35+A restart keeps every game. Each player's board is rebuilt from its log on their next request. When the update changes the rules, it bumps `model.Version`, and players with an older board start a new campaign on their next request. Their old logs stay in `games/`.
3636
3737 ## Read the logs
3838
internal/gen/gen_test.go+5-3
@@ -118,12 +118,14 @@ func TestSeedsVary(t *testing.T) {
118118 }
119119
120120 func TestEveryCampaignIsAKeyHuntOverPlacesOnTheMap(t *testing.T) {
121- for seed := model.Seed(1); seed <= 60; seed++ {
121+ for seed := model.Seed(1); seed <= 200; seed++ {
122122 w := Generate(seed)
123+ names := map[string]bool{}
123124 for i, s := range w.Campaign.Main.Steps[1 : len(w.Campaign.Main.Steps)-1] {
124- if s.Kind != "retrieve" || s.Slots.Item == "" {
125- t.Fatalf("seed %d: main step %d is %q with item %q", seed, i+2, s.Kind, s.Slots.Item)
125+ if s.Kind != "retrieve" || s.Slots.Item == "" || names[s.Text[:strings.Index(s.Text, " from ")]] {
126+ t.Fatalf("seed %d: main step %d is %q, %q, with item %q", seed, i+2, s.Kind, s.Text, s.Slots.Item)
126127 }
128+ names[s.Text[:strings.Index(s.Text, " from ")]] = true
127129 }
128130 for _, sys := range w.Campaign.Systems {
129131 kind, ok := strings.CutPrefix(sys, "poi:")
internal/gen/mission.go+1-1
@@ -76,7 +76,7 @@ func (q *questBuilder) side(i int, pois []model.POI) model.Mission {
7676 return model.Mission{Template: "side", Name: sideNames[i%len(sideNames)], Steps: steps}
7777 }
7878
79-var keyNames = []string{"Sunken Crown", "Bone Key", "Moonstone Sigil", "Ember Seal", "Gilded Chalice", "Black Lantern", "Serpent Idol"}
79+var keyNames = []string{"Sunken Crown", "Bone Key", "Moonstone Sigil", "Ember Seal", "Gilded Chalice", "Black Lantern", "Serpent Idol", "Iron Reliquary", "Glass Eye", "Thorn Circlet"}
8080
8181 func makeKeyItem(n int, name string) model.Item {
8282 return model.Item{ID: fmt.Sprintf("key%d", n), Name: name, Rarity: "rare", Key: true}
internal/model/api.go+1-0
@@ -8,6 +8,7 @@ type Route struct {
88 Path [][2]int `json:"path"`
99 Time int `json:"time"`
1010 Dusk bool `json:"dusk"`
11+ Hazard int `json:"hazard,omitempty"`
1112 Blocked string `json:"blocked,omitempty"`
1213 }
1314
internal/model/version.go+1-1
@@ -1,5 +1,5 @@
11 package model
22
3-const Version = 1
3+const Version = 2
44
55 type Seed int64
internal/server/hazards.go+4-4
@@ -29,13 +29,13 @@ func hazardOf(m *model.Map, x, y int) (string, string) {
2929 return "", ""
3030 }
3131
32-func (g *game) endure(x, y int, lost map[string]int) {
33- name, typ := hazardOf(&g.state.Map, x, y)
32+func endure(m *model.Map, units []model.Unit, x, y int, lost map[string]int) {
33+ name, typ := hazardOf(m, x, y)
3434 if name == "" {
3535 return
3636 }
37- for i := range g.state.Party.Units {
38- u := &g.state.Party.Units[i]
37+ for i := range units {
38+ u := &units[i]
3939 if typ != sim.Physical && sim.Guards(*u, typ) {
4040 continue
4141 }
internal/server/move.go+7-1
@@ -2,6 +2,7 @@ package server
22
33 import (
44 "errors"
5+ "slices"
56
67 "tinyadventure/internal/model"
78 "tinyadventure/internal/world"
@@ -59,7 +60,7 @@ func (g *game) move(tx, ty, limit int) error {
5960 g.pass(g.state.Map.Cost(s[0], s[1]))
6061 g.pickup(s[0], s[1])
6162 g.visit(s[0], s[1])
62- g.endure(s[0], s[1], lost)
63+ endure(&g.state.Map, g.state.Party.Units, s[0], s[1], lost)
6364 g.settle()
6465 if id := g.tickBands(); id != "" {
6566 g.threat = id
@@ -73,12 +74,17 @@ func (g *game) move(tx, ty, limit int) error {
7374 func (g *game) route(tx, ty int) (model.Route, error) {
7475 steps, err := g.path(tx, ty)
7576 out := model.Route{Path: [][2]int{}}
77+ units, lost := slices.Clone(g.state.Party.Units), map[string]int{}
7678 for _, s := range steps {
7779 if out.Blocked = g.blocker(s[0], s[1]); out.Blocked != "" {
7880 break
7981 }
8082 out.Path = append(out.Path, s)
8183 out.Time += g.state.Map.Cost(s[0], s[1])
84+ endure(&g.state.Map, units, s[0], s[1], lost)
85+ }
86+ for _, n := range lost {
87+ out.Hazard += n
8288 }
8389 c := g.state.Clock
8490 out.Dusk = !c.Night() && c.Time+out.Time >= c.DayLength
internal/server/server.go+4-4
@@ -121,11 +121,11 @@ func (s *Server) game(player string) (*game, error) {
121121 }
122122 g := s.fresh(s.first)
123123 if id := s.store.current(player); id != "" {
124- loaded, err := s.store.load(id)
125- if err != nil {
126- return nil, err
124+ if loaded, err := s.store.load(id); err != nil {
125+ log.Printf("load: %v, the player gets a new board", err)
126+ } else {
127+ g = loaded
127128 }
128- g = loaded
129129 }
130130 s.seat(player, g)
131131 return g, nil
internal/server/server_test.go+61-0
@@ -3,6 +3,7 @@ package server
33 import (
44 "bytes"
55 "encoding/json"
6+ "fmt"
67 "io"
78 "net/http"
89 "net/http/httptest"
@@ -154,6 +155,39 @@ func TestPathPreviewMatchesTheWalk(t *testing.T) {
154155 }
155156 }
156157
158+func TestPathPreviewCountsTheHazardHp(t *testing.T) {
159+ for seed := model.Seed(1); seed <= 20; seed++ {
160+ srv, c := open(t, seed, "")
161+ g, _ := srv.game(testPlayer)
162+ hp := func() int {
163+ n := 0
164+ for _, u := range g.state.Party.Units {
165+ n += u.Stats.HP
166+ }
167+ return n
168+ }
169+ for dx := -6; dx <= 6; dx++ {
170+ for dy := -6; dy <= 6; dy++ {
171+ tx, ty := g.state.Party.X+dx, g.state.Party.Y+dy
172+ route, err := g.route(tx, ty)
173+ if err != nil || route.Hazard == 0 || route.Blocked != "" {
174+ continue
175+ }
176+ before := hp()
177+ c.call("POST", "/api/move", model.Action{X: tx, Y: ty}, 200)
178+ if g.state.Party.X != tx || g.state.Party.Y != ty {
179+ t.Skipf("seed %d: a band cut the walk short", seed)
180+ }
181+ if lost := before - hp(); lost != route.Hazard {
182+ t.Fatalf("seed %d: preview %d hp, walk cost %d", seed, route.Hazard, lost)
183+ }
184+ return
185+ }
186+ }
187+ }
188+ t.Fatal("no route with a hazard near any spawn")
189+}
190+
157191 func TestTheLogReplaysToTheSameGame(t *testing.T) {
158192 dir := t.TempDir()
159193 srv, c := open(t, 7, dir)
@@ -178,6 +212,33 @@ func TestTheLogReplaysToTheSameGame(t *testing.T) {
178212 }
179213 }
180214
215+func TestBoardsThatNoLongerReplayStartOver(t *testing.T) {
216+ for name, edit := range map[string]func([]byte) []byte{
217+ "older rules": func(b []byte) []byte {
218+ return bytes.Replace(b, []byte(fmt.Sprintf(`"version":%d`, model.Version)), []byte(`"version":0`), 1)
219+ },
220+ "a rejected step": func(b []byte) []byte {
221+ return append(b, []byte(`{"kind":"equip","t":1,"unit":"u1","item":"gone"}`+"\n")...)
222+ },
223+ } {
224+ dir := t.TempDir()
225+ srv, c := open(t, 7, dir)
226+ old := firstFight(t, c)
227+ file := filepath.Join(dir, "games", old.Game+".jsonl")
228+ b, _ := os.ReadFile(file)
229+ os.WriteFile(file, edit(b), 0o644)
230+ srv.seats = map[string]*seat{}
231+ st := c.call("GET", "/api/state", nil, 200)
232+ if st.Game == old.Game || st.Summary.Battles != 0 {
233+ t.Fatalf("%s: got game %s with %d battles", name, st.Game, st.Summary.Battles)
234+ }
235+ after, _ := os.ReadFile(file)
236+ if !bytes.Equal(after, edit(b)) {
237+ t.Fatalf("%s: the old log changed", name)
238+ }
239+ }
240+}
241+
181242 func TestFeedbackOpensAfterAFightAndAGearChange(t *testing.T) {
182243 dir := t.TempDir()
183244 srv, c := open(t, 7, dir)
internal/server/store.go+3-0
@@ -109,6 +109,9 @@ func (s store) load(id string) (*game, error) {
109109 if err := json.Unmarshal(sc.Bytes(), &h); err != nil {
110110 return nil, fmt.Errorf("game %s header: %w", id, err)
111111 }
112+ if h.Version != model.Version {
113+ return nil, fmt.Errorf("game %s was saved under rules version %d, the server runs %d", id, h.Version, model.Version)
114+ }
112115 g := newGame(h.Game, h.Seed, time.UnixMilli(h.Started))
113116 g.saved = true
114117 for n := 2; sc.Scan(); n++ {
internal/sim/abilities.go+2-2
@@ -69,8 +69,8 @@ func init() {
6969 damage("shadow-bolt", "Shadow Bolt", Shadow), area("shadow-wave", "Shadow Wave", Shadow),
7070 {ID: "heal", Name: "Heal", Kind: KindHeal, Power: 1.6, Cooldown: 1, Target: TargetAlly},
7171 {ID: "prayer", Name: "Prayer", Kind: KindHeal, Power: 0.6, Cooldown: 3, Target: TargetAllAllies},
72- {ID: "taunt", Name: "Taunt", Kind: KindBuff, Cooldown: 2, Target: TargetSelf},
73- {ID: "rage", Name: "Rage", Kind: KindBuff, Power: 0.6, Cooldown: 2, Target: TargetSelf},
72+ {ID: "taunt", Name: "Taunt", Kind: KindDebuff, Cooldown: 2, Target: TargetAllEnemies},
73+ {ID: "rage", Name: "Rage", Kind: KindBuff, Power: 1, Cooldown: 2, Target: TargetSelf},
7474 {ID: "sneak", Name: "Sneak", Kind: KindBuff, Cooldown: 3, Target: TargetSelf},
7575 {ID: "dodge", Name: "Dodge", Kind: KindBuff, Cooldown: 2, Target: TargetSelf},
7676 {ID: "ward", Name: "Ward", Kind: KindBuff, Cooldown: 3, Target: TargetAllAllies},
internal/sim/choice.go+29-6
@@ -11,8 +11,8 @@ func (b *battle) pickTarget(actor *combatant, foes []*combatant) *combatant {
1111 if seen := slices.DeleteFunc(slices.Clone(foes), (*combatant).hidden); len(seen) > 0 {
1212 foes = seen
1313 }
14- if guards := slices.DeleteFunc(slices.Clone(foes), func(f *combatant) bool { return !f.taunting() }); len(guards) > 0 {
15- foes = guards
14+ if t := actor.tauntedBy(foes); t != nil {
15+ return t
1616 }
1717 switch actor.role {
1818 case RoleTank:
@@ -39,6 +39,7 @@ func (b *battle) choose(actor *combatant, extra bool) model.Ability {
3939 ready[a.ID] = a
4040 }
4141 }
42+ a := func(id string) float64 { return ready[id].Power }
4243 use := func(id string, when bool) (model.Ability, bool) {
4344 a, ok := ready[id]
4445 return a, ok && when
@@ -63,10 +64,10 @@ func (b *battle) choose(actor *combatant, extra bool) model.Ability {
6364 {"dodge", actor.hurt()},
6465 {"sneak", actor.hurt()},
6566 {"ward", !actor.under("ward") && b.threatens(foes, allies)},
66- {"rage", !actor.hurt()},
67- {"rally", true},
68- {"mark", true},
69- {"haste", len(allies) > 1},
67+ {"rage", b.payback(actor, foes, a("rage")*b.best(actor, foes, 1))},
68+ {"rally", b.payback(actor, foes, a("rally")*b.team(allies, foes, 1))},
69+ {"mark", b.payback(actor, foes, a("mark")*b.team(allies, foes, 1)/float64(len(foes)))},
70+ {"haste", len(allies) > 1 && b.payback(actor, foes, b.best(b.hasteTarget(actor), foes, 0))},
7071 } {
7172 if a, ok := use(try.id, try.when); ok {
7273 return a
@@ -84,6 +85,28 @@ func (b *battle) choose(actor *combatant, extra bool) model.Ability {
8485 return best
8586 }
8687
88+func (b *battle) payback(actor *combatant, foes []*combatant, gain float64) bool {
89+ return gain > b.best(actor, foes, 0)
90+}
91+
92+func (b *battle) best(c *combatant, foes []*combatant, slack int) float64 {
93+ top := 0.0
94+ for _, a := range slices.Concat(c.abils, []model.Ability{mustAbility(StrikeID)}) {
95+ if (a.Kind == KindDamage || a.Kind == KindAoE) && c.cd[a.ID] <= slack {
96+ top = max(top, b.expected(c, a, foes))
97+ }
98+ }
99+ return top
100+}
101+
102+func (b *battle) team(allies, foes []*combatant, slack int) float64 {
103+ n := 0.0
104+ for _, al := range allies {
105+ n += b.best(al, foes, slack)
106+ }
107+ return n
108+}
109+
87110 func (b *battle) expected(actor *combatant, a model.Ability, foes []*combatant) float64 {
88111 typ := actor.typeOf(a)
89112 total, top := 0.0, 0.0
internal/sim/combat.go+2-1
@@ -78,8 +78,9 @@ func (b *battle) act(actor *combatant, extra bool) {
7878 actor.cd[id] = v - 1
7979 }
8080 }
81- b.expire(actor)
8281 }
82+ actor.startTurn()
83+ defer actor.endTurn()
8384 a := b.choose(actor, extra)
8485 foes := b.side(1 - actor.side)
8586 switch a.Kind {
internal/sim/damage.go+0-3
@@ -44,9 +44,6 @@ func (c *combatant) defense() int {
4444 if c.has("armored") {
4545 def += armorPlus
4646 }
47- if c.under("rage") {
48- def /= 2
49- }
5047 return def
5148 }
5249
internal/sim/effects.go+24-8
@@ -11,6 +11,7 @@ type effect struct {
1111 id string
1212 owner *combatant
1313 power float64
14+ due bool
1415 }
1516
1617 func (c *combatant) under(id string) bool {
@@ -33,21 +34,32 @@ func (c *combatant) sum(id string) float64 {
3334
3435 func (c *combatant) boost() float64 { return 1 + c.sum("rage") + c.sum("rally") }
3536
37+func (c *combatant) tauntedBy(foes []*combatant) *combatant {
38+ for i := len(c.effects) - 1; i >= 0; i-- {
39+ if e := c.effects[i]; e.id == "taunt" && slices.Contains(foes, e.owner) {
40+ return e.owner
41+ }
42+ }
43+ return nil
44+}
45+
3646 func (c *combatant) exposure() float64 { return 1 + c.sum("mark") }
3747
3848 func (c *combatant) hidden() bool { return c.under("sneak") }
3949
40-func (c *combatant) taunting() bool { return c.has("taunt") || c.under("taunt") }
41-
42-func (b *battle) expire(owner *combatant) {
43- for _, c := range b.all {
44- c.effects = slices.DeleteFunc(c.effects, func(e effect) bool { return e.owner == owner })
50+func (c *combatant) startTurn() {
51+ for i := range c.effects {
52+ c.effects[i].due = true
4553 }
4654 }
4755
56+func (c *combatant) endTurn() {
57+ c.effects = slices.DeleteFunc(c.effects, func(e effect) bool { return e.due })
58+}
59+
4860 var effectText = map[string]string{
49- "taunt": "draws the foes' attacks",
50- "rage": "rages: %d%% more damage, half defense",
61+ "taunt": "must attack %s next",
62+ "rage": "rages: %d%% more damage on the next attack",
5163 "sneak": "slips out of sight",
5264 "dodge": "gets ready to dodge",
5365 "ward": "is warded against every type",
@@ -63,6 +75,8 @@ func (b *battle) cast(actor *combatant, a model.Ability) {
6375 targets = []*combatant{actor}
6476 case TargetAllAllies:
6577 targets = b.side(actor.side)
78+ case TargetAllEnemies:
79+ targets = b.side(1 - actor.side)
6680 case TargetEnemy:
6781 targets = []*combatant{b.pickTarget(actor, b.side(1-actor.side))}
6882 case TargetAlly:
@@ -73,7 +87,9 @@ func (b *battle) cast(actor *combatant, a model.Ability) {
7387 t.effects = append(t.effects, effect{id: a.ID, owner: actor, power: a.Power})
7488 }
7589 text := effectText[a.ID]
76- if a.Power > 0 {
90+ if a.ID == "taunt" {
91+ text = fmt.Sprintf(text, actor.unit.Name)
92+ } else if a.Power > 0 {
7793 text = fmt.Sprintf(text, int(a.Power*100))
7894 }
7995 b.log = append(b.log, model.CombatEvent{
internal/sim/traits.go+1-2
@@ -23,11 +23,10 @@ var itemTraits = map[string]trait{
2323 "pierce": {"of Piercing", []model.Slot{model.SlotWeapon}, model.Stats{Crit: 4}},
2424 "edge": {"", weaponTrinket, model.Stats{Magic: 2}},
2525 "thorns": {"of Thorns", armorTrinket, model.Stats{Speed: 2}},
26- "taunt": {"of the Bulwark", armorTrinket, model.Stats{Attack: 2}},
2726 "guard": {"", armorTrinket, model.Stats{Attack: 2}},
2827 }
2928
30-var traitOrder = []string{"lifesteal", "first", "sweep", "pierce", "edge", "thorns", "taunt", "guard"}
29+var traitOrder = []string{"lifesteal", "first", "sweep", "pierce", "edge", "thorns", "guard"}
3130
3231 var edgeSuffix = map[string]string{Poison: "of Venom", Fire: "of Embers", Frost: "of Rime", Lightning: "of Storms", Holy: "of Dawn", Shadow: "of Dusk"}
3332
internal/sim/traits_test.go+25-2
@@ -47,15 +47,38 @@ func TestPierceBeatsArmorAndThornsHurtBack(t *testing.T) {
4747 }
4848 }
4949
50-func TestTauntDrawsEnemyAttacks(t *testing.T) {
50+func TestTauntDecidesEachFoesNextAttackOnly(t *testing.T) {
5151 b := &battle{r: rng.New(1)}
5252 foe := newCombatant(dummy(), 1)
53- soft, tank := newCombatant(dummy(), 0), newCombatant(dummy("taunt"), 0)
53+ soft, tank := newCombatant(dummy(), 0), newCombatant(dummy(), 0)
5454 soft.hp = 1
5555 b.all = []*combatant{soft, tank, foe}
56+ b.cast(tank, mustAbility("taunt"))
57+ foe.startTurn()
5658 if got := b.pickTarget(foe, b.side(0)); got != tank {
5759 t.Fatal("taunt did not draw the attack")
5860 }
61+ foe.endTurn()
62+ if foe.tauntedBy(b.side(0)) != nil {
63+ t.Fatal("taunt outlived the foe's turn")
64+ }
65+}
66+
67+func TestRageBoostsTheCastersNextAttack(t *testing.T) {
68+ b := &battle{r: rng.New(1)}
69+ hero, foe := newCombatant(dummy(), 0), newCombatant(dummy(), 1)
70+ b.all = []*combatant{hero, foe}
71+ hero.startTurn()
72+ b.cast(hero, mustAbility("rage"))
73+ hero.endTurn()
74+ hero.startTurn()
75+ if hero.boost() != 2 {
76+ t.Fatalf("boost on the next turn is %v", hero.boost())
77+ }
78+ hero.endTurn()
79+ if hero.boost() != 1 {
80+ t.Fatalf("rage outlived the next turn: %v", hero.boost())
81+ }
5982 }
6083
6184 func TestImbueAddsTraitWithCost(t *testing.T) {