Add health condition list, tick, and save for phase 77.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -11,19 +11,19 @@
|
||||
|
||||
## Задачи
|
||||
|
||||
- [ ] На человеке список медицинских условий: def, тяжесть, прогресс, метаданные старта
|
||||
- [ ] Тик тяжести/стадий на потоке школы; пустой список = здоров
|
||||
- [ ] Сейв вместе с человеком
|
||||
- [ ] Нужды не удалять и не подменять одним «HP»
|
||||
- [ ] Пока можно без ванильных DiseaseDef-вспышек — инфраструктура и тест на искусственное условие
|
||||
- [ ] Детерминизм тика от сида человека и дня
|
||||
- [x] На человеке список медицинских условий: def, тяжесть, прогресс, метаданные старта
|
||||
- [x] Тик тяжести/стадий на потоке школы; пустой список = здоров
|
||||
- [x] Сейв вместе с человеком
|
||||
- [x] Нужды не удалять и не подменять одним «HP»
|
||||
- [x] Пока можно без ванильных DiseaseDef-вспышек — инфраструктура и тест на искусственное условие
|
||||
- [x] Детерминизм тика от сида человека и дня
|
||||
|
||||
## Тесты, без которых фаза не закрыта
|
||||
|
||||
- [ ] Условие с кривой тяжести меняется одинаково при том же сиде
|
||||
- [ ] Сейв восстанавливает список
|
||||
- [ ] Два условия на одном человеке не затирают друг друга
|
||||
- [ ] Нужда голода по-прежнему тикает отдельно
|
||||
- [x] Условие с кривой тяжести меняется одинаково при том же сиде
|
||||
- [x] Сейв восстанавливает список
|
||||
- [x] Два условия на одном человеке не затирают друг друга
|
||||
- [x] Нужда голода по-прежнему тикает отдельно
|
||||
|
||||
## Критерий готовности
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HSchool.People;
|
||||
|
||||
/// <summary>
|
||||
/// One medical condition on a person (hediff-like). Needs stay separate — a disease may
|
||||
/// later modify decay, but hunger is still a need.
|
||||
/// </summary>
|
||||
public sealed class HealthCondition
|
||||
{
|
||||
public required string DefName { get; init; }
|
||||
|
||||
/// <summary>0…1. Stages and effects read this; DiseaseDef curves land in phase 78.</summary>
|
||||
public float Severity { get; set; }
|
||||
|
||||
/// <summary>Immunity / treatment progress 0…1.</summary>
|
||||
public float Progress { get; set; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Source { get; init; }
|
||||
|
||||
public DateTime StartedAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Base severity change per game day before the person+day seed factor.
|
||||
/// Artificial conditions carry this until DiseaseDef owns the curve (phase 78).
|
||||
/// </summary>
|
||||
public float SeverityPerDay { get; init; }
|
||||
|
||||
/// <summary>Base progress change per game day before the person+day seed factor.</summary>
|
||||
public float ProgressPerDay { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Mutates the sparse <see cref="Person.Conditions"/> list and ticks severity deterministically.</summary>
|
||||
public static class HealthConditions
|
||||
{
|
||||
public static void Add(Person person, HealthCondition condition)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(person);
|
||||
ArgumentNullException.ThrowIfNull(condition);
|
||||
|
||||
var list = person.Conditions;
|
||||
if (list is null)
|
||||
{
|
||||
list = [];
|
||||
person.Conditions = list;
|
||||
}
|
||||
|
||||
list.Add(condition);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Advances severity/progress for everyone with conditions. Same
|
||||
/// <paramref name="peopleSeed"/>, person id and <paramref name="dayNumber"/> yield the same curve.
|
||||
/// </summary>
|
||||
public static bool Tick(Person person, int peopleSeed, int dayNumber, double gameMinutes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(person);
|
||||
var list = person.Conditions;
|
||||
if (list is null || list.Count == 0 || gameMinutes <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var daySeed = Seed.Mix(peopleSeed, person.Id, dayNumber, Seed.HealthSalt);
|
||||
var unit = (daySeed & int.MaxValue) / (float)int.MaxValue;
|
||||
var dayFactor = 0.5f + unit;
|
||||
var days = gameMinutes / (24d * 60d);
|
||||
var changed = false;
|
||||
|
||||
foreach (var condition in list)
|
||||
{
|
||||
var severityDelta = (float)(condition.SeverityPerDay * dayFactor * days);
|
||||
var progressDelta = (float)(condition.ProgressPerDay * dayFactor * days);
|
||||
if (severityDelta == 0f && progressDelta == 0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var nextSeverity = Math.Clamp(condition.Severity + severityDelta, 0f, 1f);
|
||||
var nextProgress = Math.Clamp(condition.Progress + progressDelta, 0f, 1f);
|
||||
if (nextSeverity == condition.Severity && nextProgress == condition.Progress)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
condition.Severity = nextSeverity;
|
||||
condition.Progress = nextProgress;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,12 @@ public sealed record Person
|
||||
/// </summary>
|
||||
public List<OffenseRecord>? Offenses { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Active medical conditions. Null when healthy (empty) so people.json stays compact.
|
||||
/// Needs are not replaced by this list.
|
||||
/// </summary>
|
||||
public List<HealthCondition>? Conditions { get; set; }
|
||||
|
||||
public int AgeOn(DateTime asOf) => SchoolYears.AgeYears(BirthDate, asOf);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ public static class Seed
|
||||
public const int OrientationSalt = 13;
|
||||
public const int ConflictSalt = 14;
|
||||
public const int HomeSalt = 15;
|
||||
public const int HealthSalt = 16;
|
||||
|
||||
/// <summary>A stream that belongs to the school rather than to one family.</summary>
|
||||
public static int ForSchool(int schoolSeed, int salt) => Mix(schoolSeed, familyIndex: -1, salt);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using HSchool.People;
|
||||
|
||||
namespace HSchool.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Ticks medical condition severity on the roster. Contagion and DiseaseDef outbreaks are later phases.
|
||||
/// </summary>
|
||||
internal static class HealthConditionSystem
|
||||
{
|
||||
public static bool Apply(School school, double gameMinutes)
|
||||
{
|
||||
if (gameMinutes <= 0 || school.Roster is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var dayNumber = DateOnly.FromDateTime(school.Clock.Time).DayNumber;
|
||||
var changed = false;
|
||||
foreach (var person in school.Roster.People)
|
||||
{
|
||||
changed |= HealthConditions.Tick(person, school.PeopleSeed, dayNumber, gameMinutes);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -348,7 +348,7 @@ public sealed class School : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs one fixed step of the school: calendar, yearly intake, applicant refresh, presence, actions, need decay, then apparel wear.</summary>
|
||||
/// <summary>Runs one fixed step of the school: calendar, yearly intake, applicant refresh, presence, actions, need decay, apparel wear, then health conditions.</summary>
|
||||
/// <returns><see langword="true"/> when the roster, applicant pool or wardrobe changed this step.</returns>
|
||||
public bool Tick(double deltaTime, double gameMinutesPerRealSecond)
|
||||
{
|
||||
@@ -442,6 +442,7 @@ public sealed class School : IDisposable
|
||||
peopleChanged |= AffinitySystem.Apply(this, talked);
|
||||
}
|
||||
|
||||
peopleChanged |= HealthConditionSystem.Apply(this, gameMinutes);
|
||||
peopleChanged |= RosterTalkDirty;
|
||||
RosterTalkDirty = false;
|
||||
return peopleChanged;
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
namespace HSchool.People.Tests;
|
||||
|
||||
public class HealthConditionTests
|
||||
{
|
||||
[Fact]
|
||||
public void SameSeed_YieldsSameSeverityCurve()
|
||||
{
|
||||
var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc);
|
||||
var first = Blank("p1");
|
||||
var second = Blank("p1");
|
||||
HealthConditions.Add(first, Artificial(started, severity: 0.2f));
|
||||
HealthConditions.Add(second, Artificial(started, severity: 0.2f));
|
||||
|
||||
Assert.True(HealthConditions.Tick(first, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60));
|
||||
Assert.True(HealthConditions.Tick(second, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60));
|
||||
|
||||
Assert.Equal(first.Conditions![0].Severity, second.Conditions![0].Severity);
|
||||
Assert.True(first.Conditions[0].Severity > 0.2f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentDaySeed_ChangesTheCurve()
|
||||
{
|
||||
var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc);
|
||||
var a = Blank("p1");
|
||||
var b = Blank("p1");
|
||||
HealthConditions.Add(a, Artificial(started, severity: 0.2f));
|
||||
HealthConditions.Add(b, Artificial(started, severity: 0.2f));
|
||||
|
||||
HealthConditions.Tick(a, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60);
|
||||
HealthConditions.Tick(b, peopleSeed: 7, dayNumber: 101, gameMinutes: 24 * 60);
|
||||
|
||||
Assert.NotEqual(a.Conditions![0].Severity, b.Conditions![0].Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RosterJson_RoundTripsConditions_AndOmitsHealthy()
|
||||
{
|
||||
var roster = Fixtures.Generate(Fixtures.Classrooms(4));
|
||||
var pupil = roster.People.First(person => person.IsStudent && !person.IsParent);
|
||||
var started = new DateTime(2012, 4, 3, 9, 0, 0, DateTimeKind.Utc);
|
||||
HealthConditions.Add(pupil, Artificial(started, severity: 0.35f, defName: "TestCold"));
|
||||
HealthConditions.Add(
|
||||
pupil,
|
||||
new HealthCondition
|
||||
{
|
||||
DefName = "TestStomach",
|
||||
Severity = 0.15f,
|
||||
Progress = 0.05f,
|
||||
Source = "idiopathic",
|
||||
StartedAt = started.AddHours(1),
|
||||
SeverityPerDay = 0.05f,
|
||||
ProgressPerDay = 0.02f,
|
||||
});
|
||||
|
||||
var json = RosterJson.Serialize(RosterDocument.From(1, roster));
|
||||
Assert.Contains("\"conditions\"", json, StringComparison.Ordinal);
|
||||
Assert.Contains("\"defName\": \"TestCold\"", json, StringComparison.Ordinal);
|
||||
Assert.Contains("\"defName\": \"TestStomach\"", json, StringComparison.Ordinal);
|
||||
|
||||
var healthy = roster.People.First(person => person.Conditions is null || person.Conditions.Count == 0);
|
||||
var healthySlice = PersonJsonSlice(json, healthy.Id);
|
||||
Assert.DoesNotContain("\"conditions\"", healthySlice, StringComparison.Ordinal);
|
||||
|
||||
var loaded = RosterJson.Parse(json).ToRoster();
|
||||
var loadedPupil = loaded.People.First(person => person.Id.Equals(pupil.Id, StringComparison.Ordinal));
|
||||
Assert.NotNull(loadedPupil.Conditions);
|
||||
Assert.Equal(2, loadedPupil.Conditions!.Count);
|
||||
Assert.Equal("TestCold", loadedPupil.Conditions[0].DefName);
|
||||
Assert.Equal(0.35f, loadedPupil.Conditions[0].Severity);
|
||||
Assert.Equal("cold", loadedPupil.Conditions[0].Source);
|
||||
Assert.Equal(started, loadedPupil.Conditions[0].StartedAt);
|
||||
Assert.Equal("TestStomach", loadedPupil.Conditions[1].DefName);
|
||||
Assert.Equal(0.15f, loadedPupil.Conditions[1].Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoConditions_DoNotOverwriteEachOther()
|
||||
{
|
||||
var person = Blank("p1");
|
||||
var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc);
|
||||
HealthConditions.Add(person, Artificial(started, severity: 0.4f, defName: "A"));
|
||||
HealthConditions.Add(person, Artificial(started, severity: 0.1f, defName: "B"));
|
||||
|
||||
Assert.Equal(2, person.Conditions!.Count);
|
||||
Assert.Equal("A", person.Conditions[0].DefName);
|
||||
Assert.Equal(0.4f, person.Conditions[0].Severity);
|
||||
Assert.Equal("B", person.Conditions[1].DefName);
|
||||
Assert.Equal(0.1f, person.Conditions[1].Severity);
|
||||
|
||||
HealthConditions.Tick(person, peopleSeed: 3, dayNumber: 50, gameMinutes: 60);
|
||||
Assert.Equal(2, person.Conditions.Count);
|
||||
Assert.Equal("A", person.Conditions[0].DefName);
|
||||
Assert.Equal("B", person.Conditions[1].DefName);
|
||||
Assert.True(person.Conditions[0].Severity > 0.4f);
|
||||
Assert.True(person.Conditions[1].Severity > 0.1f);
|
||||
}
|
||||
|
||||
private static HealthCondition Artificial(
|
||||
DateTime started,
|
||||
float severity,
|
||||
string defName = "TestCold") =>
|
||||
new()
|
||||
{
|
||||
DefName = defName,
|
||||
Severity = severity,
|
||||
Progress = 0f,
|
||||
Source = "cold",
|
||||
StartedAt = DateTime.SpecifyKind(started, DateTimeKind.Utc),
|
||||
SeverityPerDay = 0.2f,
|
||||
ProgressPerDay = 0.1f,
|
||||
};
|
||||
|
||||
private static string PersonJsonSlice(string json, string personId)
|
||||
{
|
||||
var marker = $"\"id\": \"{personId}\"";
|
||||
var start = json.IndexOf(marker, StringComparison.Ordinal);
|
||||
Assert.True(start >= 0);
|
||||
var end = json.IndexOf("},", start, StringComparison.Ordinal);
|
||||
if (end < 0)
|
||||
{
|
||||
end = json.Length;
|
||||
}
|
||||
|
||||
return json[start..end];
|
||||
}
|
||||
|
||||
private static Person Blank(string id)
|
||||
{
|
||||
var cases = new CaseTable
|
||||
{
|
||||
Nom = id,
|
||||
Gen = id,
|
||||
Dat = id,
|
||||
Acc = id,
|
||||
Ins = id,
|
||||
Pre = id,
|
||||
};
|
||||
return new Person
|
||||
{
|
||||
Id = id,
|
||||
FamilyId = "f",
|
||||
Female = false,
|
||||
BirthDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
Name = new PersonName(id, id, id, cases, cases, cases),
|
||||
IsStudent = true,
|
||||
IsStaff = false,
|
||||
IsParent = false,
|
||||
Numbers = new Dictionary<string, int>(StringComparer.Ordinal),
|
||||
Choices = new Dictionary<string, string>(StringComparer.Ordinal),
|
||||
Skills = new Dictionary<string, int>(StringComparer.Ordinal),
|
||||
Traits = [],
|
||||
Needs = new Dictionary<string, float>(StringComparer.Ordinal),
|
||||
Opinions = new Dictionary<string, int>(StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using Arch.Core;
|
||||
using HSchool.Ai;
|
||||
using HSchool.Content;
|
||||
using HSchool.People;
|
||||
using HSchool.Schedule;
|
||||
|
||||
namespace HSchool.Simulation.Tests;
|
||||
|
||||
public class HealthConditionSystemTests
|
||||
{
|
||||
private static readonly DateTime TuesdayLesson = new(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void SameSeed_SchoolTick_YieldsSameSeverity()
|
||||
{
|
||||
using var first = OpenStaffed();
|
||||
using var second = OpenStaffed();
|
||||
var pupilId = first.Roster!.People.First(person => person.IsStudent && !person.IsParent).Id;
|
||||
HangArtificial(first, pupilId, severity: 0.25f);
|
||||
HangArtificial(second, pupilId, severity: 0.25f);
|
||||
|
||||
TickMinutes(first, 60);
|
||||
TickMinutes(second, 60);
|
||||
|
||||
var a = first.Roster.People.First(person => person.Id == pupilId).Conditions![0].Severity;
|
||||
var b = second.Roster!.People.First(person => person.Id == pupilId).Conditions![0].Severity;
|
||||
Assert.Equal(a, b);
|
||||
Assert.True(a > 0.25f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hunger_StillDecaysWhileConditionTicks()
|
||||
{
|
||||
using var school = OpenStaffed();
|
||||
AdvanceTo(school, TuesdayLesson);
|
||||
var onCampus = school.CapturePresence().First(row => row.NodeId is not null);
|
||||
var pupil = school.Roster!.People.First(person => person.Id.Equals(onCampus.PersonId, StringComparison.Ordinal));
|
||||
HangArtificial(school, pupil.Id, severity: 0.2f);
|
||||
|
||||
var hungerBefore = ReadHunger(school, pupil.Id);
|
||||
var severityBefore = pupil.Conditions![0].Severity;
|
||||
|
||||
TickMinutes(school, 60);
|
||||
|
||||
var hungerAfter = ReadHunger(school, pupil.Id);
|
||||
var severityAfter = pupil.Conditions[0].Severity;
|
||||
var catalogHunger = school.Catalog!.Needs["Hunger"];
|
||||
Assert.True(hungerAfter < hungerBefore);
|
||||
Assert.Equal(hungerBefore - catalogHunger.DecayPerHour, hungerAfter, precision: 3);
|
||||
Assert.True(severityAfter > severityBefore);
|
||||
}
|
||||
|
||||
private static void HangArtificial(School school, string personId, float severity)
|
||||
{
|
||||
var person = school.Roster!.People.First(row => row.Id.Equals(personId, StringComparison.Ordinal));
|
||||
HealthConditions.Add(
|
||||
person,
|
||||
new HealthCondition
|
||||
{
|
||||
DefName = "TestCold",
|
||||
Severity = severity,
|
||||
Progress = 0f,
|
||||
Source = "dev",
|
||||
StartedAt = school.Clock.Time,
|
||||
SeverityPerDay = 0.5f,
|
||||
ProgressPerDay = 0.1f,
|
||||
});
|
||||
}
|
||||
|
||||
private static float ReadHunger(School school, string personId)
|
||||
{
|
||||
var value = float.NaN;
|
||||
var query = new QueryDescription().WithAll<PersonIdentity, PersonNeeds>();
|
||||
school.World.Query(
|
||||
in query,
|
||||
(ref PersonIdentity identity, ref PersonNeeds needs) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
value = needs.Values["Hunger"];
|
||||
}
|
||||
});
|
||||
Assert.False(float.IsNaN(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void TickMinutes(School school, int minutes)
|
||||
{
|
||||
for (var i = 0; i < minutes; i++)
|
||||
{
|
||||
school.Tick(0.2d, 5d);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AdvanceTo(School school, DateTime until)
|
||||
{
|
||||
while (school.Clock.Time < until)
|
||||
{
|
||||
school.Tick(0.2d, 5d);
|
||||
}
|
||||
}
|
||||
|
||||
private static School OpenStaffed()
|
||||
{
|
||||
var start = new DateTime(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
|
||||
var (catalog, map) = Vanilla();
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", start);
|
||||
var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", start);
|
||||
var schoolClass = roster.Classes.First(row =>
|
||||
row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104");
|
||||
var school = School.Create(1, "Здоровье", start, catalog, map);
|
||||
school.InstallPeople(roster, seed: 1, "Russia", pool);
|
||||
school.SetTimetable(new Timetable(
|
||||
[
|
||||
new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1),
|
||||
new LessonPlacement(schoolClass.Id, "PhysicalEducation", "t2", "gym-hall", Day: 1, Period: 2),
|
||||
],
|
||||
[]));
|
||||
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
return school;
|
||||
}
|
||||
|
||||
private static (DefCatalog Catalog, MapLayout Map) Vanilla()
|
||||
{
|
||||
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
|
||||
var documents = new List<ContentDocument>();
|
||||
foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase)
|
||||
&& !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var relative = Path.GetRelativePath(root, path).Replace('\\', '/');
|
||||
documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path)));
|
||||
}
|
||||
|
||||
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
|
||||
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
|
||||
Assert.NotNull(map);
|
||||
return (catalog, map);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user