Add README and documentation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-24 18:10:43 -04:00
parent 0ff8a32b95
commit 6c7348f924
3 changed files with 639 additions and 0 deletions
+103
View File
@@ -0,0 +1,103 @@
# AI Tycoon
A browser-based incremental/idle game where you manage an AI company from a garage startup to building AGI. Navigate the real tensions of the AI industry: scaling compute, training frontier models, balancing safety vs capability, hiring talent, and competing with rival labs.
**Target:** 4-8 hour single playthrough | **Platform:** Desktop browser | **Price:** Free
## Quick Start
```bash
# Prerequisites: Node.js 18+, pnpm 10+
pnpm install
pnpm dev
```
The web app starts at `http://localhost:5173` (or the next available port). The backend server starts alongside it for cloud saves and leaderboards.
## Tech Stack
| Layer | Choice |
|-------|--------|
| Frontend | React 19 + TypeScript, Vite |
| State | Zustand (slice pattern, localStorage persistence) |
| Styling | Tailwind CSS (custom dark theme) |
| Charts | Recharts |
| Backend | Hono (Node.js) |
| Database | PostgreSQL + Drizzle ORM |
| Monorepo | Turborepo + pnpm workspaces |
## Project Structure
```
ai-tycoon/
├── apps/
│ ├── web/ # React frontend (Vite)
│ └── server/ # Hono API backend
└── packages/
├── shared/ # Types, constants, formatters
└── game-engine/ # Pure TS simulation (no DOM dependencies)
```
The game engine is fully decoupled from React. It runs identically for real-time ticks, offline catch-up, and testing.
## Game Overview
### Four Eras
1. **Startup** (~30 min) — First datacenter, first model, first customers
2. **Scale-up** (~2 hr) — Growth, multiple datacenters, specializations
3. **Big Tech** (~4 hr) — Global operations, regulation, IPO
4. **AGI** (~8 hr) — Endgame push, AI agents, custom chips
### Core Loop
Buy GPUs → Allocate compute → Train models → Deploy → Earn revenue → Expand
### Key Systems
- **Infrastructure** — Datacenters across 7 global regions with different costs, latency, and risks
- **Research** — Tech tree with generation upgrades and specialization branches
- **Models** — Train, tune, and deploy models with capability scores across reasoning, coding, creative, multimodal, and agents
- **Market** — Consumer subscriptions and B2B API with token-based pricing
- **Talent** — Four departments (Research, Engineering, Ops, Sales) with hiring and morale
- **Competitors** — AI rival labs with distinct personalities that react to your moves
- **Events** — 40+ events across industry, regulatory, PR, internal, market, and geopolitical categories
- **Safety** — Tradeoff between capability benchmarks and safety; low safety risks PR disasters
- **Funding** — VC rounds from Seed to IPO with dilution mechanics
- **Achievements** — 15 milestones tracking progression
## Scripts
```bash
pnpm dev # Start all apps in development mode
pnpm build # Production build
pnpm typecheck # Type-check all packages
pnpm lint # Lint all packages
pnpm clean # Clean build artifacts
```
## Backend Setup
The backend requires PostgreSQL for cloud saves and leaderboards. Set the connection string in `apps/server/.env`:
```
DATABASE_URL=postgresql://user:password@localhost:5432/ai_tycoon
```
Run migrations:
```bash
cd apps/server
pnpm db:push
```
The game works fully offline without the backend — saves persist to localStorage.
## Documentation
- [Architecture Guide](docs/architecture.md) — Technical deep dive into the engine, state management, and simulation systems
- [How to Play](docs/how-to-play.md) — Player guide with mechanics, strategies, and tips
## License
All rights reserved.
+302
View File
@@ -0,0 +1,302 @@
# Architecture Guide
## Layer Stack
```
React UI Layer (components, pages, dashboards)
↕ reads/writes via Zustand selectors and actions
Zustand State Layer (14 slices, persisted to localStorage)
↕ engine writes state, UI reads it
Game Engine (pure TypeScript, zero DOM dependencies)
↕ uses formulas, runs systems
Simulation Core (math, scaling laws, cost curves)
```
The game engine and simulation core have no React dependency. They can run identically for real-time play, offline catch-up, and automated testing.
## Monorepo Layout
```
ai-tycoon/
├── turbo.json # Turborepo task config
├── pnpm-workspace.yaml # Workspace definition
├── apps/
│ ├── web/ # React frontend (Vite)
│ │ └── src/
│ │ ├── components/ # layout/, common/, charts/, events/, game/
│ │ ├── pages/ # One page per game system
│ │ ├── store/ # Zustand store with slice pattern
│ │ ├── hooks/ # useGameLoop, useOfflineCatchUp, etc.
│ │ └── lib/ # API client, formatters
│ │
│ └── server/ # Hono backend
│ └── src/
│ ├── db/ # Drizzle schema + migrations
│ ├── routes/ # auth, saves, leaderboards
│ ├── middleware/ # auth, rate limiting
│ └── services/ # Business logic
└── packages/
├── shared/ # Shared types & constants
│ └── src/
│ ├── types/ # All game state type definitions
│ ├── constants/ # gameBalance.ts (single source of truth)
│ └── utils/ # Number/money/time formatting
└── game-engine/ # Pure TS game simulation
└── src/
├── engine.ts # GameEngine class (tick scheduling)
├── tick.ts # Tick processor (orchestrates systems)
├── systems/ # One file per simulation system
└── data/ # Event definitions, tech tree, datasets
```
## Tick System
The game uses a fixed-tick model: 1 tick = 1 second of game time at 1x speed.
### Game Loop
The `useGameLoop` hook runs in the React app:
1. `requestAnimationFrame` fires continuously
2. An accumulator tracks elapsed time since the last tick
3. When accumulated time exceeds `TICK_INTERVAL_MS / gameSpeed`, a tick fires
4. `processTick(state)` runs all systems and returns a partial state update
5. A single `setState` call applies the update to Zustand
Speed controls (1x, 2x, 5x) divide the tick interval, so 5x processes 5 ticks per real second.
### Per-Tick Processing Order
Each tick runs these systems sequentially, since later systems depend on earlier results:
```
1. Infrastructure — GPU health, failures, maintenance
2. Models — Training progress, model completion
3. Market — Demand, subscribers, API calls, revenue calc
4. Compute — Capacity, utilization, allocation
5. Talent — Department effectiveness, morale
6. Research — R&D progress, project completion
7. Reputation — Safety incidents, regulatory standing, score
8. Economy — Revenue, expenses, net cash flow
9. Data — Data acquisition, user data flywheel
10. Competitors — AI rival decisions and actions
11. Events — Random + condition-triggered events
12. Era check — Threshold-based era transitions
13. Valuation — Dynamic company valuation
14. Achievements — Milestone checks (every 10 ticks)
```
### Offline Catch-Up
When the player returns after being away:
- Elapsed ticks = `min((now - lastTick) / interval, MAX_OFFLINE_TICKS)`
- Max offline cap: 24 hours (86,400 ticks)
- Ticks process in batches of `FAST_FORWARD_BATCH_SIZE` (100) with reduced fidelity (`OFFLINE_EFFICIENCY = 0.8`)
- A progress bar shows catch-up progress
- A summary screen reports what happened while away
## State Management
### Zustand Store
The store uses a slice pattern with 14 slices, each owning a portion of the game state:
| Slice | Responsibility |
|-------|---------------|
| `gameMetaSlice` | Tick count, era, pause state, speed, timestamps |
| `economySlice` | Money, revenue, expenses, funding, financial history |
| `infrastructureSlice` | Datacenters, GPUs, locations, total FLOPS |
| `computeSlice` | Training/inference allocation, utilization |
| `researchSlice` | Tech tree, active/completed projects |
| `modelsSlice` | Trained models, active training, deployment |
| `marketSlice` | Subscribers, API demand, pricing, overload policy |
| `competitorSlice` | Rival AI labs, their models, actions |
| `talentSlice` | Departments, headcount, morale, hiring |
| `dataSlice` | Datasets, quality, user data generation |
| `reputationSlice` | Safety record, public perception, regulatory standing |
| `eventSlice` | Active events, history, cooldowns |
| `achievementSlice` | Unlocked achievements |
| `uiSlice` | Active page, notifications, modals (not persisted) |
### Persistence
- **localStorage**: Auto-save every 60 ticks under key `ai-tycoon-save`. The Zustand `persist` middleware handles serialization.
- **Cloud saves**: Optional. POST to `/api/saves` every 5 minutes when authenticated. Requires the Hono backend + PostgreSQL.
- **Save format versioning**: A `version` field in meta enables migration functions for breaking state changes.
### State Flow
```
User Action (click "Buy GPU")
→ Zustand action (buyGPU)
→ Mutates store directly (immer-style)
→ React re-renders via selectors
Tick fires
→ processTick(currentState)
→ Returns Partial<GameState>
→ Zustand merges into store
→ React re-renders
```
Actions that happen instantly (buying, selling, hiring) mutate the store directly. The tick system handles everything time-based (training progress, revenue accrual, demand changes).
## Game Engine Systems
### Economy System (`economySystem.ts`)
Calculates per-tick financials:
- **Revenue**: Market revenue (API tokens + subscriptions)
- **Expenses**: GPU energy costs + maintenance + talent salaries + compliance costs
- **Compliance**: Scales with model capability and era index: `capability * REGULATION_COMPLIANCE_PER_CAPABILITY * (1 + eraIdx * 0.5) / 100`
- **Financial snapshots**: Recorded every 60 ticks, circular buffer of 1000
### Infrastructure System (`infrastructureSystem.ts`)
- Each GPU has a per-tick failure probability (`GPU_FAILURE_RATE_BASE`)
- Redundancy level reduces failure rate by `REDUNDANCY_FAILURE_REDUCTION`
- Failed GPUs are removed from capacity calculations
- Total FLOPS = sum of healthy GPU FLOPS across all datacenters
- Locations have different energy costs, latency tiers, and regulatory environments
### Model System (`modelSystem.ts`)
Training a model:
1. Player commits compute + data tokens + researchers
2. Progress increments per tick, boosted by researcher and engineer effectiveness
3. On completion, `createTrainedModel` generates capability scores:
- Base capability from `sqrt(compute) * 5 + log10(1 + dataTokens/1e8) * 10 + researchBonus`
- Each capability dimension (reasoning, coding, creative, multimodal, agents) gets a random multiplier
- Safety score: `30 + safetyResearch * 15 + random * 10`
- Benchmark penalized by high safety: `(safetyScore - 60) * 0.1` when safety > 60
### Market System (`marketSystem.ts`)
- **Subscribers**: Grow based on model quality, churn based on satisfaction
- **API demand**: Function of subscriber count and pricing
- **Open-source effect**: Boosts subscriber growth, reduces revenue per model
- **Overload handling**: When demand > capacity, player-configured policy determines behavior (queue, degrade quality, prioritize enterprise)
- **Subscriber history**: Sampled every 60 ticks, max 500 entries
### Reputation System (`reputationSystem.ts`)
Composite score (0-100) from four factors:
- **Safety record** (30%): Damaged by safety incidents
- **Public perception** (30%): Affected by events and incidents
- **Employee satisfaction** (20%): Driven by department morale averages
- **Regulatory standing** (20%): `50 + safetyResearch * 8 - eraIndex * 5`
Safety incidents trigger when deployed models have safety scores below `LOW_SAFETY_THRESHOLD` (40), checked every 60 ticks with probability `SAFETY_INCIDENT_PROBABILITY_BASE * (threshold - safetyLevel)`.
### Event System (`eventSystem.ts`)
- 40+ event definitions across 6 categories
- Events have conditions (era, tick count, state thresholds), weights, cooldowns, and max occurrences
- Most events present 2-3 choices with consequences affecting money, reputation, compute, or other state
- Template system with variable interpolation prevents repetition
- Geopolitical events (export controls, energy crises, natural disasters) affect specific regions
### Competitor System (`competitorSystem.ts`)
- 3+ AI rival labs with archetypes (safety-first, move-fast, big tech, open-source)
- Scripted core milestones for pacing
- Personality-driven decision-making
- Light reactive behavior to player actions
- Can be acquired in bigtech/agi eras
### Achievement System (`achievementSystem.ts`)
- 15 achievement definitions with dot-path field access conditions
- Virtual fields for computed values (`meta._eraIndex`, `meta._deployedModelCount`, `infrastructure._totalGpuCount`)
- Checked every 10 ticks for performance
- Notifications on unlock
### Funding System (`fundingSystem.ts`)
- 6 rounds: Seed → Series A → B → C → D → IPO
- Each round has amount, dilution percentage, and requirements (min revenue, users, reputation)
- Dynamic valuation computed from revenue, subscribers, and model capability
- Dilution reduces founder equity permanently
## Frontend Architecture
### Routing
No router library — the active page is stored in Zustand (`uiSlice.activePage`). The sidebar sets it, `MainLayout` renders the corresponding page component. This keeps things simple for a single-page game.
### Pages
| Page | System |
|------|--------|
| Dashboard | Overview KPIs, tutorial hints, trend charts |
| Infrastructure | Datacenter management, GPU purchasing |
| Research | Tech tree, active projects |
| Models | Training, deployment, tuning |
| Market | Pricing, subscribers, overload policy |
| Talent | Department management, hiring |
| Data | Dataset marketplace, data quality |
| Competitors | Rival labs, acquisition |
| Finance | Cash flow, funding rounds, financial history |
| Achievements | Achievement grid with unlock status |
| Leaderboard | Global rankings by category |
| Settings | Sound, save management, export/import |
### Progressive Disclosure
- Pages unlock as the player progresses through eras
- Newly available pages get a "NEW" badge in the sidebar
- Tutorial hints appear contextually and persist dismissal to localStorage
### Charts
All charts use Recharts with consistent dark-theme styling. Chart data comes from circular buffer history arrays in the game state (financial snapshots, subscriber history, reputation history).
## Backend Architecture
### API Routes
```
POST /api/auth/anonymous # Create anonymous session (UUID token)
POST /api/auth/link # Link email/password to anonymous session
POST /api/auth/login # Email/password login
GET /api/saves # List saves for authenticated user
POST /api/saves # Create/update save
GET /api/saves/:id # Load specific save
GET /api/leaderboard/:cat # Get leaderboard by category
POST /api/leaderboard # Submit score
```
### Database
PostgreSQL with Drizzle ORM. Tables: `users`, `saves`, `leaderboard_entries`.
### Auth
Anonymous-first: players get a UUID token on first visit. Optional email/password linking for cross-device play. JWT-based session tokens.
## Performance Considerations
- Game engine runs outside React's render cycle; single `setState` per tick
- Achievements check every 10 ticks, events every 30 ticks
- History arrays use circular buffers with configurable max sizes
- Snapshots sample at intervals (every 60-120 ticks), not every tick
- All systems are bounded O(n) where n is small (number of GPUs, models, competitors)
- Speed modes simply increase tick frequency, not computation complexity
## Key Design Decisions
1. **Pure engine**: The game-engine package has zero DOM/React dependencies, enabling offline catch-up, testing, and potential server-side simulation.
2. **Single constants file**: All balance numbers live in `gameBalance.ts`. One place to tune everything.
3. **Slice pattern**: Each game system owns its state slice. Slices compose into the full store without coupling.
4. **Notifications via `_notifications`**: The tick processor attaches notifications as a side-channel property on the result, keeping the return type clean while enabling the UI to show contextual alerts.
5. **Cached definitions**: Event and achievement definitions are set once at game start via `setEventDefinitions` / `setAchievementDefinitions`, avoiding repeated imports in the hot tick path.
+234
View File
@@ -0,0 +1,234 @@
# How to Play
## Getting Started
When you start a new game, you name your AI company and begin in the **Startup era** with $50,000 in seed money. Your goal: build the world's leading AI company and eventually achieve AGI.
The game runs in real-time at 1 tick per second. Use the speed controls in the top bar to play at 1x, 2x, or 5x speed, or pause to plan your next moves.
## The Core Loop
The fundamental cycle of the game:
1. **Buy GPUs** — Purchase compute hardware in the Infrastructure page
2. **Allocate compute** — Split between training new models and serving inference
3. **Train a model** — Start a training run in the Models page
4. **Deploy** — Put your trained model into production
5. **Earn revenue** — Users pay for API access and subscriptions
6. **Reinvest** — Buy more GPUs, hire talent, fund research
Everything else in the game builds on or modifies this loop.
## Key Resources
### Money
Your primary resource. Earned from API revenue and consumer subscriptions. Spent on GPUs, talent, data, and energy. Shown in the top bar with income trend.
### Compute (FLOPS)
Total processing power from your GPU fleet. The main bottleneck — you never have enough. Split between training (building new models) and inference (serving users).
### Reputation (0-100)
Public trust in your company. Affects talent acquisition, user growth, investor confidence, and regulatory treatment. Composed of safety record, public perception, employee satisfaction, and regulatory standing.
### Talent
Headcount across four departments: Research, Engineering, Ops, and Sales. Each department has effectiveness and morale scores that affect their output.
### Data
Training data quality and quantity. Better data produces better models. Acquired through the data marketplace or generated passively from your user base.
### Research
Progress through the tech tree. Unlocks better GPU tiers, model architectures, efficiency improvements, and safety techniques.
## Game Systems
### Infrastructure
Your datacenters house GPU clusters. Seven global regions are available, each with tradeoffs:
- **US-West / US-East** — Balanced costs, good latency to North American users
- **EU-West / EU-North** — Higher energy costs, strict regulation, access to EU market
- **Asia-East / Asia-South** — Lower costs, emerging markets
- **Middle-East** — Cheap energy, political risk
Each datacenter has a size (GPU slots), cooling level, and redundancy level. Higher redundancy reduces GPU failure rates but costs more. GPUs can fail randomly — lost hardware means lost capacity until you replace them.
GPU types unlock through research. Early on you have basic GPUs; research unlocks progressively more powerful (and expensive) tiers.
### Research
The tech tree has two dimensions:
- **Generations**: Small → Medium → Large → Frontier → AGI-scale models
- **Specializations**: Reasoning, coding, creative, multimodal, agents
Research projects require researchers and time. Completing projects unlocks new capabilities:
- Better GPU tiers
- Training efficiency improvements (quantization, distillation)
- Safety techniques (alignment research, interpretability)
- New product capabilities
### Models
Training a model requires:
- **Compute**: How many FLOPS to dedicate to training
- **Data**: Training data tokens to use
- **Time**: Training runs take real time (boosted by researcher and engineer quality)
When training completes, your model gets capability scores across five dimensions: reasoning, coding, creative, multimodal, and agents. A composite benchmark score determines its market competitiveness.
#### Safety vs Capability
This is the game's central tension. Safety research improves your model's safety score but penalizes benchmark performance. Low safety scores risk:
- **Safety incidents**: PR disasters that damage reputation
- **Regulatory backlash**: Higher compliance costs
High safety scores mean:
- Lower benchmarks (competitors may outperform you)
- Better regulatory standing
- Protection from reputation-damaging incidents
There's no single right answer — it depends on your strategy.
#### Model Tuning
After deploying a model, you can tune its behavior:
- **Presets**: Quick settings (Helpful-Safe, Performance, Creative, Balanced)
- **Sliders**: Fine-grained control over safety, creativity, verbosity, and speed/quality tradeoff (unlocked after completing alignment research)
### Market
Revenue comes from two sources:
**Consumer Subscriptions**: Users pay a monthly fee for your chat product. Subscriber count grows based on model quality and shrinks from churn. Higher quality models and competitive pricing accelerate growth.
**B2B API**: Enterprise customers pay per token. Set your input/output token pricing to balance revenue against demand.
#### Overload Policy
When demand exceeds your inference capacity, you choose how to handle it:
- **Queue depth**: How many requests to buffer
- **Rate limits**: Max requests per user
- **Degrade quality**: Serve faster but lower-quality responses
- **Prioritize enterprise**: Give B2B customers priority over consumers
Each choice has tradeoffs. Degrading quality hurts satisfaction. Enterprise prioritization frustrates consumer users.
#### Open Source
You can open-source deployed models. This:
- Boosts reputation significantly
- Attracts more talent
- Reduces direct revenue from that model
- Increases subscriber growth (community effect)
### Talent
Four departments, each critical:
| Department | Effect |
|-----------|--------|
| Research | Speeds up R&D projects and improves model training quality |
| Engineering | Speeds up model training and infrastructure reliability |
| Ops | Reduces infrastructure costs and failure rates |
| Sales | Increases enterprise API demand |
Hire to increase headcount. Morale affects effectiveness — keep your teams happy by managing workload and company reputation.
### Competitors
Three rival AI labs compete with you. Each has a personality:
- Some prioritize safety, others move fast
- Some are big-tech giants with deep pockets, others are scrappy startups
- They release models, gain users, and react to your moves
In later eras (Big Tech and AGI), you can **acquire** competitors, absorbing their talent and technology.
### Events
Random and conditional events keep the game dynamic. Categories include:
- **Industry**: Breakthroughs, open-source releases, benchmarks
- **Regulatory**: Hearings, compliance requirements, AI bills
- **PR/Cultural**: Media coverage, safety debates, public opinion shifts
- **Internal**: Employee issues, technical problems
- **Market**: Demand spikes, pricing pressure
- **Geopolitical**: Export controls, energy crises, natural disasters
Most events present 2-3 choices with meaningful tradeoffs. Some trigger chain events with delayed consequences.
### Funding
Raise capital through VC rounds as you grow:
| Round | Amount | Dilution | Key Requirement |
|-------|--------|----------|----------------|
| Seed | $100K | 10% | $100/s revenue |
| Series A | $500K | 15% | 100 users, 20 reputation |
| Series B | $2M | 12% | 1,000 users, 30 reputation |
| Series C | $10M | 10% | 10,000 users, 40 reputation |
| Series D | $50M | 8% | 50,000 users, 50 reputation |
| IPO | $200M | 20% | 100,000 users, 60 reputation |
Each round permanently dilutes your founder equity. Time your raises carefully — you want enough runway to grow but minimum dilution.
## Era Progression
The game has four eras that unlock progressively. Transitions happen automatically when you meet thresholds:
### Startup → Scale-up
- Revenue: $10,000/s
- Best model capability: 15+
- Reputation: 30+
### Scale-up → Big Tech
- Revenue: $1,000,000/s
- Best model capability: 50+
- Reputation: 60+
### Big Tech → AGI
- Revenue: $100,000,000/s
- Best model capability: 90+
- Reputation: 70+
Each era unlocks new game systems and sidebar pages. Watch for the "NEW" badge on newly available pages.
## Strategies
### The Safety-First Path
Invest heavily in alignment and interpretability research. Your benchmarks will lag competitors initially, but you avoid safety incidents and build strong regulatory standing. Good for steady, sustainable growth.
### The Move-Fast Path
Minimize safety investment, maximize raw capability. You'll lead benchmarks and attract users quickly, but safety incidents can crater your reputation. High risk, high reward.
### The Open-Source Play
Open-source your models to build massive community goodwill and attract top talent. Revenue per model drops, but subscriber growth accelerates and reputation soars. Strong mid-game strategy.
### The Vertical Integrator
Invest in multiple specializations and diverse products. Spread your compute across reasoning, coding, creative, and multimodal capabilities. More resilient but slower to dominate any single benchmark.
## Tips
- **Don't neglect infrastructure redundancy.** GPU failures at scale can cripple your capacity.
- **Watch your burn rate.** It's easy to over-hire and run out of money before your models generate revenue.
- **Timing funding rounds matters.** Raise too early and you give up equity cheaply. Raise too late and you run out of runway.
- **Safety research compounds.** Each safety project improves all future models.
- **Check competitor activity.** If a rival just released a strong model, expect to lose some subscribers unless you respond.
- **Events have lasting consequences.** Read the options carefully — some choices trigger follow-up events.
- **The data flywheel is real.** More users generate more data, which trains better models, which attract more users.
- **Deploy your models.** A trained model sitting idle generates zero revenue.
- **Use speed controls.** Pause when making big decisions. Speed up during waiting periods.
## Saving
The game auto-saves to your browser's localStorage every 60 ticks. You can also:
- **Export** your save as a JSON file from the Settings page
- **Import** a previously exported save
- **Cloud save** by creating an account (requires the backend server)
Closing the browser tab is safe — when you return, an offline catch-up system simulates what happened while you were away (up to 24 hours).
## Achievements
15 achievements track your progression milestones, from training your first model to reaching AGI. Check the Achievements page to see what you've unlocked and what's still ahead.