A real-time civilization sandbox where autonomous agents learn from scratch, survive a living world, build infrastructure, form relationships, and carry knowledge across generations.
Симулятор цивилизации в реальном времени, где автономные агенты учатся с нуля, выживают в живом мире, строят, влюбляются и передают опыт следующим поколениям.
Autonomous agents. Persistent learning. Emergent stories.
- Pure Python, Pygame, and NumPy.
- Reflexes for survival + DQN for long-term behavior.
- Emotions, trust, messages, pair-wise love, trade, and reproduction.
- Stone Age → Bronze Age → Iron Age progression with craftable tools and buildings.
- Procedural world with wildlife, day/night, rain, seasons, and temperature shifts.
- Persistent
brain.savekeeps learned progress alive across restarts.
Main simulation view with live population, season, weather, speed controls, and world activity.
Focused-agent view with current action, mood, relationship status, generation info, and quick controls.
CivSim is a real-time agent-based civilization simulator built with Python and Pygame. You create the world, place autonomous humans inside it, and then watch a society emerge from survival pressure, social bonds, learning, and repetition.
Every agent is shaped by two layers at once: hard survival reflexes for immediate danger, and a learned DQN policy for longer-term decisions. Over time, agents gather resources, craft tools, build structures, trust or avoid each other, fall in love, reproduce, and pass both knowledge and mutated traits to the next generation.
- The agents are not scripted puppets: they combine emergency reflexes with a neural policy trained from scratch in pure
numpy. - The social layer is personal: trust and love are tracked per agent, not as one generic reputation number.
- Knowledge persists: the simulation can carry learning across runs through
brain.save. - Civilization emerges from pressure: hunger, thirst, fatigue, predators, weather, and seasons constantly reshape behavior.
- The world keeps pushing back: deer and rabbits can be hunted, while wolves and bears create real danger.
git clone https://github.com/v0id-core/civilization-sim.git
cd civilization-sim
pip install -r requirements.txt
python main.pyRequirements:
- Python
3.10+ pygame>=2.5.0numpy>=1.24.0
- Survival loop: hunger, thirst, energy, and health constantly decay, so even simple existence becomes a meaningful decision problem.
- Social behavior: agents share danger, food, and help messages; trust each other at different levels; and develop pair-wise affection over time.
- Love and reproduction: compatible agents can reproduce, creating children with inherited brain influence and mutated genetic traits.
- Physical economy: trade is tangible, with items dropped on the ground rather than teleported through menus.
- Visible progression: agents move from Stone Age to Bronze Age to Iron Age as they unlock stronger tools and structures.
- A living world: the map includes food, berries, trees, stone, copper, iron, water, changing seasons, rain, temperature shifts, and wildlife.
| System | What it does |
|---|---|
| Survival | Hunger, thirst, energy, and health force constant prioritization. |
| Social Layer | Trust, pair-wise love, message broadcasting, and cooperation shape behavior. |
| Reproduction | Children inherit mixed learning influence and mutated traits such as metabolism, sociality, and gather speed. |
| Progression | Stone → Bronze → Iron unlocks better tools, stronger weapons, and more advanced buildings. |
| Building | Agents can create campfires, walls, storage, wells, farms, watchtowers, and forges. |
| Economy | Resource gathering, crafting, and dropped-item trade create a simple physical economy. |
| Ecology | Deer, rabbits, wolves, and bears create opportunities and threats across the map. |
| World Pressure | Day/night, rain, season changes, and temperature affect survival and decision-making. |
| Persistence | brain.save stores learned progress, generation data, and best-run metadata across sessions. |
- Two-layer behavior model: hardcoded reflexes handle urgent survival cases, while the DQN handles longer-term action selection.
- Neural network from scratch: the brain is implemented in pure
numpy, without external ML frameworks. - Compact decision state: the DQN operates on a 26-feature state vector built from needs, inventory, tools, nearby resources, buildings, kills, seeds, and time-of-day context.
- Standard RL machinery: replay buffer, target network, epsilon-greedy exploration, and reward shaping are all implemented directly in the project.
- Spatial optimization: spatial hashing and tile indexing reduce expensive proximity checks in a crowded world.
- Navigation: A* pathfinding with path caching helps agents route around obstacles efficiently.
| Key / Button | Action |
|---|---|
R |
New world + new generation |
Space |
Pause / Resume |
A |
Toggle auto-restart when all agents die |
1 / 2 / 3 |
Speed ×1 / ×2 / ×5 |
< > buttons |
Switch UI focus to another agent |
EN/RU button |
Toggle interface language live |
The UI tracks more than raw survival numbers. You can follow the focused agent, see mood and social hints, inspect generation and best-tick stats, watch current season/weather/temperature, and read a live event log as the world evolves.
main.py - game loop, rendering, UI, focus controls, language toggle
agent.py - agents, emotions, trust, love, reproduction, trade, spatial systems
brain.py - DQN implementation in pure numpy, replay buffer, persistence
config.py - constants, recipes, tuning values, world and simulation parameters
world.py - procedural world generation, seasons, temperature, tile rendering
entities.py - animals and building rendering/behavior helpers
brain.save - persistent learning state created automatically on first save
brain.savestores network weights, target weights, epsilon, training counters, generation count, lives, and best survival record.- If the file exists, CivSim loads prior learning on startup.
- If you want a fully fresh training run, removing
brain.saveresets the accumulated learned progress.
CivSim — это симуляция цивилизации в реальном времени на Python и Pygame. Ты создаёшь мир, запускаешь в него автономных людей и наблюдаешь, как из выживания, обучения, конфликтов и отношений постепенно рождается маленькая история общества.
Главная идея проекта в том, что агенты не просто ходят по скрипту. Они реагируют на срочные угрозы рефлексами, а долгосрочное поведение выбирают через DQN, обучаемый с нуля на чистом numpy.
- Живые агенты: голод, жажда, энергия, здоровье, эмоции и личные отношения влияют на каждое решение.
- Социалка не для галочки: есть доверие, сообщения об опасности и еде, попарная любовь, торговля и размножение.
- Развитие цивилизации: крафт, инструменты, оружие, постройки и переход от каменного века к бронзовому и железному.
- Живой мир: процедурная карта, еда, ягоды, деревья, камень, медь, железо, дождь, день и ночь, сезоны и температура.
- Память между запусками:
brain.saveсохраняет накопленное обучение и статистику поколений.
git clone https://github.com/v0id-core/civilization-sim.git
cd civilization-sim
pip install -r requirements.txt
python main.pyТребуется Python 3.10+.
| Клавиша / Кнопка | Действие |
|---|---|
R |
Новый мир + новое поколение |
Space |
Пауза / Продолжить |
A |
Авто-рестарт, когда все агенты погибнут |
1 / 2 / 3 |
Скорость ×1 / ×2 / ×5 |
Кнопки < > |
Сменить агента в фокусе |
Кнопка EN/RU |
Переключить язык интерфейса |
| Система | Что происходит |
|---|---|
| Выживание | Агенты постоянно тратят еду, воду и энергию, могут болеть и погибать. |
| Социальное поведение | Есть доверие, любовь, сообщения danger / help / food и обмен ресурсами. |
| Размножение | Дети наследуют влияние родительских мозгов и мутировавшие черты. |
| Постройки | Костёр, стена, склад, колодец, ферма, вышка, кузница. |
| Мир | Олень, кролик, волк, медведь, а также дождь, сезоны, температура и смена дня/ночи. |
| ИИ | Рефлексы + DQN, spatial hashing, tile index и A* с кэшем путей. |
main.py - цикл игры, рендер, UI и переключение языка
agent.py - логика агентов, эмоции, отношения, размножение, торговля
brain.py - DQN на чистом numpy и сохранение обучения
config.py - все константы, рецепты и параметры симуляции
world.py - генерация мира, сезоны и тайлы
entities.py - животные и постройки
Made by @v0id-core

