Skip to content

v0id-core/civilization-sim

Repository files navigation

🌍 CivSim — Civilization Agent Simulation / Симуляция цивилизации

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.

At a Glance

  • 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.save keeps learned progress alive across restarts.

Screenshots

Main CivSim world view with multiple agents, weather, season, population, and controls

Main simulation view with live population, season, weather, speed controls, and world activity.

Focused agent panel showing current action, mood, relationship, brain status, and UI controls

Focused-agent view with current action, mood, relationship status, generation info, and quick controls.

Contents

🇬🇧 English

What is CivSim?

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.

Why It Stands Out

  • 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.

Quick Start

git clone https://github.com/v0id-core/civilization-sim.git
cd civilization-sim
pip install -r requirements.txt
python main.py

Requirements:

  • Python 3.10+
  • pygame>=2.5.0
  • numpy>=1.24.0

Gameplay Highlights

  • 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.

Simulation Systems

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.

AI and Technical Overview

  • 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.

Controls and UI

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.

Project Structure

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

Persistence

  • brain.save stores 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.save resets 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

About

Real-time civilization simulation with autonomous agents, emotions, DQN learning, reproduction, crafting, and emergent behavior

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages