Add life rules and implement tests for civilization and life states

- Introduced a new file `life_rules.txt` to define life progression and degradation rules.
- Created `test_civilization_state.gd` to validate the functionality of civilization rules and ethics.
- Added `test_life.gd` to test life evolution, including initialization, batch processing, and state validation.
- Implemented `civilization_state.gd` to manage civilization ethics and space civilization detachment logic.
- Ensured all tests check for expected outcomes and validate state integrity after operations.
This commit is contained in:
Kirill
2026-09-15 23:05:05 +03:00
parent cc2700d507
commit 5f3875bc14
16 changed files with 673 additions and 25 deletions
+14
View File
@@ -46,3 +46,17 @@ godot --headless --path Owniverse.GI --script res://tests/test_descriptions.gd
`%valueN%` заменяется значением переменной, имя которой записано в поле `valueN` этой строки. Поддерживаются `amount`, `colored costs`, `lifespan`, `voids`, `he / h`, `metallicity`, показатели энергии, плотности и скорости времени. `amount1`–`amount4` сил пока отображаются как `—`; неизвестные непустые обозначения тоже дают `—`, пустые поля — пустую строку. `[p]` превращается в разделение абзацев, цветовые BBCode-теги сохраняются.
Доступные требования зелёные, недоступные красные. Для объектов со связанными экземплярами выводится доступное количество и серым общее; для планет — общее количество. Скорость изменения вычисляется по реальному времени и обновляется раз в 0,25 секунды. Доли He/H вычисляются из текущих свободных запасов; при пустой смеси показывается `—`. Металличность и плотность используют расчёт среды GI. Счётчики исходной материи и этики Unity в текущей GI отсутствуют и здесь не добавляются.
## Первичная жизнь
```sh
godot --headless --path Owniverse.GI --script res://tests/test_life.gd
```
Проверяются абиогенез, деградация, повторные попытки без создания дополнительных планет, появление C0.0 на прежней звезде, остатки вероятностей, сохранение/продолжение, однократная инициализация старых планет и отсутствие воскрешения после бластов.
Проверка загрузки этических правил, миграции распределений и отделения космических цивилизаций:
```sh
godot --headless --path Owniverse.GI --script res://tests/test_civilization_state.gd
```
+75
View File
@@ -0,0 +1,75 @@
extends SceneTree
const Clock = preload("res://world/owniverse/simulation_time.gd")
var checks: int = 0
var failures: int = 0
func _initialize() -> void:
call_deferred("run")
func check(condition: bool, message: String) -> void:
checks += 1
if not condition:
failures += 1
push_error(message)
func fixture():
var world = load("res://world/owniverse/owniverse.gd").new()
var global: Node = root.get_node("Global")
for id in global.OwniverseEntities:
var entity = load("res://world/owniverse/owniverse_entity.gd").new(global.OwniverseEntities[id])
world.entities[id] = entity
world.state.amount[id] = 0.0
world.state.stats.total_amount[id] = 0.0
if entity.group_as != "":
world.state.amount[entity.group_as] = 0.0
world.state.stats.total_amount[entity.group_as] = 0.0
world.entities["N"].life_product = {}
world.entities["N"].product_per_year_type = "H"
world.entities["N"].product_per_year_amount = 10.0
world.entities["N"].auto = 0.0
world.state.amount.N = 1.0
return world
func dispose(world) -> void:
for entity in world.entities.values():
entity.free()
world.free()
func run() -> void:
var world = fixture()
var global: Node = root.get_node("Global")
check(global.CivilizationRules.size() == 43, "Load all ethical civilization stages")
for row: Dictionary in global.CivilizationRules.values():
check(row.ethics.size() == 6, "Every ethical stage has six rules")
world.state.amount["C0.2"] = 8.0
world.state.binds.RD = {"C2.0": 12.0, "C1.9": 3.0}
world.initialize_life_batches()
check(world.state.amount["C2.0"] == 12.0 and world.state.binds.RD["C2.0"] == 0.0, "Old space civilizations detach without loss")
check(world.state.binds.RD["C1.9"] == 3.0, "Planetary civilizations retain their host")
check(world.state.ethics["C0.2"] == {"m": 2.0, "l": 2.0, "w": 1.0, "d": 1.0, "c": 1.0, "b": 1.0}, "Migration uses equal ethics and deterministic remainder")
check(world.state.ethics["C2.0"].values().all(func(n): return n == 2.0), "Bound civilization ethics count physical population")
var before: Dictionary = world.state.duplicate(true)
world.initialize_life_batches()
check(world.state == before, "Repeated initialization preserves ethics")
world.state.ethics["C0.2"] = {"m": 8.0, "l": 0.0, "w": 0.0, "d": 0.0, "c": 0.0, "b": 0.0}
world.initialize_life_batches()
check(world.state.ethics["C0.2"].m == 8.0, "Existing unequal distribution is retained")
world.state.amount["C0.2"] = 3.0
world.initialize_life_batches()
check(world.state.ethics["C0.2"].m == 3.0, "Losses reduce ethics without inventing population")
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Ethics state validates")
var restored = fixture()
restored.state = bytes_to_var(var_to_bytes(world.state))
restored.initialize_life_batches()
check(restored.state == world.state, "Save roundtrip preserves ethics and ownership")
dispose(restored)
dispose(world)
world = fixture()
world.entities["C1.9"].output_and = {"C2.0": 1.0}
world.state.binds.RD = {"C1.9": 10.0}
world.state.batches["C1.9"] = [{"amount": 10.0, "start_year": 1.0, "end_year": 1.0}]
world._evolve_batches(world.state, 1.0)
check(world.state.amount["C2.0"] == 10.0 and world.state.binds.RD.get("C2.0", 0.0) == 0.0, "Space successor does not inherit planetary binding")
dispose(world)
print("Civilization state: %d checks, %d failures" % [checks, failures])
quit(0 if failures == 0 else 1)
+1
View File
@@ -0,0 +1 @@
uid://nvgiilyqitw
+124
View File
@@ -0,0 +1,124 @@
extends SceneTree
const Clock = preload("res://world/owniverse/simulation_time.gd")
var checks: int = 0
var failures: int = 0
func _initialize() -> void:
call_deferred("run")
func check(condition: bool, message: String) -> void:
checks += 1
if not condition:
failures += 1
push_error(message)
func fixture():
var world = load("res://world/owniverse/owniverse.gd").new()
var global: Node = root.get_node("Global")
for id in global.OwniverseEntities:
var entity = load("res://world/owniverse/owniverse_entity.gd").new(global.OwniverseEntities[id])
world.entities[id] = entity
world.state.amount[id] = 0.0
world.state.stats.total_amount[id] = 0.0
if entity.group_as != "":
world.state.amount[entity.group_as] = 0.0
world.state.stats.total_amount[entity.group_as] = 0.0
world.entities["N"].life_product = {}
world.entities["N"].product_per_year_type = "H"
world.entities["N"].product_per_year_amount = 10.0
world.entities["N"].auto = 0.0
world.state.amount.N = 1.0
return world
func dispose(world) -> void:
for entity in world.entities.values():
entity.free()
world.free()
func run() -> void:
var world = fixture()
world.state.amount.N = 0.0
world.state.amount.HP = 40000.0
world.initialize_life_batches()
check(world.state.batches.HP.size() == 1, "Old HP receives life cohort")
check(world.state.batches.HP[0].start_year == 5e6, "HP uses source span")
var before: Dictionary = world.state.duplicate(true)
world.initialize_life_batches()
check(world.state == before, "Initialization is idempotent")
world._evolve_batches(world.state, 5e6 + 5e6 / 40.0)
check(world.state.amount.EON1 == 10.0, "HP abiogenesis follows source probability")
check(world.state.amount.RP == 100.0, "HP degradation produces RP")
check(world.state.amount.HP == 39890.0, "Unchanged planets retry, not disappear")
check(world.state.stats.total_amount.HP == 0.0, "Retry does not inflate creation statistics")
check(world.state.batches.HP.size() > 0, "Survivors get next attempt")
var physical: Dictionary = world._physical_amounts(world.state)
check(physical.HP + physical.EON1 + physical.RP == 40000.0, "Life conserves planets")
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Life save validates")
var restored = fixture()
restored.state = bytes_to_var(var_to_bytes(world.state))
world._evolve_batches(world.state, 11e6)
restored._evolve_batches(restored.state, 11e6)
check(world.state == restored.state, "Life continuation preserves cohorts and carries")
dispose(restored)
dispose(world)
world = fixture()
world.state.amount.RD = 1.0
world.state.binds.RD = {"EON5": 40000.0}
world.initialize_life_batches()
world._evolve_batches(world.state, 5e5 + 5e5 / 40.0)
check(world.state.binds.RD["C0.0"] == 10.0, "Intelligence emerges at the same host star")
check(world.state.amount["C0.0"] == 0.0, "Life transition keeps planet bound")
check(world.state.batches.has("C0.0"), "New C0.0 starts civilization evolution")
dispose(world)
world = fixture()
var progress: float = 0.0
var degraded: float = 0.0
var valid_outcomes: bool = true
for i in 4001:
var products: Dictionary = world._life_products(world.state, world.entities.HP, 1.0)
var total: float = 0.0
for value in products.values():
total += value
valid_outcomes = valid_outcomes and value >= 0.0 and value == floorf(value)
valid_outcomes = valid_outcomes and total == 1.0
progress += products.get("EON1", 0.0)
degraded += products.get("RP", 0.0)
check(valid_outcomes, "Every single-planet attempt has whole outcomes and conserves population")
check(progress == 1.0 and degraded == 10.0, "Rare outcomes accumulate deterministically")
dispose(world)
world = fixture()
world.state.time = {"datetime": 123.4, "year": 123.4}
world.state.binds.RD = {"HP": 2.0}
world.initialize_life_batches()
check(world.state.batches.HP[0].created_from == 123.4, "Old bound worlds begin life at load time")
world._destroy_planets(world.state, "RD", 1.0, 1)
world._evolve_batches(world.state, 1e7)
check(world._physical_amounts(world.state).HP == 0.0 and world.state.binds.RD.RP == 2.0, "Destroyed life does not resurrect from cohort")
dispose(world)
world = fixture()
world.state.time = {"datetime": 123.4, "year": 123.4}
world.state.life_version = 1
world.state.amount["C0.0"] = 40000.0
world.initialize_life_batches()
check(world.state.life_version == 2 and world.state.batches["C0.0"][0].created_from == 123.4, "Previous life saves receive missing civilization cohorts")
before = world.state.duplicate(true)
world.initialize_life_batches()
check(world.state == before, "Second life migration is idempotent")
world._evolve_batches(world.state, 2173.4)
check(world.state.amount["C0.1"] == 700.0 and world.state.amount.EON5 == 1000.0, "C0.0 progresses and degrades by Unity rates")
check(world.state.amount["C0.0"] == 38300.0, "C0.0 remainder stays alive")
dispose(world)
world = fixture()
world.state.amount.RD = 1.0
world.state.binds.RD = {"C0.1": 40000.0}
world.initialize_life_batches()
world._evolve_batches(world.state, 2050.0)
check(world.state.binds.RD["C0.2"] == 700.0, "C0.1 reaches ethical civilization without losing host")
check(world.state.binds.RD["C0.0"] == 1000.0, "C0.1 degradation follows Unity")
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Extended life save validates")
dispose(world)
print("Life: %d checks, %d failures" % [checks, failures])
quit(0 if failures == 0 else 1)
+1
View File
@@ -0,0 +1 @@
uid://dghmnvnl7ks1b