# 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 - **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 - **Maslow-priority AI**: Agents prioritize survival over economic activities - **Real-time visualization**: Pygame 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 - **Settings panel**: Adjust simulation parameters with sliders - **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) │ └── domain/ # Data models (agent, resources, actions) ├── frontend/ # Pygame visualizer │ ├── main.py # Entry point │ ├── client.py # HTTP client │ └── renderer/ # Drawing components (map, agents, UI, settings) ├── 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 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 Frontend Visualizer Open another terminal and run: ```bash python -m frontend.main ``` A Pygame window will open showing the simulation. ## Controls | Key | Action | |-----|--------| | `SPACE` | Advance one turn (manual mode) | | `R` | Reset simulation | | `M` | Toggle between MANUAL and AUTO mode | | `S` | Open/close settings panel | | `ESC` | Close settings or quit | Hover over agents to see detailed information. ## Settings Panel Press `S` to open the settings panel where you can adjust: - **Agent Stats**: Max values and decay rates for energy, hunger, thirst, heat - **World Settings**: Grid size, initial agent count, day length - **Action Costs**: Energy costs for hunting, gathering, etc. - **Resource Effects**: How much stats are restored by consuming resources - **Market Settings**: Price adjustment timing and rates - **Simulation Speed**: Auto-step interval Changes require clicking "Apply & Restart" to take effect. ## 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 Priority System 1. **Critical needs** (stat < 20%): Consume, buy, or gather resources 2. **Energy management**: Rest if too tired 3. **Economic activity**: Sell excess inventory, buy needed materials 4. **Routine work**: Perform profession-specific tasks ## Development ### Project Structure - **Config** (`backend/config.py`): Centralized configuration with dataclasses - **Domain Layer** (`backend/domain/`): Pure data models - **Core Layer** (`backend/core/`): Game logic, AI, market, logging - **API Layer** (`backend/api/`): FastAPI routes and schemas - **Frontend** (`frontend/`): Pygame visualization client ### 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 - Web-based frontend alternative ## License MIT License