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

tiny-adventure / commits / 41107f3

Heroes draw three abilities from a class pool, damage has seven types that gear guards against, and enemies fight by role

Each class has a pool built around a role (tank, striker, caster, support), and every hero draws three abilities from it with at least one attack. Seven damage types each have a single-target and an area attack; physical and poison scale with attack, the rest with magic. Defense always cuts physical, and a guard trait or an enemy's resistance extends it to one more type, which also spares a hero that type's hazards. Taunt, Rage, Sneak, Dodge, Ward, Rally, Mark and Haste last until the caster's next turn. Enemies draw a kit from their role and their faction's type, and target by role, so fights stop all focusing the weakest hero. Every campaign is now a key hunt, and the systems list names only place kinds on the map. The careful bot wins 19 of 20 seeds; seed 20 strands an underleveled three-hero party with nothing left to fight.

Co-Authored-By: Claude Opus 5.5

sacenox1 day ago41107f3f1b887c9bf28983f9f26246163691246aparent 63daab424 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

CLAUDE.md+3-3
@@ -9,9 +9,9 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
99 - `internal/rng`: the one RNG (`math/rand/v2` PCG), `Sub(seed, tag)` streams, `Pick`, `Shuffled`, `Between`, six-digit `NewSeed`.
1010 - `internal/world`: hex math, noise, terrain bytes, pathfinding.
1111 - `internal/gen`: builds a `World` from a seed: terrain, factions, POIs, spawns, bands, loot, landmarks, missions, party, encounters.
12-- `internal/sim`: game rules that are pure functions: classes and growth, abilities, items (`BuildItem`, `RollItem`), traits and `EdgeOf`, combat, `Forecast` odds, XP.
12+- `internal/sim`: game rules that are pure functions: classes, roles, ability pools and growth (`classes.go`), the ability catalog and `Draw` (`abilities.go`), items (`BuildItem`, `RollItem`), traits, guards and `EdgeOf`, the battle loop (`combat.go`), damage and healing (`damage.go`), one-turn effects (`effects.go`), targeting and ability choice (`choice.go`), `Forecast` odds, XP.
1313 - `internal/server`: HTTP and the stateful game: move, bands, hazards, landmarks, clock and camping, shops, threat view, fights. `actions.go` is the one switch every POST goes through, `store.go` the per-game action logs and replay, `server.go` players, seats and routes, `limit.go` rate limits, `feedback.go` its gate, `run.go` and `card.go` the share page and PNG card (fonts in `internal/server/fonts`, lining numerals frozen in).
14-- `web/js`: one concern per file. `main.js` wires the flow. `kit.js` is the canvas-texture UI layer, `frames.js` its widgets, `text.js` fonts and text, `theme.js` colour roles, `layout.js` widget rects. Board and art: `board.js`, `flora.js`, `props.js`, `figures.js`, `minis.js`, `beasts.js`, `sky.js`. Feedback: `combat.js` plays the server log one turn at a time, `levelup.js` celebrates level gains above the hero cards, `route.js` draws the `/api/path` preview, `playback.js` applies one combat e …
14+- `web/js`: one concern per file. `main.js` wires the flow. `kit.js` is the canvas-texture UI layer, `frames.js` its widgets, `text.js` fonts and text, `theme.js` colour roles, `layout.js` widget rects. Board and art: `board.js`, `flora.js`, `props.js`, `figures.js`, `minis.js`, `beasts.js`, `sky.js`. Feedback: `combat.js` plays the server log one turn at a time, `levelup.js` celebrates level gains above the hero cards, `route.js` draws the `/api/path` preview, `playback.js` applies one combat e …
1515 - `deploy`: the systemd unit and Caddy block for tiny-adventure.xonecas.io. Steps in `docs/deploy.md`.
1616 - `scripts`: the harness. `serve.sh` starts a server, `driver.mjs` drives the browser, `bot.mjs` is the careful player policy shared by verify and playthrough, `fights.mjs` replays fight logs through `web/js/playback.js` and checks them against the server, `layout.mjs` checks rects.
1717
@@ -42,7 +42,7 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
4242 - Defeat ends the campaign. Any harness setup that fights through the API can end the run; pin the seed and check `phase`.
4343 - Never kill processes with `pkill -f`; it matches the agent's own shell. Find a server by port: `ss -ltnpH 'sport = :PORT'`.
4444 - 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 19 wins in about 10 to 11 days. `TestCarefulPlayWinsMostCampaigns` is the fast Go guard.
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.
4646 - 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.
4747 - 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.
4848 - 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+16-5
@@ -25,12 +25,12 @@ Everything is drawn at runtime, with no image assets. The board and miniatures t
2525
2626 The seed decides every system and its details:
2727
28-- Enabled systems: factions, hazards, key items, side quests, and which POI kinds exist (village, ruins, mine, tower, beach, camp, crypt).
28+- Enabled systems: factions, hazards, side quests, and which POI kinds are on the map (village, ruins, mine, tower, beach, camp, crypt).
2929 - Factions: names, themes and power, which set the enemy types and strength.
30-- Main mission: a template of typed steps (reach, defeat, retrieve, boss) whose slots (POI kind, faction, item) are filled from the seed. Swapping a mine and vampires for a beach and lizardfolk only changes slot values.
30+- Main mission: reach the first place, recover a key from each place after it, then face the boss. The slots (POI kind, faction, key) are filled from the seed. Swapping a mine and vampires for a beach and lizardfolk only changes slot values.
3131 - Side quests: a few smaller missions that reuse the same step types.
3232 - Spawn: the party starts at structures whose hints point to the first main step.
33-- Party: classes, stats, abilities and starting gear are rolled per seed.
33+- Party: classes, stats and starting gear are rolled per seed, and each hero draws 3 abilities from their class pool, at least one of them an attack. Some seeds give an awkward party. Gear is how you fill the gaps.
3434 - Progression: enemy level grows with distance from the spawn. Gear comes from loot found on the map and from fights. XP comes from fights. The boss fight unlocks after every other main step is done.
3535
3636 Beating the boss ends the campaign with a victory screen. If the whole party falls, it ends with a defeat screen. Both show the run's numbers and put its share link in the address bar. Copy link copies it. The link opens that result card for anyone, with a preview image for chat apps, and Play this seed starts the same campaign.
@@ -44,12 +44,23 @@ Beating the boss ends the campaign with a victory screen. If the whole party fal
4444 - Traders (T) work at the spawns and at camps and villages you cleared. They sell potions and gear.
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.
47-- 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, such as fire, lifesteal or taunt, paid for with a lower stat. Enemies show their 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. 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.
47+- 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.
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.
5252
53+## Combat in short
54+
55+- Seven damage types: physical and poison scale with attack, and fire, frost, lightning, holy and shadow with magic.
56+- Defense always cuts physical damage. A guard trait on gear, such as Fireguard, makes it cut that type too, and spares the hero that type's hazards on the map. Unguarded fire, frost, lightning, holy, shadow and poison go straight through defense.
57+- Enemies take 1.5 times damage from the types they are weak to, and their defense covers the types they resist.
58+- A weapon edge, such as of Embers, turns the wielder's physical abilities into that type.
59+- 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.
61+
62+The full rules and numbers are in `docs/api.md`, under Combat.
63+
5364 ## Check
5465
5566 `scripts/verify.sh <outdir> [seed]` runs the live-game harness at every resolution. `scripts/playthrough.sh <outdir> <seed> [width height name]` plays a whole campaign from the title to the end screen with real clicks, using the same careful bot as the verify fast-forward (`scripts/bot.mjs`), records it, and fails on a softlock, a state mismatch, a layout problem or a console error. See `docs/verification.md`.
docs/api.md+77-11
@@ -6,9 +6,9 @@ Each player has one board. The server names a player by a random 32-hex-digit id
66
77 Errors return a non-2xx status and `{"error": "message"}` (`ErrorResponse`).
88
9-Every endpoint returns a full `GameState`. After victory or defeat every POST except `/api/new` fails with 400. `phase` is one of `explore`, `combat`, `victory`, `defeat`.
9+Every endpoint returns a full `GameState`. After victory or defeat every POST except `/api/new` and `/api/feedback` fails with 400. `phase` is one of `explore`, `combat`, `victory`, `defeat`.
1010
11-`stats.hp` is a unit's current health. It carries from fight to fight and is capped by `maxHp` plus gear `maxHp` bonuses. Every item has a `value` in gold. `party.potions` counts potions.
11+`stats` are the unit's own numbers, and each worn item's `bonus` adds to them. `stats.hp` is current health. It carries from fight to fight and is capped by `maxHp` plus gear `maxHp` bonuses, so it can read above `stats.maxHp`. Empty `gear`, and `cleared` or `used` while false, are left out of the JSON. Every item has a `value` in gold. `party.potions` counts potions.
1212
1313 ## GameState example
1414
@@ -22,7 +22,7 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
2222 "systems": ["factions", "sidequests"],
2323 "factions": [{"id": "f1", "name": "Vampires", "theme": "undead", "power": 3}],
2424 "main": {
25- "template": "fetch-key",
25+ "template": "siege",
2626 "name": "The Crimson Key",
2727 "steps": [
2828 {"id": "s1", "kind": "reach", "text": "Find the mine", "slots": {"poiKind": "mine", "faction": "f1", "item": "i2"}, "poi": "poi1", "done": false}
@@ -45,7 +45,7 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
4545 {
4646 "id": "u1", "name": "Ayla", "class": "fighter", "race": "dwarf", "level": 1, "xp": 0,
4747 "stats": {"hp": 10, "maxHp": 10, "attack": 3, "defense": 1, "magic": 0, "speed": 4, "crit": 5},
48- "abilities": [{"id": "a1", "name": "Slash", "kind": "damage", "power": 1.2, "cooldown": 2, "target": "enemy"}],
48+ "abilities": [{"id": "heavy-strike", "name": "Heavy Strike", "kind": "damage", "type": "physical", "power": 1.5, "cooldown": 2, "target": "enemy"}],
4949 "gear": {}
5050 }
5151 ],
@@ -63,7 +63,7 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
6363 }
6464 ```
6565
66-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. Each log event carries its `kind`: `damage`, `magic` and `aoe` hit a foe, `heal` restores the target's hp, and `buff` raises the target's power by `amount` percent with no hp change. Lifesteal is a `heal` the attacker casts on itself, and thorns are `damage` the struck unit deals back. Replaying the events from the starting …
66+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. Each log event carries its `kind`: `damage` and `aoe` hit a foe for `amount` of damage `type`, `heal` restores the target's hp, `buff` puts an effect on an ally and `debuff` on a foe, both with no hp change. A hit with `dodged` deals 0. Lifesteal is a `heal` the attacker casts on itself, and thorns are `damage` the struck un …
6767
6868 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).
6969
@@ -71,7 +71,7 @@ Optional fields: `encounter` (`Encounter`, present after a fight), `rewards` (`R
7171
7272 A hero at 0 hp is fallen. A fallen hero sits out fights and the odds, earns no XP, and takes no hazard or trap damage. A potion brings them back at potion strength, and camp brings every fallen hero back at full health. A shrine heals only the living.
7373
74-A lost fight sets `phase: "defeat"` and every hero's `hp` to 0. The campaign is over: every action except `/api/new` fails with 400.
74+A lost fight sets `phase: "defeat"` and every hero's `hp` to 0. The campaign is over: every action except `/api/new` and `/api/feedback` fails with 400.
7575
7676 ## Clock
7777
@@ -109,12 +109,78 @@ A cleared band stays `cleared`. Backing off from a band's threat sets its `calm`
109109
110110 `loot[].trap` chests wound the party on pickup unless a rogue or ranger disarms them.
111111
112-Units carry `race`. Enemies also carry `traits`, `weak` and `resist`. Items may carry one `trait`, paid for with a lower stat. Traits:
112+Units carry `race`. Enemies also carry `traits`, `weak` and `resist`. Items may carry one `trait`, paid for with a lower stat, and rare or better items grant one ability in their `abilities` list. Traits are listed under Combat.
113113
114-- `lifesteal`, `first`, `cleave`, `pierce`, `thorns`, `taunt`, `ward`, `armored`, `swarm`, `shadow`.
115-- The elements `fire`, `frost` and `holy`.
114+`trail` lists the hexes the party walked in the latest move. `notes` lists what the walk caused, such as hazard damage, a trap, a shrine or a lookout. Shallows, mountains and three harsh biomes cost 2% of each hero's health per hex walked, never below 1 hp. Each hazard has a damage type: wading and Rime fen are frost, Mistbog is poison, Ember badlands are fire, and the climb is physical. A hero who guards the type is spared. Nothing spares the climb.
116115
117-`trail` lists the hexes the party walked in the latest move. `notes` lists what the walk caused, such as hazard damage, a trap, a shrine or a lookout. Shallows, mountains and three harsh biomes cost 2% of each hero's health per hex walked, never below 1 hp. A hero with `ward` is immune.
116+## Combat
117+
118+A fight runs in rounds. Each round every standing unit acts once, fastest first (`first` acts before everyone in round 1). A unit uses one ability a turn, or `strike` when nothing else is ready. A fight lasts at most 40 rounds, and a draw is a defeat.
119+
120+### Damage types and defense
121+
122+There are seven damage types. `physical` and `poison` scale with `attack`, the other five with `magic`.
123+
124+ damage = stat × power × roll(0.85 to 1.15) × 2 on a crit × 1.5 on a weakness × 10 / (10 + defense)
125+
126+The defense factor applies only when the target guards the type. Every unit guards `physical`. A hero guards another type with a `guard-<type>` trait, an enemy with its `resist` list, and Ward guards every type. Unguarded damage ignores defense. `weak` lists the types an enemy takes 1.5 times damage from. `crit` is the percent chance of a crit. Damage is at least 1.
127+
128+| Type | Stat | Single target | Every foe |
129+|---|---|---|---|
130+| `physical` | attack | Heavy Strike | Cleave |
131+| `poison` | attack | Envenom | Poison Cloud |
132+| `fire` | magic | Firebolt | Fireball |
133+| `frost` | magic | Ice Lance | Frost Nova |
134+| `lightning` | magic | Lightning Bolt | Chain Lightning |
135+| `holy` | magic | Smite | Radiance |
136+| `shadow` | magic | Shadow Bolt | Shadow Wave |
137+
138+Single-target abilities have power 1.5 and cooldown 2. Abilities that hit every foe have power 0.7 and cooldown 3. Strike is physical, power 1, no cooldown. A cooldown of N means N of the unit's own turns pass before the ability is ready again.
139+
140+### Effects
141+
142+Effects last until the caster's next turn. Nothing outlasts it: there are no stuns and no damage over time.
143+
144+| Ability | Kind | Effect | Cooldown |
145+|---|---|---|---|
146+| Heal | heal | Restores magic × 1.6 hp to the most hurt ally. | 1 |
147+| 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 |
150+| Sneak | buff | The caster can't be targeted, and their next hit is a crit. | 3 |
151+| Dodge | buff | The caster avoids the next hit aimed at them. | 2 |
152+| Ward | buff | Every ally guards every damage type. | 3 |
153+| Rally | buff | Every ally deals 30% more damage. | 3 |
154+| Haste | buff | The ally with the highest attack or magic acts at once. | 3 |
155+| Mark | debuff | One foe takes 30% more damage. | 2 |
156+
157+### Classes, roles and choices
158+
159+Each hero draws 3 abilities from their class pool when the seed is built, and at least one of them deals damage.
160+
161+| Class | Role | Pool |
162+|---|---|---|
163+| fighter | tank | Taunt, Rage, Heavy Strike, Cleave, Rally |
164+| rogue | striker | Sneak, Dodge, Heavy Strike, Envenom, Poison Cloud |
165+| mage | caster | Haste, Ward, Firebolt, Fireball, Ice Lance, Frost Nova |
166+| cleric | support | Heal, Prayer, Rally, Smite, Radiance |
167+| ranger | striker | Mark, Dodge, Heavy Strike, Lightning Bolt, Chain Lightning |
168+
169+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.
170+
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.
172+
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.
174+
175+### Traits
176+
177+- `lifesteal` heals 30% of damage dealt. `first` acts first in round 1, and the first hit deals 50% more.
178+- `sweep` (weapon) splashes single-target hits onto a second foe for half. `pierce` (weapon) ignores defense.
179+- `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.
180+- `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.
182+
183+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.
118184
119185 ## GET /api/state
120186
@@ -148,7 +214,7 @@ Moves the party toward hex `x,y`. The server paths over walkable hexes and retur
148214 {"band": "band1", "enemies": [], "odds": 64, "wounds": 50, "edge": {"hits": [], "blunted": ["frost (Cael)"]}}
149215 ```
150216
151-`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` …
217+`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 who deals a type an enemy is weak to, or has pierce against armor. It also names each hero who deals a type the enemies resist. Start the fight with `POST /api/interact` on the POI or band …
152218
153219 ```json
154220 {"x": 12, "y": 7, "steps": 1}
internal/gen/encounters.go+13-8
@@ -7,6 +7,7 @@ import (
77
88 "tinyadventure/internal/model"
99 "tinyadventure/internal/rng"
10+ "tinyadventure/internal/sim"
1011 )
1112
1213 var bossEpithets = []string{"the Pale", "the Unbroken", "the Hungering", "of the Long Night", "the Merciless", "Ironhand"}
@@ -17,7 +18,7 @@ func bossName(r *rand.Rand, f model.Faction) string {
1718 return fmt.Sprintf("%s %s %s", rng.Pick(r, d.titles), rng.Pick(r, bossNames), rng.Pick(r, bossEpithets))
1819 }
1920
20-func enemy(r *rand.Rand, id string, l look, f model.Faction, level int, hpMult, atkMult float64) model.Unit {
21+func enemy(r *rand.Rand, id string, l look, f model.Faction, level int, hpMult, atkMult float64, kit int) model.Unit {
2122 hp := int(float64(hpBase+level*hpGrow+r.IntN(5)) * hpMult)
2223 n := natures[defOf(f).name]
2324 return model.Unit{
@@ -25,14 +26,18 @@ func enemy(r *rand.Rand, id string, l look, f model.Faction, level int, hpMult,
2526 ID: id, Name: l.name, Race: l.race, Class: l.class, Faction: f.ID, Level: level,
2627 Stats: model.Stats{
2728 HP: hp, MaxHP: hp, Attack: int(float64(atkBase+level*atkGrow/2) * atkMult), Defense: 1 + level/2,
28- Magic: level, Speed: rng.Between(r, 3, 7), Crit: 5,
29+ Magic: int(float64(atkBase+level*atkGrow/2) * atkMult * magicMult), Speed: rng.Between(r, 3, 7), Crit: 5,
2930 },
30- Abilities: []model.Ability{{ID: "strike", Name: "Strike", Kind: "damage", Power: 1.0, Cooldown: 0, Target: "enemy"}},
31+ Abilities: sim.EnemyKit(r, l.class, n.typ, kit),
3132 }
3233 }
3334
35+const minionKit, bossKit = 2, 3
36+
37+const magicMult = 0.6
38+
3439 const (
35- hpBase, hpGrow, atkBase, atkGrow = 22, 11, 11, 5
40+ hpBase, hpGrow, atkBase, atkGrow = 22, 11, 10, 5
3641 bossHP, bossAtk = 1.7, 1.1
3742 swarmHP, swarmAtk = 0.65, 0.8
3843 )
@@ -49,7 +54,7 @@ func buildEncounter(r *rand.Rand, poi model.POI, f model.Faction, level int, bos
4954 e := model.Encounter{ID: "enc-" + poi.ID, POI: poi.ID}
5055 if boss != "" {
5156 e.Boss = true
52- e.Enemies = append(e.Enemies, enemy(r, e.ID+"-boss", look{boss, d.boss.race, d.boss.class}, f, level+1, bossHP, bossAtk))
57+ e.Enemies = append(e.Enemies, enemy(r, e.ID+"-boss", look{boss, d.boss.race, d.boss.class}, f, level+1, bossHP, bossAtk, bossKit))
5358 }
5459 count := rng.Between(r, 2, 2+min(2, level/3))
5560 if boss != "" {
@@ -57,7 +62,7 @@ func buildEncounter(r *rand.Rand, poi model.POI, f model.Faction, level int, bos
5762 }
5863 count, hpMult, atkMult := squad(d, count)
5964 for i := range count {
60- e.Enemies = append(e.Enemies, enemy(r, fmt.Sprintf("%s-e%d", e.ID, i+1), rng.Pick(r, d.minions), f, level, hpMult, atkMult))
65+ e.Enemies = append(e.Enemies, enemy(r, fmt.Sprintf("%s-e%d", e.ID, i+1), rng.Pick(r, d.minions), f, level, hpMult, atkMult, minionKit))
6166 }
6267 return e
6368 }
@@ -67,7 +72,7 @@ const mimicHP, mimicAtk = 1.8, 1.3
6772 func buildBandEncounter(r *rand.Rand, b model.Band, f model.Faction) model.Encounter {
6873 e := model.Encounter{ID: "enc-" + b.ID, POI: b.ID}
6974 if b.Kind == "mimic" {
70- m := enemy(r, e.ID+"-m", look{"Mimic", "beast", "mimic"}, f, b.Level, mimicHP, mimicAtk)
75+ m := enemy(r, e.ID+"-m", look{"Mimic", "beast", "mimic"}, f, b.Level, mimicHP, mimicAtk, minionKit)
7176 m.Traits = []string{"first"}
7277 e.Enemies = []model.Unit{m}
7378 return e
@@ -75,7 +80,7 @@ func buildBandEncounter(r *rand.Rand, b model.Band, f model.Faction) model.Encou
7580 d := defOf(f)
7681 count, hpMult, atkMult := squad(d, 2)
7782 for i := range count {
78- e.Enemies = append(e.Enemies, enemy(r, fmt.Sprintf("%s-e%d", e.ID, i+1), rng.Pick(r, d.minions), f, b.Level, hpMult, atkMult))
83+ e.Enemies = append(e.Enemies, enemy(r, fmt.Sprintf("%s-e%d", e.ID, i+1), rng.Pick(r, d.minions), f, b.Level, hpMult, atkMult, minionKit))
7984 }
8085 return e
8186 }
internal/gen/factions.go+14-10
@@ -6,6 +6,7 @@ import (
66
77 "tinyadventure/internal/model"
88 "tinyadventure/internal/rng"
9+ "tinyadventure/internal/sim"
910 )
1011
1112 type look struct{ name, race, class string }
@@ -18,18 +19,21 @@ type factionDef struct {
1819 titles []string
1920 }
2021
21-type nature struct{ traits, weak, resist []string }
22+type nature struct {
23+ typ string
24+ traits, weak, resist []string
25+}
2226
2327 var natures = map[string]nature{
24- "Vampires": {[]string{"lifesteal", "shadow"}, []string{"holy", "fire"}, []string{"frost", "shadow"}},
25- "Lizardfolk": {[]string{"thorns"}, []string{"frost"}, []string{"fire"}},
26- "Bandits": {[]string{"first"}, nil, nil},
27- "Undead": {[]string{"armored", "frost"}, []string{"holy", "fire"}, []string{"frost", "shadow"}},
28- "Cultists": {[]string{"fire"}, []string{"frost"}, []string{"fire", "shadow"}},
29- "Goblins": {[]string{"swarm", "first"}, []string{"fire"}, nil},
30- "Beastkin": {[]string{"swarm", "thorns"}, []string{"fire"}, []string{"frost"}},
31- "Witches": {[]string{"shadow", "ward"}, []string{"holy"}, []string{"shadow", "frost"}},
32- "Wildlings": {[]string{"swarm"}, []string{"fire"}, nil},
28+ "Vampires": {sim.Shadow, []string{"lifesteal"}, []string{"holy", "fire"}, []string{"frost", "shadow"}},
29+ "Lizardfolk": {sim.Poison, []string{"thorns"}, []string{"frost", "lightning"}, []string{"fire", "poison"}},
30+ "Bandits": {sim.Physical, []string{"first"}, []string{"poison"}, nil},
31+ "Undead": {sim.Frost, []string{"armored"}, []string{"holy", "fire"}, []string{"frost", "shadow", "poison"}},
32+ "Cultists": {sim.Fire, nil, []string{"frost", "lightning"}, []string{"fire", "shadow"}},
33+ "Goblins": {sim.Poison, []string{"swarm", "first"}, []string{"fire"}, []string{"poison"}},
34+ "Beastkin": {sim.Physical, []string{"swarm", "thorns"}, []string{"fire"}, []string{"frost"}},
35+ "Witches": {sim.Shadow, nil, []string{"holy"}, []string{"shadow", "frost"}},
36+ "Wildlings": {sim.Physical, []string{"swarm"}, []string{"fire"}, nil},
3337 }
3438
3539 var factionPool = []factionDef{
internal/gen/gen.go+3-0
@@ -37,6 +37,9 @@ func Generate(seed model.Seed) World {
3737 main := mainland(&m)
3838 spawns := buildSpawns(lr, &m, main)
3939 pois := layoutPOIs(&layout{r: lr, sys: sys, m: &m, main: main, spawns: spawns, byPower: byPower, harsh: harshest(toward)}, nMain, nSide)
40+ sys.POIKinds = slices.DeleteFunc(sys.POIKinds, func(k string) bool {
41+ return !slices.ContainsFunc(pois, func(p model.POI) bool { return p.Kind == k })
42+ })
4043 boss := pois[nMain-1]
4144 maxDist := world.Distance(boss.X, boss.Y, spawns[0].X, spawns[0].Y)
4245
internal/gen/gen_test.go+30-0
@@ -2,11 +2,13 @@ package gen
22
33 import (
44 "reflect"
5+ "slices"
56 "strings"
67 "testing"
78
89 "tinyadventure/internal/model"
910 "tinyadventure/internal/rng"
11+ "tinyadventure/internal/sim"
1012 "tinyadventure/internal/world"
1113 )
1214
@@ -114,3 +116,31 @@ func TestSeedsVary(t *testing.T) {
114116 t.Fatalf("too little variety: %d %d %d", len(systems), len(factions), len(names))
115117 }
116118 }
119+
120+func TestEveryCampaignIsAKeyHuntOverPlacesOnTheMap(t *testing.T) {
121+ for seed := model.Seed(1); seed <= 60; seed++ {
122+ w := Generate(seed)
123+ 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)
126+ }
127+ }
128+ for _, sys := range w.Campaign.Systems {
129+ kind, ok := strings.CutPrefix(sys, "poi:")
130+ if ok && !slices.ContainsFunc(w.Map.POIs, func(p model.POI) bool { return p.Kind == kind }) {
131+ t.Fatalf("seed %d lists %s with no %s on the map", seed, sys, kind)
132+ }
133+ }
134+ }
135+}
136+
137+func TestEveryHeroDrawsThreeAbilitiesWithOneThatHits(t *testing.T) {
138+ for seed := model.Seed(1); seed <= 60; seed++ {
139+ for _, u := range Generate(seed).Party.Units {
140+ hits := slices.ContainsFunc(u.Abilities, func(a model.Ability) bool { return a.Kind == sim.KindDamage || a.Kind == sim.KindAoE })
141+ if len(u.Abilities) != sim.Drawn || !hits {
142+ t.Fatalf("seed %d %s %s: %+v", seed, u.Class, u.Name, u.Abilities)
143+ }
144+ }
145+ }
146+}
internal/gen/mission.go+1-5
@@ -47,16 +47,12 @@ func (q *questBuilder) step(id string, kind string, poi model.POI) model.Mission
4747 }
4848
4949 func (q *questBuilder) main(pois []model.POI, boss string) model.Mission {
50- kinds := kindsFor(q.sys)
5150 last := pois[len(pois)-1]
5251 steps := make([]model.MissionStep, 0, len(pois))
5352 for i, p := range pois[:len(pois)-1] {
5453 kind := "reach"
55- switch {
56- case i > 0 && q.sys.KeyItems:
54+ if i > 0 {
5755 kind = "retrieve"
58- case i > 0:
59- kind = rng.Pick(q.r, kinds)
6056 }
6157 steps = append(steps, q.step(fmt.Sprintf("m%d", i+1), kind, p))
6258 }
internal/gen/party.go+1-1
@@ -38,7 +38,7 @@ func rollParty(r *rand.Rand, spawn model.SpawnPoint) model.Party {
3838 HP: hp, MaxHP: hp, Attack: b.Attack + rc.atk + r.IntN(3), Defense: b.Defense + rc.def + r.IntN(2),
3939 Magic: b.Magic + rc.mag + r.IntN(3), Speed: rng.Between(r, 3, 8) + rc.speed, Crit: rng.Between(r, 3, 10) + rc.crit,
4040 },
41- Abilities: sim.Abilities(c.Abilities...),
41+ Abilities: sim.Draw(r, c.Pool, sim.Drawn),
4242 Gear: model.Gear{},
4343 }
4444 for _, s := range rng.Shuffled(r, sim.Slots)[:rng.Between(r, 2, 3)] {
internal/gen/systems.go+1-3
@@ -10,7 +10,6 @@ var allPOIKinds = []string{"mine", "beach", "ruins", "crypt", "village", "tower"
1010
1111 type Systems struct {
1212 Factions bool
13- KeyItems bool
1413 SideQuest bool
1514 Hazards bool
1615 POIKinds []string
@@ -20,7 +19,6 @@ func rollSystems(r *rand.Rand) Systems {
2019 kinds := rng.Shuffled(r, allPOIKinds)[:rng.Between(r, 4, len(allPOIKinds))]
2120 return Systems{
2221 Factions: r.IntN(4) != 0,
23- KeyItems: r.IntN(4) != 0,
2422 SideQuest: r.IntN(4) != 0,
2523 Hazards: r.IntN(2) == 0,
2624 POIKinds: kinds,
@@ -29,7 +27,7 @@ func rollSystems(r *rand.Rand) Systems {
2927
3028 func (s Systems) List() []string {
3129 var out []string
32- for name, on := range map[string]bool{"factions": s.Factions, "keyitems": s.KeyItems, "sidequests": s.SideQuest, "hazards": s.Hazards} {
30+ for name, on := range map[string]bool{"factions": s.Factions, "sidequests": s.SideQuest, "hazards": s.Hazards} {
3331 if on {
3432 out = append(out, name)
3533 }
internal/model/ability.go+1-0
@@ -4,6 +4,7 @@ type Ability struct {
44 ID string `json:"id"`
55 Name string `json:"name"`
66 Kind string `json:"kind"`
7+ Type string `json:"type,omitempty"`
78 Power float64 `json:"power"`
89 Cooldown int `json:"cooldown"`
910 Target string `json:"target"`
internal/model/combat.go+2-0
@@ -29,7 +29,9 @@ type CombatEvent struct {
2929 Target string `json:"target"`
3030 Ability string `json:"ability"`
3131 Kind string `json:"kind"`
32+ Type string `json:"type,omitempty"`
3233 Amount int `json:"amount"`
34+ Dodged bool `json:"dodged,omitempty"`
3335 Crit bool `json:"crit,omitempty"`
3436 Killed bool `json:"killed,omitempty"`
3537 Text string `json:"text"`
internal/server/danger_test.go+1-1
@@ -52,7 +52,7 @@ func TestHazardsSapButNeverKill(t *testing.T) {
5252 g.state.Map.Hex(x, 0)[0] = model.ShapeShallow
5353 }
5454 g.state.Party = party("fighter", "mage")
55- g.state.Party.Units[1].Gear = model.Gear{model.SlotArmor: &model.Item{ID: "w", Trait: "ward"}}
55+ g.state.Party.Units[1].Gear = model.Gear{model.SlotArmor: &model.Item{ID: "w", Trait: "guard-frost"}}
5656 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 {
internal/server/game.go+1-1
@@ -160,7 +160,7 @@ func (g *game) bossGate(p *model.POI) bool {
160160 func (g *game) tally(log []model.CombatEvent) {
161161 sum := &g.state.Summary
162162 for _, e := range log {
163- if e.Kind == sim.KindHeal || e.Kind == sim.KindBuff {
163+ if e.Kind == sim.KindHeal || e.Kind == sim.KindBuff || e.Kind == sim.KindDebuff {
164164 continue
165165 }
166166 if g.unit(e.Actor) != nil {
internal/server/hazards.go+11-10
@@ -11,31 +11,32 @@ import (
1111
1212 const hazardPC = 2
1313
14-var hazardBiomes = map[byte]bool{2: true, 5: true, 6: true}
14+var hazardBiomes = map[byte]string{2: sim.Frost, 5: sim.Poison, 6: sim.Fire}
1515
16-func hazardOf(m *model.Map, x, y int) string {
16+func hazardOf(m *model.Map, x, y int) (string, string) {
1717 h := m.Hex(x, y)
1818 switch {
1919 case h[3]&model.FlagRoad != 0:
20- return ""
20+ return "", ""
2121 case h[0] == model.ShapeShallow:
22- return "Wading"
22+ return "Wading", sim.Frost
2323 case h[0] == model.ShapeMountain:
24- return "The climb"
25- case hazardBiomes[h[1]]:
26- return model.Biomes[h[1]]
24+ return "The climb", sim.Physical
2725 }
28- return ""
26+ if typ, ok := hazardBiomes[h[1]]; ok {
27+ return model.Biomes[h[1]], typ
28+ }
29+ return "", ""
2930 }
3031
3132 func (g *game) endure(x, y int, lost map[string]int) {
32- name := hazardOf(&g.state.Map, x, y)
33+ name, typ := hazardOf(&g.state.Map, x, y)
3334 if name == "" {
3435 return
3536 }
3637 for i := range g.state.Party.Units {
3738 u := &g.state.Party.Units[i]
38- if slices.Contains(sim.TraitsOf(*u), "ward") {
39+ if typ != sim.Physical && sim.Guards(*u, typ) {
3940 continue
4041 }
4142 hit := min(u.Stats.HP-1, max(1, sim.Effective(*u).MaxHP*hazardPC/100))
internal/sim/abilities.go+69-17
@@ -1,43 +1,82 @@
11 package sim
22
3-import "tinyadventure/internal/model"
3+import (
4+ "math/rand/v2"
5+ "slices"
6+
7+ "tinyadventure/internal/model"
8+ "tinyadventure/internal/rng"
9+)
410
511 const (
612 KindDamage = "damage"
7- KindMagic = "magic"
813 KindAoE = "aoe"
914 KindHeal = "heal"
1015 KindBuff = "buff"
16+ KindDebuff = "debuff"
1117
1218 TargetEnemy = "enemy"
1319 TargetAllEnemies = "all_enemies"
1420 TargetAlly = "ally"
1521 TargetAllAllies = "all_allies"
22+ TargetSelf = "self"
23+)
24+
25+const (
26+ Physical = "physical"
27+ Poison = "poison"
28+ Fire = "fire"
29+ Frost = "frost"
30+ Lightning = "lightning"
31+ Holy = "holy"
32+ Shadow = "shadow"
1633 )
1734
35+var Types = []string{Physical, Poison, Fire, Frost, Lightning, Holy, Shadow}
36+
37+var Elements = Types[1:]
38+
39+func usesAttack(t string) bool { return t == Physical || t == Poison }
40+
1841 const StrikeID = "strike"
1942
43+const (
44+ strikePower, aoePower = 1.5, 0.7
45+ strikeCD, aoeCD = 2, 3
46+)
47+
2048 var catalog = map[string]model.Ability{}
2149
2250 func register(a model.Ability) { catalog[a.ID] = a }
2351
52+func damage(id, name, typ string) model.Ability {
53+ return model.Ability{ID: id, Name: name, Kind: KindDamage, Type: typ, Power: strikePower, Cooldown: strikeCD, Target: TargetEnemy}
54+}
55+
56+func area(id, name, typ string) model.Ability {
57+ return model.Ability{ID: id, Name: name, Kind: KindAoE, Type: typ, Power: aoePower, Cooldown: aoeCD, Target: TargetAllEnemies}
58+}
59+
2460 func init() {
2561 for _, a := range []model.Ability{
26- {ID: StrikeID, Name: "Strike", Kind: KindDamage, Power: 1.0, Cooldown: 0, Target: TargetEnemy},
27- {ID: "power-strike", Name: "Power Strike", Kind: KindDamage, Power: 1.7, Cooldown: 2, Target: TargetEnemy},
28- {ID: "backstab", Name: "Backstab", Kind: KindDamage, Power: 2.0, Cooldown: 2, Target: TargetEnemy},
29- {ID: "firebolt", Name: "Firebolt", Kind: KindMagic, Power: 1.2, Cooldown: 0, Target: TargetEnemy},
30- {ID: "fireball", Name: "Fireball", Kind: KindAoE, Power: 0.8, Cooldown: 3, Target: TargetAllEnemies},
31- {ID: "smite", Name: "Smite", Kind: KindMagic, Power: 1.0, Cooldown: 0, Target: TargetEnemy},
32- {ID: "heal", Name: "Healing Word", Kind: KindHeal, Power: 1.6, Cooldown: 1, Target: TargetAlly},
33- {ID: "rally", Name: "Rally", Kind: KindBuff, Power: 0.25, Cooldown: 5, Target: TargetAllAllies},
34- {ID: "cleave", Name: "Cleave", Kind: KindAoE, Power: 0.7, Cooldown: 3, Target: TargetAllEnemies},
35- {ID: "mend", Name: "Mend", Kind: KindHeal, Power: 1.3, Cooldown: 2, Target: TargetAlly},
36- {ID: "shield-bash", Name: "Shield Bash", Kind: KindDamage, Power: 0.9, Cooldown: 3, Target: TargetEnemy},
37- {ID: "poison-dart", Name: "Poison Dart", Kind: KindDamage, Power: 1.1, Cooldown: 2, Target: TargetEnemy},
38- {ID: "frost-nova", Name: "Frost Nova", Kind: KindAoE, Power: 0.8, Cooldown: 3, Target: TargetAllEnemies},
39- {ID: "piercing-shot", Name: "Piercing Shot", Kind: KindDamage, Power: 1.4, Cooldown: 2, Target: TargetEnemy},
40- {ID: "volley", Name: "Volley", Kind: KindAoE, Power: 0.6, Cooldown: 3, Target: TargetAllEnemies},
62+ {ID: StrikeID, Name: "Strike", Kind: KindDamage, Type: Physical, Power: 1.0, Target: TargetEnemy},
63+ damage("heavy-strike", "Heavy Strike", Physical), area("cleave", "Cleave", Physical),
64+ damage("envenom", "Envenom", Poison), area("poison-cloud", "Poison Cloud", Poison),
65+ damage("firebolt", "Firebolt", Fire), area("fireball", "Fireball", Fire),
66+ damage("ice-lance", "Ice Lance", Frost), area("frost-nova", "Frost Nova", Frost),
67+ damage("lightning-bolt", "Lightning Bolt", Lightning), area("chain-lightning", "Chain Lightning", Lightning),
68+ damage("smite", "Smite", Holy), area("radiance", "Radiance", Holy),
69+ damage("shadow-bolt", "Shadow Bolt", Shadow), area("shadow-wave", "Shadow Wave", Shadow),
70+ {ID: "heal", Name: "Heal", Kind: KindHeal, Power: 1.6, Cooldown: 1, Target: TargetAlly},
71+ {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},
74+ {ID: "sneak", Name: "Sneak", Kind: KindBuff, Cooldown: 3, Target: TargetSelf},
75+ {ID: "dodge", Name: "Dodge", Kind: KindBuff, Cooldown: 2, Target: TargetSelf},
76+ {ID: "ward", Name: "Ward", Kind: KindBuff, Cooldown: 3, Target: TargetAllAllies},
77+ {ID: "rally", Name: "Rally", Kind: KindBuff, Power: 0.3, Cooldown: 3, Target: TargetAllAllies},
78+ {ID: "haste", Name: "Haste", Kind: KindBuff, Cooldown: 3, Target: TargetAlly},
79+ {ID: "mark", Name: "Mark", Kind: KindDebuff, Power: 0.3, Cooldown: 2, Target: TargetEnemy},
4180 } {
4281 register(a)
4382 }
@@ -57,3 +96,16 @@ func Abilities(ids ...string) []model.Ability {
5796 }
5897 return out
5998 }
99+
100+func dealsDamage(id string) bool {
101+ k := catalog[id].Kind
102+ return k == KindDamage || k == KindAoE
103+}
104+
105+func Draw(r *rand.Rand, pool []string, n int) []model.Ability {
106+ ids := rng.Shuffled(r, pool)[:min(n, len(pool))]
107+ if !slices.ContainsFunc(ids, dealsDamage) {
108+ ids[len(ids)-1] = rng.Pick(r, slices.DeleteFunc(slices.Clone(pool), func(id string) bool { return !dealsDamage(id) }))
109+ }
110+ return Abilities(ids...)
111+}
internal/sim/choice.go+120-0
@@ -0,0 +1,120 @@
1+package sim
2+
3+import (
4+ "slices"
5+
6+ "tinyadventure/internal/model"
7+ "tinyadventure/internal/rng"
8+)
9+
10+func (b *battle) pickTarget(actor *combatant, foes []*combatant) *combatant {
11+ if seen := slices.DeleteFunc(slices.Clone(foes), (*combatant).hidden); len(seen) > 0 {
12+ foes = seen
13+ }
14+ if guards := slices.DeleteFunc(slices.Clone(foes), func(f *combatant) bool { return !f.taunting() }); len(guards) > 0 {
15+ foes = guards
16+ }
17+ switch actor.role {
18+ case RoleTank:
19+ if slices.Contains(foes, actor.hurtBy) {
20+ return actor.hurtBy
21+ }
22+ case RoleStriker:
23+ best := foes[0]
24+ for _, f := range foes[1:] {
25+ if f.hp < best.hp {
26+ best = f
27+ }
28+ }
29+ return best
30+ }
31+ return rng.Pick(b.r, foes)
32+}
33+
34+func (b *battle) choose(actor *combatant, extra bool) model.Ability {
35+ allies, foes := b.side(actor.side), b.side(1-actor.side)
36+ ready := map[string]model.Ability{}
37+ for _, a := range actor.abils {
38+ if actor.cd[a.ID] == 0 && !(extra && a.ID == "haste") {
39+ ready[a.ID] = a
40+ }
41+ }
42+ use := func(id string, when bool) (model.Ability, bool) {
43+ a, ok := ready[id]
44+ return a, ok && when
45+ }
46+ low := 0
47+ hurt := false
48+ for _, al := range allies {
49+ if al.hp*10 < al.stats.MaxHP*7 {
50+ low++
51+ }
52+ if al != actor && al.hurt() {
53+ hurt = true
54+ }
55+ }
56+ for _, try := range []struct {
57+ id string
58+ when bool
59+ }{
60+ {"prayer", low >= 2},
61+ {"heal", slices.ContainsFunc(allies, (*combatant).hurt)},
62+ {"taunt", hurt && !actor.hurt()},
63+ {"dodge", actor.hurt()},
64+ {"sneak", actor.hurt()},
65+ {"ward", !actor.under("ward") && b.threatens(foes, allies)},
66+ {"rage", !actor.hurt()},
67+ {"rally", true},
68+ {"mark", true},
69+ {"haste", len(allies) > 1},
70+ } {
71+ if a, ok := use(try.id, try.when); ok {
72+ return a
73+ }
74+ }
75+ best, bestScore := mustAbility(StrikeID), -1.0
76+ for _, a := range slices.Concat(actor.abils, []model.Ability{best}) {
77+ if (a.Kind != KindDamage && a.Kind != KindAoE) || actor.cd[a.ID] > 0 {
78+ continue
79+ }
80+ if s := b.expected(actor, a, foes); s > bestScore {
81+ best, bestScore = a, s
82+ }
83+ }
84+ return best
85+}
86+
87+func (b *battle) expected(actor *combatant, a model.Ability, foes []*combatant) float64 {
88+ typ := actor.typeOf(a)
89+ total, top := 0.0, 0.0
90+ for _, f := range foes {
91+ v := float64(max(actor.statFor(a), 1)) * a.Power
92+ if slices.Contains(f.unit.Weak, typ) {
93+ v *= weakMult
94+ }
95+ if f.guarded(typ) && !actor.has("pierce") {
96+ v = v * 10 / float64(10+f.defense())
97+ }
98+ total += v
99+ top = max(top, v)
100+ }
101+ if a.Kind == KindAoE {
102+ return total
103+ }
104+ return top
105+}
106+
107+func (b *battle) threatens(foes, allies []*combatant) bool {
108+ for _, f := range foes {
109+ for _, a := range f.abils {
110+ typ := f.typeOf(a)
111+ if (a.Kind == KindDamage || a.Kind == KindAoE) && slices.ContainsFunc(allies, func(al *combatant) bool { return !al.guarded(typ) }) {
112+ return true
113+ }
114+ }
115+ if typ := f.typeOf(mustAbility(StrikeID)); slices.ContainsFunc(allies, func(al *combatant) bool { return !al.guarded(typ) }) {
116+ return true
117+ }
118+ }
119+ return false
120+}
internal/sim/classes.go+60-10
@@ -1,20 +1,70 @@
11 package sim
22
3-import "tinyadventure/internal/model"
3+import (
4+ "math/rand/v2"
5+
6+ "tinyadventure/internal/model"
7+)
48
59 type Class struct {
6- Name string
7- Base model.Stats
8- Growth model.Stats
9- Abilities []string
10+ Name string
11+ Role string
12+ Base model.Stats
13+ Growth model.Stats
14+ Pool []string
1015 }
1116
17+const (
18+ RoleTank = "tank"
19+ RoleStriker = "striker"
20+ RoleCaster = "caster"
21+ RoleSupport = "support"
22+)
23+
24+const Drawn = 3
25+
1226 var Classes = []Class{
13- {"fighter", model.Stats{MaxHP: 30, Attack: 6, Defense: 4, Magic: 1}, model.Stats{MaxHP: 9, Attack: 2, Defense: 1}, []string{"cleave", "shield-bash"}},
14- {"rogue", model.Stats{MaxHP: 22, Attack: 7, Defense: 2, Magic: 1}, model.Stats{MaxHP: 6, Attack: 2, Defense: 1, Speed: 1, Crit: 1}, []string{"backstab", "poison-dart"}},
15- {"mage", model.Stats{MaxHP: 18, Attack: 2, Defense: 1, Magic: 8}, model.Stats{MaxHP: 5, Defense: 1, Magic: 3}, []string{"firebolt", "frost-nova"}},
16- {"cleric", model.Stats{MaxHP: 24, Attack: 3, Defense: 3, Magic: 6}, model.Stats{MaxHP: 7, Attack: 1, Defense: 1, Magic: 2}, []string{"heal", "smite"}},
17- {"ranger", model.Stats{MaxHP: 22, Attack: 6, Defense: 2, Magic: 2}, model.Stats{MaxHP: 6, Attack: 2, Defense: 1, Speed: 1, Crit: 1}, []string{"piercing-shot", "volley"}},
27+ {"fighter", RoleTank, model.Stats{MaxHP: 30, Attack: 6, Defense: 4, Magic: 1}, model.Stats{MaxHP: 9, Attack: 2, Defense: 1}, []string{"taunt", "rage", "heavy-strike", "cleave", "rally"}},
28+ {"rogue", RoleStriker, model.Stats{MaxHP: 22, Attack: 7, Defense: 2, Magic: 1}, model.Stats{MaxHP: 6, Attack: 2, Defense: 1, Speed: 1, Crit: 1}, []string{"sneak", "dodge", "heavy-strike", "envenom", "poison-cloud"}},
29+ {"mage", RoleCaster, model.Stats{MaxHP: 18, Attack: 2, Defense: 1, Magic: 8}, model.Stats{MaxHP: 5, Defense: 1, Magic: 3}, []string{"haste", "ward", "firebolt", "fireball", "ice-lance", "frost-nova"}},
30+ {"cleric", RoleSupport, model.Stats{MaxHP: 24, Attack: 3, Defense: 3, Magic: 6}, model.Stats{MaxHP: 7, Attack: 1, Defense: 1, Magic: 2}, []string{"heal", "prayer", "rally", "smite", "radiance"}},
31+ {"ranger", RoleStriker, model.Stats{MaxHP: 22, Attack: 6, Defense: 2, Magic: 5}, model.Stats{MaxHP: 6, Attack: 2, Defense: 1, Magic: 1, Speed: 1, Crit: 1}, []string{"mark", "dodge", "heavy-strike", "lightning-bolt", "chain-lightning"}},
32+}
33+
34+var enemyRoles = map[string]string{
35+ "thrall": RoleStriker, "bat": RoleStriker, "archer": RoleStriker, "sneak": RoleStriker, "wolf": RoleStriker, "spider": RoleStriker, "mimic": RoleStriker,
36+ "knight": RoleTank, "brute": RoleTank, "boar": RoleTank, "troll": RoleTank, "owlbear": RoleTank,
37+ "lord": RoleTank, "chief": RoleTank, "captain": RoleTank, "warboss": RoleTank,
38+ "shaman": RoleCaster, "cultist": RoleCaster, "witch": RoleCaster, "crow": RoleCaster, "lich": RoleCaster, "coven": RoleCaster,
39+ "priest": RoleSupport, "zealot": RoleSupport, "prophet": RoleSupport,
40+}
41+
42+var typeKit = map[string][2]string{
43+ Physical: {"heavy-strike", "cleave"}, Poison: {"envenom", "poison-cloud"}, Fire: {"firebolt", "fireball"}, Frost: {"ice-lance", "frost-nova"},
44+ Lightning: {"lightning-bolt", "chain-lightning"}, Holy: {"smite", "radiance"}, Shadow: {"shadow-bolt", "shadow-wave"},
45+}
46+
47+func RoleOf(class string) string {
48+ for _, c := range Classes {
49+ if c.Name == class {
50+ return c.Role
51+ }
52+ }
53+ if r, ok := enemyRoles[class]; ok {
54+ return r
55+ }
56+ return RoleStriker
57+}
58+
59+func EnemyKit(r *rand.Rand, class, typ string, n int) []model.Ability {
60+ kit := typeKit[typ]
61+ pools := map[string][]string{
62+ RoleTank: {"taunt", "rage", "heavy-strike", "cleave"},
63+ RoleStriker: {"sneak", "dodge", "heavy-strike", "envenom"},
64+ RoleCaster: {kit[0], kit[1], "ward"},
65+ RoleSupport: {"heal", "prayer", "rally", kit[0]},
66+ }
67+ return Draw(r, pools[RoleOf(class)], n)
1868 }
1969
2070 func classOf(name string) Class {
internal/sim/combat.go+27-202
@@ -1,7 +1,6 @@
11 package sim
22
33 import (
4- "fmt"
54 "math/rand/v2"
65 "slices"
76 "sort"
@@ -26,43 +25,40 @@ type Result struct {
2625 type combatant struct {
2726 unit model.Unit
2827 side int
28+ role string
2929 hp int
3030 stats model.Stats
3131 abils []model.Ability
3232 cd map[string]int
33- buffed bool
3433 struck bool
34+ ambush bool
3535 traits []string
36- element string
36+ edge string
37+ guards []string
38+ effects []effect
39+ hurtBy *combatant
3740 }
3841
3942 func newCombatant(u model.Unit, side int) *combatant {
4043 s := Effective(u)
4144 t := TraitsOf(u)
42- return &combatant{unit: u, side: side, hp: s.HP, stats: s, abils: AllAbilities(u), cd: map[string]int{}, traits: t, element: elementOf(t)}
45+ return &combatant{
46+ unit: u, side: side, role: RoleOf(u.Class), hp: s.HP, stats: s, abils: AllAbilities(u), cd: map[string]int{},
47+ traits: t, edge: edgeOf(t), guards: guardsOf(t, u.Resist),
48+ }
4349 }
4450
4551 func (c *combatant) has(t string) bool { return slices.Contains(c.traits, t) }
4652
47-const (
48- weakMult = 1.5
49- resistMult = 0.5
50- wardMult = 0.7
51- armorPlus = 3
52- firstMult = 1.5
53- lifestealPC = 30
54- thornsPC = 25
55- cleavePC = 50
56-)
57-
5853 func (c *combatant) alive() bool { return c.hp > 0 }
5954
55+func (c *combatant) hurt() bool { return c.hp*2 < c.stats.MaxHP }
56+
6057 type battle struct {
61- r *rand.Rand
62- all []*combatant
63- log []model.CombatEvent
64- tick int
65- totals [2]int
58+ r *rand.Rand
59+ all []*combatant
60+ log []model.CombatEvent
61+ tick int
6662 }
6763
6864 func (b *battle) side(s int) []*combatant {
@@ -75,193 +71,22 @@ func (b *battle) side(s int) []*combatant {
7571 return out
7672 }
7773
78-func (b *battle) emit(actor, target *combatant, a model.Ability, amount int, crit, killed bool, verb string) {
79- text := fmt.Sprintf("%s uses %s on %s for %d %s", actor.unit.Name, a.Name, target.unit.Name, amount, verb)
80- if crit {
81- text += " (crit)"
82- }
83- if killed {
84- text += ", " + target.unit.Name + " falls"
85- }
86- b.log = append(b.log, model.CombatEvent{
87- Tick: b.tick, Actor: actor.unit.ID, Target: target.unit.ID, Ability: a.ID, Kind: a.Kind,
88- Amount: amount, Crit: crit, Killed: killed, Text: text,
89- })
90-}
91-
92-func (b *battle) hit(actor, target *combatant, a model.Ability, scale float64) {
93- stat := actor.stats.Attack
94- if a.Kind == KindMagic || a.Kind == KindAoE {
95- stat = actor.stats.Magic
96- }
97- raw := float64(max(stat, 1)) * a.Power * scale * (0.85 + 0.3*b.r.Float64())
98- crit := b.r.IntN(100) < actor.stats.Crit
99- if crit {
100- raw *= 2
101- }
102- if actor.has("first") && !actor.struck {
103- raw *= firstMult
104- }
105- actor.struck = true
106- el := abilityElement[a.ID]
107- if el == "" {
108- el = actor.element
109- }
110- verb := "damage"
111- switch {
112- case el != "" && slices.Contains(target.unit.Weak, el):
113- raw *= weakMult
114- verb = el + " damage, a weakness"
115- case el != "" && slices.Contains(target.unit.Resist, el):
116- raw *= resistMult
117- verb = el + " damage, resisted"
118- case el != "":
119- verb = el + " damage"
120- }
121- if el != "" && target.has("ward") {
122- raw *= wardMult
123- }
124- def := max(target.stats.Defense, 0)
125- if target.has("armored") {
126- def += armorPlus
127- }
128- if actor.has("pierce") {
129- def = 0
130- }
131- dmg := max(1, int(raw*10/float64(10+def)))
132- target.hp = max(0, target.hp-dmg)
133- b.emit(actor, target, a, dmg, crit, !target.alive(), verb)
134- if actor.has("lifesteal") && actor.alive() && actor.hp < actor.stats.MaxHP {
135- drain := min(actor.stats.MaxHP-actor.hp, max(1, dmg*lifestealPC/100))
136- actor.hp += drain
137- b.emit(actor, actor, lifestealAbility, drain, false, false, "healing")
138- }
139- if target.has("thorns") && a.Kind != KindMagic && a.Kind != KindAoE && actor.alive() {
140- back := max(1, dmg*thornsPC/100)
141- actor.hp = max(0, actor.hp-back)
142- b.emit(target, actor, thornsAbility, back, false, !actor.alive(), "damage")
143- }
144- if scale == 1 && actor.has("cleave") && a.Kind != KindAoE && a.Kind != KindMagic {
145- for _, f := range b.side(target.side) {
146- if f != target {
147- b.hit(actor, f, a, float64(cleavePC)/100)
148- break
74+func (b *battle) act(actor *combatant, extra bool) {
75+ if !extra {
76+ for id, v := range actor.cd {
77+ if v > 0 {
78+ actor.cd[id] = v - 1
14979 }
15080 }
81+ b.expire(actor)
15182 }
152-}
153-
154-var (
155- thornsAbility = model.Ability{ID: "thorns", Name: "Thorns", Kind: KindDamage}
156- lifestealAbility = model.Ability{ID: "lifesteal", Name: "Lifesteal", Kind: KindHeal}
157-)
158-
159-func (b *battle) heal(actor, target *combatant, a model.Ability) {
160- amt := max(1, int(float64(actor.stats.Magic)*a.Power*(0.85+0.3*b.r.Float64())))
161- amt = min(amt, target.stats.MaxHP-target.hp)
162- target.hp += amt
163- b.emit(actor, target, a, amt, false, false, "healing")
164-}
165-
166-func (b *battle) buff(actor *combatant, a model.Ability) {
167- for _, t := range b.side(actor.side) {
168- t.stats.Attack += int(float64(t.stats.Attack) * a.Power)
169- t.stats.Magic += int(float64(t.stats.Magic) * a.Power)
170- t.buffed = true
171- b.log = append(b.log, model.CombatEvent{
172- Tick: b.tick, Actor: actor.unit.ID, Target: t.unit.ID, Ability: a.ID, Kind: a.Kind, Amount: int(a.Power * 100),
173- Text: fmt.Sprintf("%s uses %s: %s gains %d%% power", actor.unit.Name, a.Name, t.unit.Name, int(a.Power*100)),
174- })
175- }

Cut short: this commit's diff is over 1000 lines.

internal/sim/damage.go+154-0

Cut short: this commit's diff is over 1000 lines.

internal/sim/effects.go+100-0

Cut short: this commit's diff is over 1000 lines.

internal/sim/gear.go+4-4

Cut short: this commit's diff is over 1000 lines.

internal/sim/rules_test.go+17-5

Cut short: this commit's diff is over 1000 lines.

internal/sim/traits.go+46-22

Cut short: this commit's diff is over 1000 lines.