Remove outdated architecture documentation and add a new simplified architecture document for Village Sim, detailing the client-server model, backend and frontend structures, data flow, and technology stack.

This commit is contained in:
elit3guzhva 2026-01-18 20:10:26 +03:00
parent 0720dde31f
commit 59ac1133ce
2 changed files with 121 additions and 78 deletions

View File

@ -1,78 +0,0 @@
# Архитектура сервера симуляции (Village Sim)
## 1. Технический стек
### Phase 1 (MVP)
* **Core**: Python 3.11+
* **API**: FastAPI
* **Hot State / Broker**: Redis (используется и как БД, и как очередь сообщений)
* **Analytics**: JSON Logs (файловая система)
### Phase 2 (Target Production)
* **Analytics**: **ClickHouse**. Для хранения логов каждого хода (Time-Series) и ML-обучения.
* **Broker**: **RabbitMQ / Kafka**. Для связи с внешними микросервисами (Внешняя торговля, Auth).
* **Metrics**: Prometheus + Grafana.
## 2. Принципы проектирования (Clean Architecture)
Чтобы легко перейти от Phase 1 к Phase 2, жестко соблюдаем слои:
1. **Domain Layer (Core)**: *Чистый Python.*
* Бизнес-правила (Entity, Value Objects).
* Никаких зависимостей от внешних библиотек.
2. **Application Layer (Services)**: *Оркестрация.*
* Use Cases ("Сделать ход", "Создать игру").
* Работает с интерфейсами (`IEventBus`, `IRepository`), а не конкретными БД.
3. **Infrastructure Layer (Adapters)**: *Грязная реализация.*
* Здесь лежат драйверы Redis, ClickHouse, RabbitMQ.
* Именно этот слой мы будем менять при масштабировании.
## 3. Компоненты системы
### 4.1. API Gateway (FastAPI)
* Входная точка для клиентов.
* Конвертирует HTTP запросы в `Commands`.
### 4.2. Game Engine (Domain)
* **TimeSystem**: Абстракция времени.
* **EntityManager**: ECS-структура.
* **MarketCore**: Логика сведения ордеров.
### 4.3. Infrastructure Adapters
* **RedisGameRepository**: Реализация `IGameRepository`.
* **RedisEventBus**: Реализация `IEventBus` (в Phase 2 заменим на `KafkaEventBus`).
* **FileAnalyticsRepository**: Реализация `IAnalyticsRepository` (в Phase 2 заменим на `ClickhouseRepository`).
## 5. Поток данных (Data Flow)
1. **Action**: Клиент шлет `POST /action`.
2. **Bus**: API кладет команду в `IEventBus` (Redis).
3. **Worker**:
* Поднимает состояние из `IGameRepository`.
* Применяет логику Домена.
* Генерирует события (`FoodEaten`, `ItemCrafted`).
4. **Analytics**: События асинхронно пишутся в `IAnalyticsRepository` (ClickHouse/Files).
## 6. Структура проекта
```text
/app
/domain # ЧИСТАЯ ЛОГИКА
/entities # Agent, Resource
/interfaces # Абстракции: IGameRepository, IEventBus, IAnalytics
/events # Domain Events
/application # СЦЕНАРИИ
/commands # DTO
/use_cases # GameLoopService
/infrastructure # РЕАЛИЗАЦИЯ
/redis # RedisRepo, RedisBus
/clickhouse # (Заготовка) ClickhouseAnalytics
/fs # FileAnalytics
/web # API
/api # Routes
main.py # Dependency Injection Container
```

View File

@ -0,0 +1,121 @@
# Simple Village Simulation Architecture (MVP)
This document outlines the architecture for the Village Simulation based on [Village TZ v2](./village-tz-v2.md). The system follows a client-server model to ensure strict separation between the simulation logic (Backend) and the visualization (Frontend).
## 1. System Overview
The system consists of two distinct applications communicating via HTTP (REST API):
1. **Backend (Server)**: Responsible for the entire simulation state, economic logic, AI decision-making, and turn management.
2. **Frontend (Client)**: A "dumb" terminal using **Pygame** that queries the current state to render it and sends user commands (if any) to the server.
This separation allows replacing the Pygame frontend with Web (React/Vue) or Unity in the future without changing the backend logic.
---
## 2. Backend Architecture (Python)
We adhere to a simplified **Clean Architecture** to keep business logic isolated from the API framework.
### 2.1. Layered Structure
```text
backend/
├── main.py # Entry point, API configuration
├── api/ # Interface Layer (FastAPI)
│ ├── routes.py # Endpoints (GET /state, POST /next_turn)
│ └── schemas.py # Pydantic models for request/response
├── core/ # Business Logic Layer (The "Brain")
│ ├── engine.py # Game Loop manager (Day/Night cycle)
│ ├── world.py # Container for all entities
│ └── market.py # Order Book matching logic
└── domain/ # Data Models (Pure Python)
├── agent.py # Agent logic (stats, inventory, survival rules)
├── resources.py # Resource definitions (Meat, Wood, etc.)
└── action.py # Action definitions (Hunt, Sleep, Trade)
```
### 2.2. Key Components
1. **Domain Models (`domain/`)**:
* `Agent`: Stores state (Energy, Hunger, Money, Inventory). Contains methods like `eat()`, `work()`, but does *not* know about the game loop.
* `Resource`: Enum or classes defining resource properties (decay rate, base value).
2. **Core Engine (`core/`)**:
* `GameEngine`: Singleton that holds the `World` state.
* **Turn Processing**:
* The simulation is **Turn-Based**.
* The Engine waits for a "Next Turn" signal (or runs on a timer).
* Processing order: `Collect Actions` -> `Resolve Market` -> `Update Agent Stats` -> `Remove Dead Agents`.
3. **API (`api/`)**:
* **`GET /state`**: Returns the full snapshot of the world (Agents, Market Order Book, Global Stats) in JSON format.
* **`POST /control/next_step`**: Forces the simulation to advance one tick (useful for debugging/manual control).
* **`POST /market/order`**: (Optional) Allows manual intervention to place orders.
---
## 3. Frontend Architecture (Pygame)
The frontend acts as a **Visualizer**. It does not calculate simulation logic.
### 3.1. Structure
```text
frontend/
├── main.py # Pygame Game Loop
├── client.py # Network Client (requests lib)
├── assets/ # Sprites/Fonts
└── renderer/ # Drawing Logic
├── map_renderer.py # Draws the grid/terrain
├── agent_renderer.py # Draws agents and their status bars
└── ui_renderer.py # Draws text info (Market prices, Day/Night)
```
### 3.2. Flow
1. **Network Step**:
* Call `GET http://localhost:8000/state`.
* Receive JSON: `{"turn": 5, "time_of_day": "day", "agents": [...], "market": [...]}`.
2. **Update Step**:
* Parse JSON into local simplified objects.
3. **Draw Step**:
* Clear screen.
* Render Agents at their coordinates.
* Render UI overlays (e.g., "Day 1, Step 5", "Total Coins: 500").
* `pygame.display.flip()`.
---
## 4. Data Flow & Synchronization
Since the simulation involves AI agents acting autonomously, the Frontend is primarily an **Observer**.
1. **Initialization**: Server starts, generates N agents.
2. **Loop**:
* Server calculates the turn results (AI decisions -> Outcomes).
* Frontend polls `/state` every X milliseconds (or every frame).
* Frontend updates the screen.
### 4.1. The "God Mode" Problem
To test the simulation efficiently, the Server will expose a **Simulation Controller**:
* **Manual Mode**: The server waits for a `POST /next_step` call to advance. The User presses `SPACE` in Pygame -> Pygame sends request -> Server updates -> Pygame fetches new state.
* **Auto Mode**: Server runs a background thread updating every N seconds. Frontend just polls.
*Recommended for MVP: Manual Mode (Spacebar to advance turn).*
---
## 5. Technology Stack
* **Language**: Python 3.11+
* **Backend Framework**: FastAPI (for speed and auto-generated docs).
* **Data Validation**: Pydantic.
* **Frontend**: Pygame Community Edition (pygame-ce).
* **Communication**: HTTP (Requests/Uvicorn).
## 6. Future Extensibility (Why this architecture?)
* **Switch to Web**: Replace `frontend/` folder with a React app. The React app simply calls the same `GET /state` endpoint.
* **Switch to Unity**: Unity `UnityWebRequest` calls `GET /state`.
* **Database**: Currently state is in-memory (`core/engine.py`). Easy to swap for SQLite/Postgres later by adding a `repository` layer in Backend.