tiny-adventure / commits / fc58fcc
Each player gets their own saved board, fallen heroes stay down until a potion or camp, and finished runs get a share link with a preview card
A cookie names each player, and every game is an append-only action log under --data that replays to the same state, so it is both the save and the anonymous record of play. Feedback opens after a fight and a gear change, rate limits cover proxied traffic, and the server draws a 1200x630 card with the vendored fonts. Combat events now carry their kind and lifesteal is logged, so replaying a log gives the exact hp; TestCombatLogFollowsTheRules checks that over about 600 fights. The careful bot still wins 19 of 20 seeds, in about 10.6 days. The deploy unit and Caddy block for tiny-adventure.xonecas.io are in deploy/. Co-Authored-By: Claude Opus 5.5
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -6,19 +6,19 @@ import (
66 "net/http"
77
88 "tinyadventure/internal/model"
9- "tinyadventure/internal/rng"
109 "tinyadventure/internal/server"
1110 )
1211
1312 func main() {
1413 addr := flag.String("addr", ":8080", "listen address")
15- seed := flag.Int64("seed", 0, "campaign seed (0 picks a random one)")
14+ data := flag.String("data", "", "directory for game logs and feedback (empty keeps games in memory)")
15+ seed := flag.Int64("seed", 0, "first campaign seed for every new player (0 gives each player a random one)")
1616 web := flag.String("web", "web", "static files directory")
1717 flag.Parse()
18- s := model.Seed(*seed)
19- if *seed == 0 {
20- s = rng.NewSeed()
18+ srv, err := server.New(model.Seed(*seed), *web, *data)
19+ if err != nil {
20+ log.Fatal(err)
2121 }
22- log.Printf("seed %d, listening on %s", s, *addr)
23- log.Fatal(http.ListenAndServe(*addr, server.New(s, *web)))
22+ log.Printf("seed %d, data %q, listening on %s", *seed, *data, *addr)
23+ log.Fatal(http.ListenAndServe(*addr, srv))
2424 }
@@ -0,0 +1,4 @@
1+tiny-adventure.xonecas.io {
2+ encode zstd gzip
3+ reverse_proxy 127.0.0.1:8083
4+}
@@ -0,0 +1,14 @@
1+[Unit]
2+Description=Tiny Adventure game server
3+
4+[Service]
5+WorkingDirectory=%h/repos/tiny-adventure
6+ExecStart=%h/repos/tiny-adventure/bin/server --addr 127.0.0.1:8083 --web web --data %h/.local/state/tiny-adventure
7+Restart=on-failure
8+RestartSec=2
9+Nice=10
10+MemoryMax=512M
11+CPUQuota=50%
12+
13+[Install]
14+WantedBy=default.target
@@ -1,6 +1,8 @@
11 # HTTP API
22
3-All bodies are JSON. Types live in `internal/model`. Single player first: the player id is `local`, sent as the `X-Player` header (optional, defaults to `local`). Server state is keyed by player id so multiplayer can be added later.
3+All bodies are JSON and at most 8 KiB. Types live in `internal/model`.
4+
5+Each player has one board. The server names a player by a random 32-hex-digit id in the `ta` cookie, which it sets on the first request without one (`HttpOnly`, `SameSite=Lax`, a year long). Scripts send the same id in the `X-Player` header instead. A player's board is the game they last started; `/api/new` replaces it. The player id never appears in a response or in a game log.
46
57 Errors return a non-2xx status and `{"error": "message"}` (`ErrorResponse`).
68
@@ -13,7 +15,7 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
1315 ```json
1416 {
1517 "version": 1,
16- "playerId": "local",
18+ "game": "04339283a251d4d5",
1719 "seed": 42,
1820 "campaign": {
1921 "seed": 42,
@@ -39,7 +41,6 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
3941 "landmarks": [{"id": "lm1", "kind": "lookout", "x": 0, "y": 0, "used": false}]
4042 },
4143 "party": {
42- "playerId": "local",
4344 "units": [
4445 {
4546 "id": "u1", "name": "Ayla", "class": "fighter", "race": "dwarf", "level": 1, "xp": 0,
@@ -57,13 +58,18 @@ Every endpoint returns a full `GameState`. After victory or defeat every POST ex
5758 "log": [],
5859 "phase": "explore",
5960 "clock": {"day": 1, "time": 0, "dayLength": 140, "nightLength": 40},
60- "summary": {"battles": 0, "kills": 0, "loot": 0, "steps": 0, "seconds": 0}
61+ "summary": {"battles": 0, "kills": 0, "loot": 0, "steps": 0, "seconds": 0, "fallen": 0, "hexes": 0, "dealt": 0, "taken": 0, "crits": 0, "best": 0, "potions": 0, "camps": 0},
62+ "feedback": false
6163 }
6264 ```
6365
64-Combat resolves instantly on the server, so `phase` is never left at `combat`. After a fight `encounter` (`Encounter`) and `log` describe it until the next move or interact. `summary.seconds` is the elapsed play time, frozen at victory or defeat. The boss POI only starts its fight once all other main steps are done. Every main step after the first is a `retrieve` step. It completes once its POI is cleared and its key is in `party.keys`. Keys never enter the inventory and cannot be equipped or so …
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 …
67+
68+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).
69+
70+`game` is the id of this campaign, used by its share link. `summary` counts the run: `hexes` walked, damage `dealt` and `taken` by the heroes, `crits`, the `best` single hit, heroes `fallen`, `potions` drunk and nights `camps`ed. `feedback` is true once the party has fought a battle and changed gear, and stays true for up to three notes per game.
6571
66-Optional fields: `encounter` (`Encounter`, present after a fight), `rewards` (`Rewards`, present after a won fight), `found` (items auto-collected by the latest move or interact, cleared on the next action), `threat` (`Threat`, see `/api/move`), `shop` (`Shop`, present while the party stands where a trader works), `winner` (player id, set at `victory`).
72+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.
6773
6874 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.
6975
@@ -194,7 +200,7 @@ Traders work at the spawns and at cleared POIs of kind `camp` or `village`. Whil
194200
195201 ### POST /api/rest
196202
197-Makes camp where the party stands. Body `{}`. Heals every hero to full and starts the next day at `time` 0. Fails with 400 during the day, and with 400 when an uncleared POI or band is within one hex.
203+Makes camp where the party stands. Body `{}`. Heals every hero to full, fallen ones included, and starts the next day at `time` 0. Fails with 400 during the day, and with 400 when an uncleared POI or band is within one hex.
198204
199205 ### POST /api/buy
200206
@@ -214,12 +220,42 @@ Sells a pack item for half its `value`. Quest items cannot be sold.
214220
215221 ## POST /api/drink
216222
217-Drinks a potion on a hero, anywhere, healing half of their maximum health. Fails with 400 with no potions or at full health.
223+Drinks a potion on a hero, anywhere, healing half of their maximum health. A fallen hero gets back up. Fails with 400 with no potions or at full health.
218224
219225 ```json
220226 {"unit": "u1"}
221227 ```
222228
229+## POST /api/feedback
230+
231+Sends a free-form note about the current game. Opens once `feedback` is true. The text must hold 3 to 2000 characters. The note is stored with the game id, day and phase, and the game log beside it tells the rest.
232+
233+```json
234+{"text": "The boss fight was too long"}
235+```
236+
237+Response: `GameState`.
238+
239+## GET /api/run/{id}
240+
241+Returns the `Run` of a finished game: `game`, `seed`, `phase`, `mission`, `boss`, `day`, `keys`, `keysOf`, `gold`, `summary` and `party` (name, race, class and level per hero). Unfinished or unknown games return 404.
242+
243+## GET /r/{id}
244+
245+The share link. It serves the game page with `og:` and `twitter:` meta tags for the run, so a link preview shows the result. The client opens on the run's end card, with "Play this seed" and "New game".
246+
247+## GET /r/{id}/card.png
248+
249+The 1200 by 630 preview image of the run, drawn with the vendored fonts and cached in the data directory.
250+
251+## Storage
252+
253+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 …
254+
255+## Limits
256+
257+Requests through the proxy are limited per client address. Reads allow 20 a second with a burst of 80, actions 8 a second with a burst of 60, new games one per 30 seconds with a burst of 10, and feedback one per 10 minutes with a burst of 3. Excess requests get 429. Direct loopback requests without `X-Forwarded-For`, such as the harness, are not limited. The server keeps up to 400 boards in memory and reloads evicted ones from their logs.
258+
223259 ## Mission templates
224260
225261 A mission is a list of `MissionStep`. Each step has typed `slots` (`poiKind`, `faction`, `item`) filled from the seed, so the `mine`/`vampires`/`key` template becomes `beach`/`lizardfolk`/`key` by changing slot values only.
@@ -0,0 +1,43 @@
1+# Deploy
2+
3+The game runs as a systemd user service behind Caddy. The Go server serves the page, the API and the share cards on `127.0.0.1:8083`. Caddy terminates TLS and proxies to it. Games and feedback live in `~/.local/state/tiny-adventure`.
4+
5+## First install
6+
7+1. Clone the repo to `~/repos/tiny-adventure` and build the server:
8+
9+ git clone <remote> ~/repos/tiny-adventure
10+ cd ~/repos/tiny-adventure
11+ go build -o bin/server ./cmd/server
12+ mkdir -p ~/.local/state/tiny-adventure
13+
14+2. Install and start the user unit. Enable linger for the user so it runs without a login:
15+
16+ install -Dm 644 deploy/tiny-adventure.service ~/.config/systemd/user/tiny-adventure.service
17+ systemctl --user daemon-reload
18+ systemctl --user enable --now tiny-adventure
19+ curl -s 127.0.0.1:8083/api/state | head -c 80
20+
21+3. Append the block in `deploy/Caddyfile` to the live Caddyfile, validate it and reload Caddy:
22+
23+ cat /etc/caddy/Caddyfile deploy/Caddyfile > /tmp/Caddyfile
24+ caddy validate --adapter caddyfile --config /tmp/Caddyfile
25+ sudo install -m 644 /tmp/Caddyfile /etc/caddy/Caddyfile
26+ sudo systemctl reload caddy
27+
28+## Update
29+
30+ cd ~/repos/tiny-adventure
31+ git pull
32+ go build -o bin/server ./cmd/server
33+ systemctl --user restart tiny-adventure
34+
35+A restart keeps every game. Each player's board is rebuilt from its log on their next request.
36+
37+## Read the logs
38+
39+- Server: `journalctl --user -u tiny-adventure -f`.
40+- Feedback: `~/.local/state/tiny-adventure/feedback.jsonl`. Each note names its `game`.
41+- Play: `~/.local/state/tiny-adventure/games/<game>.jsonl`, one action per line.
42+
43+The unit caps the server at 512 MB and half a CPU, so a busy game never starves the other services on the host.
@@ -1,3 +1,10 @@
11 module tinyadventure
22
33 go 1.27
4+
5+require golang.org/x/image v0.48.0
6+
7+require (
8+ golang.org/x/sys v0.50.0 // indirect
9+ golang.org/x/text v0.44.0 // indirect
10+)
@@ -0,0 +1,6 @@
1+golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
2+golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
3+golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
4+golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
5+golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
6+golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
@@ -11,28 +11,50 @@ type Route struct {
1111 Blocked string `json:"blocked,omitempty"`
1212 }
1313
14-type MoveRequest struct {
15- X int `json:"x"`
16- Y int `json:"y"`
17- Steps int `json:"steps,omitempty"`
14+type Action struct {
15+ Kind string `json:"kind"`
16+ T int64 `json:"t"`
17+ X int `json:"x,omitempty"`
18+ Y int `json:"y,omitempty"`
19+ Steps int `json:"steps,omitempty"`
20+ ID string `json:"id,omitempty"`
21+ Unit string `json:"unit,omitempty"`
22+ Item string `json:"item,omitempty"`
23+ Unequip bool `json:"unequip,omitempty"`
24+ Text string `json:"text,omitempty"`
1825 }
1926
20-type InteractRequest struct {
21- ID string `json:"id"`
27+type Entry struct {
28+ Action
29+ Err string `json:"err,omitempty"`
2230 }
2331
24-type EquipRequest struct {
25- Unit string `json:"unit"`
26- Item string `json:"item"`
27- Unequip bool `json:"unequip,omitempty"`
32+type Header struct {
33+ Game string `json:"game"`
34+ Seed Seed `json:"seed"`
35+ Started int64 `json:"started"`
36+ Version int `json:"version"`
2837 }
2938
30-type ItemRequest struct {
31- Item string `json:"item"`
39+type Run struct {
40+ Game string `json:"game"`
41+ Seed Seed `json:"seed"`
42+ Phase string `json:"phase"`
43+ Mission string `json:"mission"`
44+ Boss string `json:"boss"`
45+ Day int `json:"day"`
46+ Keys int `json:"keys"`
47+ KeysOf int `json:"keysOf"`
48+ Gold int `json:"gold"`
49+ Summary Summary `json:"summary"`
50+ Party []RunHero `json:"party"`
3251 }
3352
34-type UnitRequest struct {
35- Unit string `json:"unit"`
53+type RunHero struct {
54+ Name string `json:"name"`
55+ Race string `json:"race"`
56+ Class string `json:"class"`
57+ Level int `json:"level"`
3658 }
3759
3860 type ErrorResponse struct {
@@ -28,6 +28,7 @@ type CombatEvent struct {
2828 Actor string `json:"actor"`
2929 Target string `json:"target"`
3030 Ability string `json:"ability"`
31+ Kind string `json:"kind"`
3132 Amount int `json:"amount"`
3233 Crit bool `json:"crit,omitempty"`
3334 Killed bool `json:"killed,omitempty"`
@@ -6,11 +6,19 @@ type Summary struct {
66 Loot int `json:"loot"`
77 Steps int `json:"steps"`
88 Seconds int `json:"seconds"`
9+ Fallen int `json:"fallen"`
10+ Hexes int `json:"hexes"`
11+ Dealt int `json:"dealt"`
12+ Taken int `json:"taken"`
13+ Crits int `json:"crits"`
14+ Best int `json:"best"`
15+ Potions int `json:"potions"`
16+ Camps int `json:"camps"`
917 }
1018
1119 type GameState struct {
1220 Version int `json:"version"`
13- PlayerID string `json:"playerId"`
21+ Game string `json:"game"`
1422 Seed Seed `json:"seed"`
1523 Campaign Campaign `json:"campaign"`
1624 Map Map `json:"map"`
@@ -25,6 +33,6 @@ type GameState struct {
2533 Shop *Shop `json:"shop,omitempty"`
2634 Clock Clock `json:"clock"`
2735 Phase string `json:"phase"`
28- Winner string `json:"winner,omitempty"`
2936 Summary Summary `json:"summary"`
37+ Feedback bool `json:"feedback"`
3038 }
@@ -9,9 +9,9 @@ import (
99 func TestGameStateRoundTrip(t *testing.T) {
1010 sword := Item{ID: "i1", Name: "Rusty Sword", Slot: SlotWeapon, Rarity: "common", Bonus: Stats{Attack: 2}}
1111 in := GameState{
12- Version: Version,
13- PlayerID: "p1",
14- Seed: 42,
12+ Version: Version,
13+ Game: "g1",
14+ Seed: 42,
1515 Campaign: Campaign{
1616 Seed: 42,
1717 Systems: []string{"factions", "sidequests"},
@@ -29,7 +29,6 @@ func TestGameStateRoundTrip(t *testing.T) {
2929 Loot: []LootNode{{ID: "l1", Item: sword}},
3030 },
3131 Party: Party{
32- PlayerID: "p1",
3332 Units: []Unit{{ID: "u1", Name: "Ayla", Class: "fighter", Level: 1,
3433 Stats: Stats{HP: 10, MaxHP: 10, Attack: 3},
3534 Abilities: []Ability{{ID: "a1", Name: "Slash", Kind: "damage", Power: 1.2, Target: "enemy"}},
@@ -16,8 +16,9 @@ type Unit struct {
1616 Resist []string `json:"resist,omitempty"`
1717 }
1818
19+func (u Unit) Fallen() bool { return u.Stats.HP <= 0 }
20+
1921 type Party struct {
20- PlayerID string `json:"playerId"`
2122 Units []Unit `json:"units"`
2223 Inventory []Item `json:"inventory"`
2324 Keys []Item `json:"keys"`
@@ -0,0 +1,40 @@
1+package server
2+
3+import (
4+ "errors"
5+ "time"
6+
7+ "tinyadventure/internal/model"
8+)
9+
10+var kinds = []string{"move", "interact", "equip", "rest", "buy", "sell", "drink", "feedback"}
11+
12+func (g *game) apply(a model.Action) error {
13+ g.now = time.UnixMilli(a.T)
14+ if g.finished() && a.Kind != "feedback" {
15+ return errors.New("campaign is over, start a new game")
16+ }
17+ switch a.Kind {
18+ case "move":
19+ return g.move(a.X, a.Y, a.Steps)
20+ case "interact":
21+ return g.interact(a.ID)
22+ case "equip":
23+ err := g.equip(a)
24+ if err == nil && !a.Unequip {
25+ g.equips++
26+ }
27+ return err
28+ case "rest":
29+ return g.rest()
30+ case "buy":
31+ return g.buy(a.Item)
32+ case "sell":
33+ return g.sell(a.Item)
34+ case "drink":
35+ return g.drink(a.Unit)
36+ case "feedback":
37+ return g.feedback(a.Text)
38+ }
39+ return errors.New("unknown action")
40+}
@@ -0,0 +1,147 @@
1+package server
2+
3+import (
4+ "bytes"
5+ "embed"
6+ "fmt"
7+ "image"
8+ "image/color"
9+ "image/draw"
10+ "image/png"
11+ "strings"
12+ "sync"
13+
14+ "golang.org/x/image/font"
15+ "golang.org/x/image/font/opentype"
16+ "golang.org/x/image/math/fixed"
17+
18+ "tinyadventure/internal/model"
19+)
20+
21+//go:embed fonts/*.ttf
22+var fontFiles embed.FS
23+
24+var (
25+ cardBg = color.RGBA{0x14, 0x11, 0x0e, 0xff}
26+ cardRaised = color.RGBA{0x2a, 0x25, 0x1f, 0xff}
27+ cardFg = color.RGBA{0xef, 0xe6, 0xd2, 0xff}
28+ cardMuted = color.RGBA{0xb3, 0xa7, 0x8f, 0xff}
29+ cardFaint = color.RGBA{0x7c, 0x72, 0x5f, 0xff}
30+ cardAccent = color.RGBA{0xff, 0xc9, 0x4d, 0xff}
31+ cardDanger = color.RGBA{0xe2, 0x55, 0x3f, 0xff}
32+)
33+
34+var (
35+ fontsOnce sync.Once
36+ fontsErr error
37+ display *opentype.Font
38+ body *opentype.Font
39+)
40+
41+func loadCardFonts() error {
42+ fontsOnce.Do(func() {
43+ parse := func(name string) *opentype.Font {
44+ b, err := fontFiles.ReadFile("fonts/" + name)
45+ if err == nil {
46+ var f *opentype.Font
47+ if f, err = opentype.Parse(b); err == nil {
48+ return f
49+ }
50+ }
51+ fontsErr = fmt.Errorf("font %s: %w", name, err)
52+ return nil
53+ }
54+ display, body = parse("MedievalSharp.ttf"), parse("Alegreya.ttf")
55+ })
56+ return fontsErr
57+}
58+
59+type pen struct {
60+ img *image.RGBA
61+ faces map[string]font.Face
62+}
63+
64+func (p pen) face(f *opentype.Font, size float64) font.Face {
65+ key := fmt.Sprintf("%p %v", f, size)
66+ if fc, ok := p.faces[key]; ok {
67+ return fc
68+ }
69+ fc, _ := opentype.NewFace(f, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingFull})
70+ p.faces[key] = fc
71+ return fc
72+}
73+
74+func (p pen) text(f *opentype.Font, size float64, c color.Color, x, y int, s string) int {
75+ d := font.Drawer{Dst: p.img, Src: image.NewUniform(c), Face: p.face(f, size), Dot: fixed.P(x, y)}
76+ d.DrawString(s)
77+ return d.Dot.X.Round()
78+}
79+
80+func (p pen) width(f *opentype.Font, size float64, s string) int {
81+ return font.MeasureString(p.face(f, size), s).Round()
82+}
83+
84+func (p pen) rect(x, y, w, h int, c color.Color) {
85+ draw.Draw(p.img, image.Rect(x, y, x+w, y+h), image.NewUniform(c), image.Point{}, draw.Src)
86+}
87+
88+func card(run model.Run, host string) ([]byte, error) {
89+ if err := loadCardFonts(); err != nil {
90+ return nil, err
91+ }
92+ const W, H, pad = 1200, 630, 72
93+ p := pen{img: image.NewRGBA(image.Rect(0, 0, W, H)), faces: map[string]font.Face{}}
94+ p.rect(0, 0, W, H, cardBg)
95+ tone := cardAccent
96+ if run.Phase != "victory" {
97+ tone = cardDanger
98+ }
99+ p.rect(0, 0, 12, H, tone)
100+ title, _ := headline(run)
101+ p.text(display, 34, cardMuted, pad, 104, "Tiny Adventure")
102+ p.text(display, 84, tone, pad, 206, title)
103+ p.text(body, 34, cardFg, pad, 262, fitText(p, body, 34, run.Mission, W-2*pad))
104+ sum := run.Summary
105+ stats := [][2]string{
106+ {fmt.Sprint(sum.Battles), "battles"},
107+ {fmt.Sprint(sum.Kills), "foes"},
108+ {fmt.Sprintf("%d/%d", run.Keys, run.KeysOf), "keys"},
109+ {fmt.Sprint(sum.Hexes), "hexes"},
110+ {fmt.Sprint(sum.Best), "best hit"},
111+ {fmt.Sprint(sum.Fallen), "fallen"},
112+ }
113+ tw := (W - 2*pad - 5*16) / 6
114+ for i, st := range stats {
115+ x := pad + i*(tw+16)
116+ p.rect(x, 306, tw, 128, cardRaised)
117+ p.text(body, 56, cardFg, x+(tw-p.width(body, 56, st[0]))/2, 378, st[0])
118+ p.text(body, 26, cardMuted, x+(tw-p.width(body, 26, st[1]))/2, 416, st[1])
119+ }
120+ heroes := make([]string, len(run.Party))
121+ for i, h := range run.Party {
122+ heroes[i] = fmt.Sprintf("%s, level %d %s", h.Name, h.Level, strings.ToLower(h.Class))
123+ }
124+ p.text(body, 28, cardMuted, pad, 492, fitText(p, body, 28, strings.Join(heroes[:min(2, len(heroes))], " "), W-2*pad))
125+ if len(heroes) > 2 {
126+ p.text(body, 28, cardMuted, pad, 532, fitText(p, body, 28, strings.Join(heroes[2:], " "), W-2*pad))
127+ }
128+ foot := fmt.Sprintf("Seed %d", run.Seed)
129+ p.text(body, 26, cardFaint, pad, 590, foot)
130+ p.text(body, 26, cardFaint, W-pad-p.width(body, 26, host), 590, host)
131+ var buf bytes.Buffer
132+ if err := png.Encode(&buf, p.img); err != nil {
133+ return nil, err
134+ }
135+ return buf.Bytes(), nil
136+}
137+
138+func fitText(p pen, f *opentype.Font, size float64, s string, w int) string {
139+ if p.width(f, size, s) <= w {
140+ return s
141+ }
142+ r := []rune(s)
143+ for len(r) > 0 && p.width(f, size, string(r)+"…") > w {
144+ r = r[:len(r)-1]
145+ }
146+ return string(r) + "…"
147+}
@@ -39,7 +39,8 @@ func (g *game) rest() error {
3939 return errors.New("enemies are too close to make camp")
4040 }
4141 g.begin()
42- g.healAll()
42+ g.heal(true)
43+ g.state.Summary.Camps++
4344 c.Day++
4445 c.Time = 0
4546 return nil
@@ -8,7 +8,7 @@ import (
88 "tinyadventure/internal/sim"
99 )
1010
11-func (g *game) equip(req model.EquipRequest) error {
11+func (g *game) equip(req model.Action) error {
1212 u := g.unit(req.Unit)
1313 if u == nil {
1414 return errors.New("unknown unit")
@@ -0,0 +1,31 @@
1+package server
2+
3+import (
4+ "errors"
5+ "strings"
6+ "unicode/utf8"
7+)
8+
9+const (
10+ feedbackMin = 3
11+ feedbackMax = 2000
12+ feedbackEach = 3
13+)
14+
15+func (g *game) feedbackOpen() bool {
16+ return g.fights > 0 && g.equips > 0 && g.notes < feedbackEach
17+}
18+
19+func (g *game) feedback(text string) error {
20+ n := utf8.RuneCountInString(strings.TrimSpace(text))
21+ switch {
22+ case !g.feedbackOpen():
23+ return errors.New("feedback opens after a fight and a gear change")
24+ case n < feedbackMin:
25+ return errors.New("write a few words first")
26+ case n > feedbackMax:
27+ return errors.New("keep it under 2000 characters")
28+ }
29+ g.notes++
30+ return nil
31+}
@@ -0,0 +1,93 @@
1+Copyright 2011 The Alegreya Project Authors (https://github.com/huertatipografica/Alegreya)
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+http://scripts.sil.org/OFL
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file, not shown.
@@ -0,0 +1,105 @@
1+Copyright (c) 2011, wmk69 (wmk69@o2.pl),
2+with Reserved Font Name MedievalSharp.
3+
4+This Font Software is licensed under the SIL Open Font License, Version 1.1.
5+This license is copied below, and is also available with a FAQ at:
6+http://scripts.sil.org/OFL
7+
8+
9+
10+SIL OPEN FONT LICENSE
11+
12+Version 1.1 - 26 February 2007
13+
14+
15+PREAMBLE
16+
17+The goals of the Open Font License (OFL) are to stimulate worldwide
18+development of collaborative font projects, to support the font creation
19+efforts of academic and linguistic communities, and to provide a free and
20+open framework in which fonts may be shared and improved in partnership
21+with others.
22+
23+The OFL allows the licensed fonts to be used, studied, modified and
24+redistributed freely as long as they are not sold by themselves. The
25+fonts, including any derivative works, can be bundled, embedded,
26+redistributed and/or sold with any software provided that any reserved
27+names are not used by derivative works. The fonts and derivatives,
28+however, cannot be released under any other type of license. The
29+requirement for fonts to remain under this license does not apply
30+to any document created using the fonts or their derivatives.
31+
32+
33+DEFINITIONS
34+
35+"Font Software" refers to the set of files released by the Copyright
36+Holder(s) under this license and clearly marked as such. This may
37+include source files, build scripts and documentation.
38+
39+"Reserved Font Name" refers to any names specified as such after the
40+copyright statement(s).
41+
42+"Original Version" refers to the collection of Font Software components as
43+distributed by the Copyright Holder(s).
44+
45+"Modified Version" refers to any derivative made by adding to, deleting,
46+or substituting — in part or in whole — any of the components of the
47+Original Version, by changing formats or by porting the Font Software to a
48+new environment.
49+
50+"Author" refers to any designer, engineer, programmer, technical
51+writer or other person who contributed to the Font Software.
52+
53+
54+PERMISSION & CONDITIONS
55+
56+Permission is hereby granted, free of charge, to any person obtaining
57+a copy of the Font Software, to use, study, copy, merge, embed, modify,
58+redistribute, and sell modified and unmodified copies of the Font
59+Software, subject to the following conditions:
60+
61+1) Neither the Font Software nor any of its individual components,
62+in Original or Modified Versions, may be sold by itself.
63+
64+2) Original or Modified Versions of the Font Software may be bundled,
65+redistributed and/or sold with any software, provided that each copy
66+contains the above copyright notice and this license. These can be
67+included either as stand-alone text files, human-readable headers or
68+in the appropriate machine-readable metadata fields within text or
69+binary files as long as those fields can be easily viewed by the user.
70+
71+3) No Modified Version of the Font Software may use the Reserved Font
72+Name(s) unless explicit written permission is granted by the corresponding
73+Copyright Holder. This restriction only applies to the primary font name as
74+presented to the users.
75+
76+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
77+Software shall not be used to promote, endorse or advertise any
78+Modified Version, except to acknowledge the contribution(s) of the
79+Copyright Holder(s) and the Author(s) or with their explicit written
80+permission.
81+
82+5) The Font Software, modified or unmodified, in part or in whole,
83+must be distributed entirely under this license, and must not be
84+distributed under any other license. The requirement for fonts to
85+remain under this license does not apply to any document created
86+using the Font Software.
87+
88+
89+TERMINATION
90+
91+This license becomes null and void if any of the above conditions are
92+not met.
93+
94+
95+DISCLAIMER
96+
97+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
98+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
99+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
100+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
101+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
102+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
103+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
104+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
105+OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file, not shown.
@@ -16,30 +16,34 @@ type game struct {
1616 spawn model.SpawnPoint
1717 started time.Time
1818 ended time.Time
19+ now time.Time
1920 fights uint64
21+ equips int
22+ notes int
2023 threat string
2124 ticks uint64
2225 stock map[string][]model.Item
26+ saved bool
2327 }
2428
25-func newGame(player string, seed model.Seed) *game {
29+func newGame(id string, seed model.Seed, started time.Time) *game {
2630 w := gen.Generate(seed)
27- w.Party.PlayerID = player
2831 encs := map[string]model.Encounter{}
2932 for _, e := range w.Encounters {
3033 encs[e.POI] = e
3134 }
3235 g := &game{
3336 state: model.GameState{
34- Version: model.Version, PlayerID: player, Seed: seed,
37+ Version: model.Version, Game: id, Seed: seed,
3538 Campaign: w.Campaign, Map: w.Map, Party: w.Party,
3639 Log: []model.CombatEvent{}, Phase: "explore", Clock: newClock(),
3740 },
3841 encs: encs,
3942 spawn: w.Map.Spawns[0],
40- started: time.Now(),
43+ started: started,
44+ now: started,
4145 }
42- g.healAll()
46+ g.heal(true)
4347 return g
4448 }
4549
@@ -50,6 +54,7 @@ func (g *game) snapshot() model.GameState {
5054 end = time.Now()
5155 }
5256 s.Summary.Seconds = int(end.Sub(g.started).Seconds())
57+ s.Feedback = g.feedbackOpen()
5358 s.Threat = g.threatView()
5459 s.Shop = g.shopView()
5560 return s
@@ -152,6 +157,24 @@ func (g *game) bossGate(p *model.POI) bool {
152157 return true
153158 }
154159
160+func (g *game) tally(log []model.CombatEvent) {
161+ sum := &g.state.Summary
162+ for _, e := range log {
163+ if e.Kind == sim.KindHeal || e.Kind == sim.KindBuff {
164+ continue
165+ }
166+ if g.unit(e.Actor) != nil {
167+ sum.Dealt += e.Amount
168+ sum.Best = max(sum.Best, e.Amount)
169+ if e.Crit {
170+ sum.Crits++
171+ }
172+ } else if g.unit(e.Target) != nil {
173+ sum.Taken += e.Amount
174+ }
175+ }
176+}
177+
155178 func (g *game) fight(id string, x, y int, win func()) {
156179 enc := g.encs[id]
157180 tier := 1
@@ -165,23 +188,29 @@ func (g *game) fight(id string, x, y int, win func()) {
165188 g.state.Log = res.Log
166189 g.state.Encounter = &enc
167190 g.state.Summary.Battles++
191+ g.tally(res.Log)
168192 if res.Outcome != sim.OutcomeVictory {
169193 for i := range g.state.Party.Units {
170194 g.state.Party.Units[i].Stats.HP = 0
171195 }
172196 g.state.Phase = "defeat"
173- g.ended = time.Now()
197+ g.ended = g.now
174198 return
175199 }
176200 g.state.Rewards = &res.Rewards
177201 g.state.Summary.Kills += len(enc.Enemies)
202+ for _, u := range g.state.Party.Units {
203+ if u.Fallen() && slices.ContainsFunc(res.Log, func(e model.CombatEvent) bool { return e.Target == u.ID && e.Killed }) {
204+ g.state.Summary.Fallen++
205+ g.note(u.Name + " has fallen. A potion or a night's camp brings them back")
206+ }
207+ }
178208 g.state.Summary.Loot += len(res.Rewards.Items)
179209 win()
180210 g.pickup(x, y)
181211 g.advance()
182212 if enc.Boss {
183213 g.state.Phase = "victory"
184- g.state.Winner = g.state.PlayerID
185- g.ended = time.Now()
214+ g.ended = g.now
186215 }
187216 }
@@ -26,12 +26,13 @@ func (g *game) visit(x, y int) {
2626 case "lookout":
2727 g.note("From the lookout you see far across the land")
2828 case "shrine":
29- g.healAll()
30- g.note("The shrine's light mends every wound")
29+ g.heal(false)
30+ g.note("The shrine's light mends the wounds of the living")
3131 case "cache":
3232 for i := range g.state.Party.Units {
33- u := &g.state.Party.Units[i]
34- sim.Grant(u, cacheBase+cachePerLv*u.Level)
33+ if u := &g.state.Party.Units[i]; !u.Fallen() {
34+ sim.Grant(u, cacheBase+cachePerLv*u.Level)
35+ }
3536 }
3637 g.note("An old cache of maps and journals: the party gains experience")
3738 }
@@ -46,8 +47,9 @@ func (g *game) spring() {
4647 }
4748 }
4849 for i := range g.state.Party.Units {
49- u := &g.state.Party.Units[i]
50- u.Stats.HP = max(1, u.Stats.HP-max(1, sim.Effective(*u).MaxHP*trapPC/100))
50+ if u := &g.state.Party.Units[i]; !u.Fallen() {
51+ u.Stats.HP = max(1, u.Stats.HP-max(1, sim.Effective(*u).MaxHP*trapPC/100))
52+ }
5153 }
5254 g.note("A trap springs as the chest opens, wounding the party")
5355 }
@@ -0,0 +1,69 @@
1+package server
2+
3+import (
4+ "net"
5+ "net/http"
6+ "strings"
7+ "sync"
8+ "time"
9+)
10+
11+type rate struct{ per, burst float64 }
12+
13+var rates = map[string]rate{
14+ "read": {20, 80},
15+ "act": {8, 60},
16+ "new": {1.0 / 30, 10},
17+ "feedback": {1.0 / 600, 3},
18+}
19+
20+type bucket struct {
21+ tokens float64
22+ last time.Time
23+}
24+
25+type limiter struct {
26+ mu sync.Mutex
27+ buckets map[string]*bucket
28+}
29+
30+func (l *limiter) allow(ip, kind string) bool {
31+ if ip == "" {
32+ return true
33+ }
34+ r := rates[kind]
35+ now := time.Now()
36+ l.mu.Lock()
37+ defer l.mu.Unlock()
38+ if l.buckets == nil || len(l.buckets) > 20000 {
39+ l.buckets = map[string]*bucket{}
40+ }
41+ b := l.buckets[kind+" "+ip]
42+ if b == nil {
43+ b = &bucket{tokens: r.burst, last: now}
44+ l.buckets[kind+" "+ip] = b
45+ }
46+ b.tokens = min(r.burst, b.tokens+now.Sub(b.last).Seconds()*r.per)
47+ b.last = now
48+ if b.tokens < 1 {
49+ return false
50+ }
51+ b.tokens--
52+ return true
53+}
54+
55+func clientIP(r *http.Request) string {
56+ host, _, err := net.SplitHostPort(r.RemoteAddr)
57+ if err != nil {
58+ host = r.RemoteAddr
59+ }
60+ if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
61+ return host
62+ }
63+ xff := r.Header.Get("X-Forwarded-For")
64+ if xff == "" {
65+ return ""
66+ }
67+ parts := strings.Split(xff, ",")
68+ return strings.TrimSpace(parts[len(parts)-1])
69+}
@@ -55,6 +55,7 @@ func (g *game) move(tx, ty, limit int) error {
5555 }
5656 g.state.Party.X, g.state.Party.Y = s[0], s[1]
5757 g.state.Trail = append(g.state.Trail, s)
58+ g.state.Summary.Hexes++
5859 g.pass(g.state.Map.Cost(s[0], s[1]))
5960 g.pickup(s[0], s[1])
6061 g.visit(s[0], s[1])
@@ -3,6 +3,7 @@ package server
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.