Oregon Trail — IA Edition
ryandakine/oregon-trail
Jogo histórico em navegador com IA como mestre — sem banco de dados
Ver no GitHubJogo browser do Oregon Trail onde a IA funciona como mestre do jogo, gerando eventos únicos contextualizados em 1848. Utiliza Cloudflare Workers para simulação servidor-autoritária com estado assinado por HMAC e chamadas a Claude para narrativa dinâmica, sem banco de dados ou login.
Instalação
npx convez-ai ryandakine/oregon-trail1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Criar jogos narrativos baseados em IA com estado criptografado
- Implementar simulações serverless com verificação de integridade
- Gerar conteúdo dinâmico via Claude em aplicações web leves
Veredito

Implementação sofisticada de arquitetura sem banco de dados com IA generativa integrada. Exemplo educativo robusto para quem quer combinar Workers, Claude e state-signing em produção, mas com escopo muito específico (jogo); reutilizável como padrão para outros contextos narrativos.
README
A tradução para o português deste README ainda está na fila.
Oregon Trail — AI Edition
A free, browser-playable reimagining of The Oregon Trail where an AI acts as the dungeon master. Every playthrough generates unique events grounded in real 1848 historical context. No login, no database, no install.
Live: trail.osi-cyber.com
Architecture
The game splits cleanly into two deployables:
- Backend — a single Cloudflare Worker
(TypeScript) that runs all game simulation, calls Anthropic Claude to
generate events, and signs game state with HMAC-SHA256. Source in
worker/src/. - Frontend — static files in
public/served by Cloudflare Pages. The client renders state with Kaplay (loaded from CDN) on a 640×480 pixel-art canvas and sends player choices back to the Worker. It does not run simulation.
Key design decisions:
- Server-authoritative simulation. All mutation happens in the Worker; the client is a display + input layer.
- HMAC-signed state, no database. The client holds the entire
GameStateblob, signed via HMAC-SHA256 (worker/src/hmac.ts). The Worker verifies the signature on every request, mutates, and re-signs. This is the anti-cheat and the reason there's no server-side storage. Journal/resume data lives in the browser'slocalStorage. - AI as dungeon master. Events are generated by Anthropic Claude
(
claude-haiku-4-5-20251001) from the current game state plus historical context (worker/src/anthropic.ts,prompt-assembly.ts). If the API call fails or times out, the Worker falls back to pre-written events so play never stalls. - Three tone tiers.
low(classroom-safe),medium(default), andhigh(darker, with a hidden horror-tier "Bitter Path" branch gated behind a content warning).
Tech Stack
| Layer | Tech |
|---|---|
| Backend | Cloudflare Workers, TypeScript ~5.8, Wrangler 4 |
| AI | Anthropic Claude Haiku 4.5 (claude-haiku-4-5-20251001) |
| Frontend | Static HTML + vanilla JS + Kaplay 3001 (CDN), no build step |
| State | HMAC-SHA256-signed JSON (no database) |
| Tests | Vitest 3 (Worker unit tests + Playwright-driven scene smokes) |
| Hosting | Cloudflare Pages (frontend) + Cloudflare Workers (API) |
| Analytics | Plausible |
Project Structure
oregon-trail/
├── worker/
│ ├── src/
│ │ ├── index.ts # API routes + request handlers (Worker entry; main per wrangler.toml)
│ │ ├── types.ts # Shared TypeScript types
│ │ ├── state.ts # Initial state, store prices, weekly challenges, sign-on-mutate helpers
│ │ ├── simulation.ts # advanceDays() — server-side core game loop
│ │ ├── anthropic.ts # callAnthropic(), event parsing, FALLBACK_EVENTS
│ │ ├── prompt-assembly.ts # Builds LLM prompts from game state + history
│ │ ├── prompt-templates.ts # System prompts per tone tier
│ │ ├── context-loader.ts # Lookup helpers over historical-context.json
│ │ ├── hmac.ts # signState(), verify, deepCanonicalize()
│ │ └── historical-context.json # 1848 segments, landmarks, diseases, nations
│ └── tests/ # Vitest Worker unit tests
├── public/ # Static frontend — served by Cloudflare Pages
│ ├── index.html # Canvas shell + event/newspaper/tombstone overlays + PWA registration
│ ├── engine.js # Client GameEngine: state machine + API client (apiBase points at the Worker)
│ ├── main.js # Kaplay init, scene registration, stateChange bridge
│ ├── lib/ # Shared ES modules: draw.mjs, hud.mjs, tone.mjs
│ ├── scenes/ # Kaplay scenes (title, store, travel, event, river, hunting, …)
│ ├── newspaper.js, tombstone.js# DOM renderers for share artifacts
│ ├── sw.js, manifest.json # PWA service worker + manifest
│ └── fonts/, icons/ # IBM Plex Mono + PWA icons
├── test/frontend/ # Playwright-driven scene smoke tests (vitest "frontend" project)
├── scripts/
│ ├── deploy-pages.sh # Gated frontend deploy (test → preview → smoke → promote)
│ ├── deploy-smoke.mjs # Post-deploy smoke probe
│ └── … # Calibration, playthrough, and QA helpers
├── package.json # Scripts + devDependencies (no runtime deps)
├── wrangler.toml # Worker config
├── tsconfig.json
└── vitest.config.ts # Two projects: "worker" + "frontend"
Getting Started
Requires Node.js and a Cloudflare account
(for wrangler). Dependencies are dev-only — there are no runtime npm packages.
npm install
Run the Worker locally
npm run dev # wrangler dev
Provide secrets for local dev via a .dev.vars file (gitignored) in the repo root:
HMAC_SECRET=<any-strong-secret>
ANTHROPIC_API_KEY=<your-anthropic-key>
ALLOWED_ORIGIN=*
Serve the frontend locally
public/ is plain static files with no build step. Serve them with any static
server, e.g.:
npx serve public -p 8765
Note: public/engine.js points apiBase at the deployed Worker
(https://oregon-trail-api.trails710.workers.dev). Edit that value if you want
the local frontend to hit a local wrangler dev Worker.
Configuration
Worker secrets are set with wrangler secret put (never committed):
| Name | Where set | Purpose |
|---|---|---|
HMAC_SECRET | wrangler secret put HMAC_SECRET | Key for signing/verifying game state |
ANTHROPIC_API_KEY | wrangler secret put ANTHROPIC_API_KEY | Anthropic API key for event generation |
ALLOWED_ORIGIN | env / secret | Comma-separated allowed CORS origins (* allows all) |
ENVIRONMENT | wrangler.toml [vars] | production |
BITTER_PATH_ENABLED | env (optional) | Kill switch for the hidden horror branch; default true (set "false" to disable) |
Testing
Tests run with Vitest. vitest.config.ts defines two projects:
npm test # vitest run — both projects
npm run test:watch # watch mode
npx vitest run --project worker # Worker unit tests only
npx vitest run --project frontend # Playwright-driven scene smokes only
The frontend project drives Chromium via Playwright and uses longer timeouts;
it shares a single browser across tests.
Deployment
npm run deploy # deploy:worker then deploy:pages
npm run deploy:worker # wrangler deploy (Worker)
npm run deploy:pages # scripts/deploy-pages.sh (gated Pages deploy)
scripts/deploy-pages.sh runs Worker unit tests, deploys to a Cloudflare Pages
preview, smoke-probes the preview with deploy-smoke.mjs, and only promotes to
production (trail.osi-cyber.com) if the smoke passes. Useful flags:
--skip-tests— smoke only (not recommended)--smoke-only— probe production without deploying
The frontend domain trail.osi-cyber.com is a Cloudflare Pages project; the
Worker is published to oregon-trail-api.trails710.workers.dev.
API
The Worker exposes a JSON API (CORS-gated, in-memory rate limited at 200 requests/min per IP). Notable endpoints:
| Method | Path | Purpose |
|---|---|---|
| POST | /api/start | Create a new signed game (leader + 4 members, profession, tone) |
| POST | /api/store | Apply pre-departure store purchases |
| POST | /api/advance | Advance days; may return an AI event, landmark, or river |
| POST | /api/choice | Resolve a pending event choice |
| POST | /api/river | Resolve a river crossing (ford / caulk / ferry) |
| POST | /api/landmark | Rest or trade at a landmark |
| POST | /api/hunt | Hunting mini-game |
| POST | /api/newspaper | Generate an end-of-run 1848 newspaper |
| POST | /api/epitaph | Generate a gravestone inscription |
| POST | /api/bitter_path | Resolve the hidden horror-tier branch |
| POST | /api/bitter_path_skip | Opt out of the horror branch |
| GET | /api/prices | Current store prices |
| GET | /api/challenge | Current + all weekly challenges |
Every mutating request must carry the HMAC-signed state from the previous response; the Worker rejects states with a missing or invalid signature.