villsim/README.md

225 lines
7.1 KiB
Markdown

# Village Economy Simulation
A turn-based agent simulation of a village economy where AI agents work, trade, and survive based on prioritized needs.
## Overview
This project simulates a village economy with autonomous AI agents. Each agent has vital stats (energy, hunger, thirst, heat), can perform various actions (hunting, gathering, crafting), and trades resources on a central market.
### Features
- **Agent-based simulation**: Multiple AI agents with different professions
- **GOAP AI system**: Goal-Oriented Action Planning for intelligent agent behavior
- **Vital stats system**: Energy, Hunger, Thirst, and Heat with passive decay
- **Market economy**: Order book system for trading resources
- **Day/Night cycle**: 10 day steps + 1 night step per day
- **Real-time visualization**: Web-based frontend showing agents and their states
- **Agent movement**: Agents visually move to different locations based on their actions
- **Action indicators**: Visual feedback showing what each agent is doing
- **GOAP Debug Panel**: View agent planning and decision-making in real-time
- **Detailed logging**: All simulation steps are logged for analysis
## Architecture
```
villsim/
├── backend/ # FastAPI server
│ ├── main.py # Entry point
│ ├── config.py # Centralized configuration
│ ├── api/ # REST API endpoints
│ ├── core/ # Game logic (engine, world, market, AI, logger)
│ │ └── goap/ # GOAP AI system (planner, actions, goals)
│ └── domain/ # Data models (agent, resources, actions)
├── web_frontend/ # Web-based visualizer
│ ├── index.html # Main application
│ ├── goap_debug.html # GOAP debugging view
│ └── src/ # JavaScript modules (scenes, API client)
├── tools/ # Analysis and optimization scripts
├── logs/ # Simulation log files (created on run)
├── docs/design/ # Design documents
├── requirements.txt
└── config.json # Saved configuration (optional)
```
## Installation
### Prerequisites
- Python 3.11 or higher
- pip
### Setup
1. Clone the repository:
```bash
git clone <repository-url>
cd villsim
```
2. Create a virtual environment (recommended):
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
## Running the Simulation
### Start the Backend Server
Open a terminal and run:
```bash
python -m backend.main
```
The server will start at `http://localhost:8000`. You can access:
- API docs: `http://localhost:8000/docs`
- Health check: `http://localhost:8000/health`
### Start the Web Frontend
Open the web frontend by opening `web_frontend/index.html` in a web browser, or serve it with a local HTTP server:
```bash
cd web_frontend
python -m http.server 8080
```
Then navigate to `http://localhost:8080` in your browser.
## Controls
The web frontend provides buttons for:
- **Step**: Advance one turn (manual mode)
- **Auto/Manual**: Toggle between automatic and manual mode
- **Reset**: Reset simulation
Click on agents to see detailed information. Use the GOAP debug panel (`goap_debug.html`) to inspect agent planning.
## Logging
All simulation steps are logged to the `logs/` directory:
- `sim_YYYYMMDD_HHMMSS.jsonl`: Detailed JSON lines format for programmatic analysis
- `sim_YYYYMMDD_HHMMSS_summary.txt`: Human-readable summary of each turn
- `sim_YYYYMMDD_HHMMSS.log`: Standard Python logging output
Log files include:
- Every agent's stats before and after each turn
- AI decisions and reasons
- Action results (success/failure, resources gained)
- Market transactions
- Deaths and their causes
## API Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/state` | GET | Full simulation state |
| `/api/control/next_step` | POST | Advance one turn |
| `/api/control/mode` | POST | Set mode (manual/auto) |
| `/api/control/initialize` | POST | Reset simulation |
| `/api/agents` | GET | List all agents |
| `/api/market/orders` | GET | Active market orders |
| `/api/config` | GET | Get current configuration |
| `/api/config` | POST | Update configuration |
| `/api/config/reset` | POST | Reset config to defaults |
## Simulation Rules
### Agent Stats
| Stat | Max | Start | Decay/Turn |
|------|-----|-------|------------|
| Energy | 100 | 80 | -2 |
| Hunger | 100 | 80 | -2 |
| Thirst | 50 | 40 | -3 |
| Heat | 100 | 100 | -2 |
- Agents die if Hunger, Thirst, or Heat reaches 0
- Energy at 0 prevents actions but doesn't kill
- Clothes reduce heat decay by 50%
### Resources
| Resource | Source | Effect | Decay |
|----------|--------|--------|-------|
| Meat | Hunting | Hunger +30, Energy +5 | 5 turns |
| Berries | Gathering | Hunger +5, Thirst +2 | 20 turns |
| Water | Water source | Thirst +40 | ∞ |
| Wood | Chopping | Fuel for fire | ∞ |
| Hide | Hunting | Craft material | ∞ |
| Clothes | Weaving | Reduces heat loss | 50 turns |
### Professions
- **Hunter** (H): Hunts for meat and hide - moves to forest area
- **Gatherer** (G): Collects berries - moves to bushes area
- **Woodcutter** (W): Chops wood - moves to forest area
- **Crafter** (C): Weaves clothes from hide - works in village
### Agent Movement
Agents visually move across the map based on their actions:
- **River** (left): Water gathering
- **Bushes** (center-left): Berry gathering
- **Village** (center): Crafting, trading, resting
- **Forest** (right): Hunting, wood chopping
Action indicators above agents show:
- Current action letter (H=Hunt, G=Gather, etc.)
- Movement animation when traveling
- Dotted line to destination
### AI System (GOAP)
The simulation uses Goal-Oriented Action Planning (GOAP) for intelligent agent behavior:
1. **Goals**: Agents have weighted goals (Survive, Maintain Heat, Build Wealth, etc.)
2. **Actions**: Agents can perform actions with preconditions and effects
3. **Planning**: A* search finds optimal action sequences to satisfy goals
4. **Personality**: Each agent has unique traits affecting goal weights and decisions
## Development
### Project Structure
- **Config** (`backend/config.py`): Centralized configuration with dataclasses
- **Domain Layer** (`backend/domain/`): Pure data models
- **Core Layer** (`backend/core/`): Game logic, market, logging
- **GOAP AI** (`backend/core/goap/`): Goal-oriented action planning system
- **API Layer** (`backend/api/`): FastAPI routes and schemas
- **Web Frontend** (`web_frontend/`): Browser-based visualization
### Analyzing Logs
The JSON lines log files can be analyzed with Python:
```python
import json
with open("logs/sim_20260118_123456.jsonl") as f:
for line in f:
entry = json.loads(line)
if entry["type"] == "turn":
turn_data = entry["data"]
print(f"Turn {turn_data['turn']}: {len(turn_data['agent_entries'])} agents")
```
### Future Improvements
- Social interactions (gifting, cooperation)
- Agent reproduction
- Skill progression
- Persistent save/load
- Unity frontend integration
## License
MIT License