diff --git a/docs/phases/15-fallout/82-sick-staff-lessons.md b/docs/phases/15-fallout/82-sick-staff-lessons.md index b88a25b..ee0be48 100644 --- a/docs/phases/15-fallout/82-sick-staff-lessons.md +++ b/docs/phases/15-fallout/82-sick-staff-lessons.md @@ -12,18 +12,18 @@ ## Задачи -- [ ] Учитель с тяжёлой стадией / «остаться дома» не появляется на уроке (явная стыковка с 14) -- [ ] Урок без учителя → рост/оценка по уже принятым правилам 48/73 -- [ ] Лог и/или `EventDef` info «без учителя» / сорванный урок — без спама каждый тик -- [ ] Больничный лист и перерасчёт зарплаты не моделируем -- [ ] Детерминизм: тот же сид болезни → тот же приход/неприход +- [x] Учитель с тяжёлой стадией / «остаться дома» не появляется на уроке (явная стыковка с 14) +- [x] Урок без учителя → рост/оценка по уже принятым правилам 48/73 +- [x] Лог и/или `EventDef` info «без учителя» / сорванный урок — без спама каждый тик +- [x] Больничный лист и перерасчёт зарплаты не моделируем +- [x] Детерминизм: тот же сид болезни → тот же приход/неприход ## Тесты, без которых фаза не закрыта -- [ ] Больной учитель вне школы → у учеников нет роста «как с учителем в кабинете» -- [ ] Здоровый контроль при тех же слотах растёт -- [ ] Notice/лог не чаще порога -- [ ] Явка учеников при сорванном уроке не помечается как их прогул ошибочно +- [x] Больной учитель вне школы → у учеников нет роста «как с учителем в кабинете» +- [x] Здоровый контроль при тех же слотах растёт +- [x] Notice/лог не чаще порога +- [x] Явка учеников при сорванном уроке не помечается как их прогул ошибочно ## Критерий готовности diff --git a/docs/protocol.md b/docs/protocol.md index b23af74..c24f869 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -516,6 +516,8 @@ phase 34 appends it), `apparel-changed` (dressing, when phase 35 appends it), `lesson-cold` (warmth below the behaviour threshold during a lesson that otherwise taught), `lesson-no-textbook` (the bag had no textbook for that lesson; locker and home do not count). `thingDef` is the action, apparel or subject def the caption was built from. +When the assigned teacher stays home sick, the school also raises a one-shot info notice +`LessonCancelled` (`trigger` `lessonNoTeacher`) — once per class slot, not every tick. ```json { diff --git a/src/HSchool.Content/EventDefValidator.cs b/src/HSchool.Content/EventDefValidator.cs index de59416..8dc04dc 100644 --- a/src/HSchool.Content/EventDefValidator.cs +++ b/src/HSchool.Content/EventDefValidator.cs @@ -17,6 +17,7 @@ internal static class EventDefValidator EventTriggers.DirectorSummon, EventTriggers.ParentMeeting, EventTriggers.DiseaseOutbreak, + EventTriggers.LessonNoTeacher, }; private static readonly HashSet Actions = new(StringComparer.Ordinal) diff --git a/src/HSchool.Content/EventDefs.cs b/src/HSchool.Content/EventDefs.cs index bf97aa4..08b26ce 100644 --- a/src/HSchool.Content/EventDefs.cs +++ b/src/HSchool.Content/EventDefs.cs @@ -15,6 +15,7 @@ public static class EventTriggers public const string DirectorSummon = "directorSummon"; public const string ParentMeeting = "parentMeeting"; public const string DiseaseOutbreak = "diseaseOutbreak"; + public const string LessonNoTeacher = "lessonNoTeacher"; } public static class EventActions diff --git a/src/HSchool.Server/mods/core/defs/events/notices.jsonc b/src/HSchool.Server/mods/core/defs/events/notices.jsonc index c81e154..8fe7849 100644 --- a/src/HSchool.Server/mods/core/defs/events/notices.jsonc +++ b/src/HSchool.Server/mods/core/defs/events/notices.jsonc @@ -47,4 +47,12 @@ "trigger": "diseaseOutbreak", "action": "none", }, + { + "defName": "LessonCancelled", + "severity": "info", + "pause": false, + "ttlMs": 8000, + "trigger": "lessonNoTeacher", + "action": "none", + }, ] diff --git a/src/HSchool.Server/mods/core/localizations/en.jsonc b/src/HSchool.Server/mods/core/localizations/en.jsonc index 39377a9..848897a 100644 --- a/src/HSchool.Server/mods/core/localizations/en.jsonc +++ b/src/HSchool.Server/mods/core/localizations/en.jsonc @@ -237,6 +237,7 @@ "DirectorSummoned": "A pupil was summoned to the principal", "ParentMeeting": "A parent meeting is under way", "DiseaseOutbreak": "An illness is spreading at school", + "LessonCancelled": "Lesson without a teacher", "GoingToPrincipal": "going to the principal", "WaitForPrincipal": "waiting at the principal's office", "GoingToParentMeeting": "going to a parent meeting", diff --git a/src/HSchool.Server/mods/core/localizations/ru.jsonc b/src/HSchool.Server/mods/core/localizations/ru.jsonc index 343578b..99939fa 100644 --- a/src/HSchool.Server/mods/core/localizations/ru.jsonc +++ b/src/HSchool.Server/mods/core/localizations/ru.jsonc @@ -237,6 +237,7 @@ "DirectorSummoned": "Ученика вызвали к директору", "ParentMeeting": "Идёт родительское собрание", "DiseaseOutbreak": "В школе распространяется болезнь", + "LessonCancelled": "Урок без учителя", "GoingToPrincipal": "идёт к директору", "WaitForPrincipal": "ждёт у кабинета директора", "GoingToParentMeeting": "идёт на собрание", diff --git a/src/HSchool.Simulation/LessonLearningSystem.cs b/src/HSchool.Simulation/LessonLearningSystem.cs index bcde170..58dd220 100644 --- a/src/HSchool.Simulation/LessonLearningSystem.cs +++ b/src/HSchool.Simulation/LessonLearningSystem.cs @@ -54,6 +54,8 @@ internal static class LessonLearningSystem teacherSkills[identity.Id] = personSkills.Values; }); + RaiseSickTeacherLessons(school, places, weekday, slot.Index); + world.Query( in People, (ref PersonIdentity identity, ref PersonSkills skills, ref PersonTraits traits, ref PersonNeeds needs, ref PersonRoles roles, ref Presence presence, ref PersonActivity activity) => @@ -208,6 +210,56 @@ internal static class LessonLearningSystem && teacher.NodeId is not null && teacher.NodeId.Equals(roomId, StringComparison.Ordinal); + /// + /// One school toast per class slot when the assigned teacher stayed home sick (slice 15). + /// Uses the morning day plan — re-rolling at + /// lesson time can flip after severity ticks. Toilet trips keep the per-pupil log only. + /// + private static void RaiseSickTeacherLessons( + School school, + Dictionary places, + int weekday, + int period) + { + if (school.Timetable is null || school.Roster is null || school.Catalog is null) + { + return; + } + + foreach (var lesson in school.Timetable.Lessons) + { + if (lesson.Day != weekday || lesson.Period != period) + { + continue; + } + + if (TeacherStandingIn(places, lesson.TeacherId, lesson.RoomId)) + { + continue; + } + + if (!school.Plans.TryGetValue(lesson.TeacherId, out var plan) || plan.Comes) + { + continue; + } + + var teacher = school.Roster.People.FirstOrDefault(row => + row.Id.Equals(lesson.TeacherId, StringComparison.Ordinal)); + if (teacher is null + || DiseaseEffects.StayHomeChance(teacher, school.Catalog, school.Clock.Time) <= 0f) + { + continue; + } + + if (!school.TryClaimLessonNoTeacherEvent(lesson.ClassId, school.Clock.Time.Date, lesson.Period)) + { + continue; + } + + school.RaiseWorldEvent(new WorldEvent(EventTriggers.LessonNoTeacher, lesson.TeacherId)); + } + } + private static LessonPlacement? CurrentLesson(School school, Person person, int weekday, int period) { foreach (var lesson in Duty.LessonsToday(person, ClassOf(school, person), school.Timetable, weekday)) diff --git a/src/HSchool.Simulation/School.cs b/src/HSchool.Simulation/School.cs index 6d82cdd..6e6dc36 100644 --- a/src/HSchool.Simulation/School.cs +++ b/src/HSchool.Simulation/School.cs @@ -19,6 +19,7 @@ public sealed class School : IDisposable private readonly List _dayLog = []; private readonly HashSet _lessonLogOnce = new(StringComparer.Ordinal); private readonly HashSet _lessonMarkOnce = new(StringComparer.Ordinal); + private readonly HashSet _lessonNoTeacherEventOnce = new(StringComparer.Ordinal); private readonly List _worldEvents = []; internal School(int id, string name, DateTime startDate, DefCatalog? catalog, MapLayout? map) @@ -176,6 +177,7 @@ public sealed class School : IDisposable LoggedActivity.Clear(); _lessonLogOnce.Clear(); _lessonMarkOnce.Clear(); + _lessonNoTeacherEventOnce.Clear(); LastAttendanceSlot = null; } @@ -205,6 +207,15 @@ public sealed class School : IDisposable return _lessonMarkOnce.Add(key); } + /// + /// One school toast per class lesson slot when the assigned teacher stays home sick. + /// + internal bool TryClaimLessonNoTeacherEvent(string classId, DateTime day, int period) + { + var key = string.Concat(classId, "\0", day.ToString("yyyy-MM-dd"), "\0", period.ToString()); + return _lessonNoTeacherEventOnce.Add(key); + } + public void QueueDecision(string personId) { ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/tests/HSchool.Content.Tests/DiseaseDefTests.cs b/tests/HSchool.Content.Tests/DiseaseDefTests.cs index fdad46d..161f531 100644 --- a/tests/HSchool.Content.Tests/DiseaseDefTests.cs +++ b/tests/HSchool.Content.Tests/DiseaseDefTests.cs @@ -35,6 +35,14 @@ public class DiseaseDefTests Assert.True(catalog.Events.ContainsKey("DiseaseOutbreak")); Assert.Equal(EventTriggers.DiseaseOutbreak, catalog.Events["DiseaseOutbreak"].Trigger); Assert.Equal("В школе распространяется болезнь", catalog.Label("ru", catalog.Events["DiseaseOutbreak"])); + + Assert.True(catalog.Events.ContainsKey("LessonCancelled")); + Assert.Equal(EventTriggers.LessonNoTeacher, catalog.Events["LessonCancelled"].Trigger); + Assert.Equal(EventSeverities.Info, catalog.Events["LessonCancelled"].Severity); + Assert.False(catalog.Events["LessonCancelled"].Pause); + Assert.Equal(8000, catalog.Events["LessonCancelled"].TtlMs); + Assert.Equal("Урок без учителя", catalog.Label("ru", catalog.Events["LessonCancelled"])); + Assert.Equal("Lesson without a teacher", catalog.Label("en", catalog.Events["LessonCancelled"])); } [Fact] diff --git a/tests/HSchool.Content.Tests/EventDefTests.cs b/tests/HSchool.Content.Tests/EventDefTests.cs index a28ed73..848875d 100644 --- a/tests/HSchool.Content.Tests/EventDefTests.cs +++ b/tests/HSchool.Content.Tests/EventDefTests.cs @@ -42,6 +42,10 @@ public class EventDefTests Assert.Equal(EventActions.None, catalog.Events["DirectorSummoned"].Action); Assert.Equal("Ученика вызвали к директору", catalog.Label("ru", catalog.Events["DirectorSummoned"])); Assert.Equal("A pupil was summoned to the principal", catalog.Label("en", catalog.Events["DirectorSummoned"])); + + Assert.True(catalog.Events.ContainsKey("LessonCancelled")); + Assert.Equal(EventTriggers.LessonNoTeacher, catalog.Events["LessonCancelled"].Trigger); + Assert.Equal("Урок без учителя", catalog.Label("ru", catalog.Events["LessonCancelled"])); } [Fact] diff --git a/tests/HSchool.Simulation.Tests/SickStaffLessonTests.cs b/tests/HSchool.Simulation.Tests/SickStaffLessonTests.cs new file mode 100644 index 0000000..71dd125 --- /dev/null +++ b/tests/HSchool.Simulation.Tests/SickStaffLessonTests.cs @@ -0,0 +1,268 @@ +using Arch.Core; +using HSchool.Ai; +using HSchool.Content; +using HSchool.People; +using HSchool.Schedule; + +namespace HSchool.Simulation.Tests; + +public class SickStaffLessonTests +{ + private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc); + private static readonly DateTime LessonStart = new(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc); + + [Fact] + public void SickTeacherOffCampus_PupilsDoNotGainLikeWithTeacher() + { + var (sickSchool, room, pupilId, teacherId) = StaffedMath(); + using (sickSchool) + { + InfectHeavyFlu(sickSchool, teacherId); + var stayDay = TuesdayWithStayHome(sickSchool, teacherId); + RebuildDayAt(sickSchool, stayDay); + AdvanceTo(sickSchool, stayDay.Date.Add(LessonStart.TimeOfDay)); + Assert.False(IsOnCampus(sickSchool, teacherId)); + SetPlace(sickSchool, pupilId, room); + var before = SkillOf(sickSchool, pupilId, "Mathematics"); + + LessonLearningSystem.Apply(sickSchool, 45); + + Assert.Equal(before, SkillOf(sickSchool, pupilId, "Mathematics")); + Assert.Equal(2, MarkOf(sickSchool, pupilId)!.Value); + } + + var (healthySchool, healthyRoom, healthyPupil, healthyTeacher) = StaffedMath(); + using (healthySchool) + { + AdvanceTo(healthySchool, LessonStart); + SetPlace(healthySchool, healthyPupil, healthyRoom); + SetPlace(healthySchool, healthyTeacher, healthyRoom); + var before = SkillOf(healthySchool, healthyPupil, "Mathematics"); + + LessonLearningSystem.Apply(healthySchool, 45); + + Assert.True(SkillOf(healthySchool, healthyPupil, "Mathematics") > before); + } + } + + [Fact] + public void SickTeacher_NoticeAndLog_AtMostOncePerSlot() + { + var (school, room, pupilId, teacherId) = StaffedMath(); + using (school) + { + InfectHeavyFlu(school, teacherId); + var stayDay = TuesdayWithStayHome(school, teacherId); + RebuildDayAt(school, stayDay); + // Jump — do not AdvanceTo through the lesson, or Tick raises the event and claims it. + school.Clock.JumpTo(DateTime.SpecifyKind(stayDay.Date.Add(LessonStart.TimeOfDay), DateTimeKind.Utc)); + SetPlace(school, pupilId, room); + SetPlace(school, teacherId, null); + school.DrainWorldEvents(); + + Assert.True(school.Plans.TryGetValue(teacherId, out var plan) && !plan.Comes); + + LessonLearningSystem.Apply(school, 5); + LessonLearningSystem.Apply(school, 5); + LessonLearningSystem.Apply(school, 5); + + var logs = school.DayLog + .Where(row => row.PersonId == pupilId && row.Type == PersonLogTypes.LessonNoTeacher) + .ToArray(); + Assert.Single(logs); + + var facts = school.DrainWorldEvents() + .Where(row => row.Trigger.Equals(EventTriggers.LessonNoTeacher, StringComparison.Ordinal)) + .ToArray(); + Assert.Single(facts); + Assert.Equal(teacherId, facts[0].PersonKey); + } + } + + [Fact] + public void PupilsPresent_WhileTeacherSick_AreNotMarkedTruancy() + { + var (school, room, pupilId, teacherId) = StaffedMath(); + using (school) + { + InfectHeavyFlu(school, teacherId); + var stayDay = TuesdayWithStayHome(school, teacherId); + RebuildDayAt(school, stayDay); + var lessonAt = stayDay.Date.Add(LessonStart.TimeOfDay); + AdvanceTo(school, lessonAt.AddMinutes(-1)); + SetPlace(school, pupilId, room); + SetPlace(school, teacherId, null); + + school.Clock.JumpTo(lessonAt); + AttendanceSystem.Apply(school); + school.Clock.JumpTo(lessonAt.AddMinutes(45)); + AttendanceSystem.Apply(school); + + var row = school.Roster!.People.First(p => p.Id == pupilId).Attendance?.LastOrDefault(); + Assert.NotNull(row); + Assert.Equal(AttendanceStatuses.Present, row!.Status); + Assert.Null(row.AbsenceReason); + Assert.NotEqual(AbsenceReasons.Truancy, row.AbsenceReason); + } + } + + [Fact] + public void SameDiseaseSeed_SameStayHomeDecision() + { + var (school, _, _, teacherId) = StaffedMath(); + using (school) + { + InfectHeavyFlu(school, teacherId); + var teacher = school.Roster!.People.First(row => row.Id == teacherId); + var when = LessonStart.AddDays(2); + var first = DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, when); + var second = DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, when); + Assert.Equal(first, second); + } + } + + private static void InfectHeavyFlu(School school, string teacherId) + { + var teacher = school.Roster!.People.First(row => row.Id == teacherId); + HealthConditions.Add( + teacher, + new HealthCondition + { + DefName = "Influenza", + Severity = 0.85f, + Progress = 0.1f, + Source = "cold", + StartedAt = TuesdayMorning.AddDays(-3), + }); + Assert.True(DiseaseEffects.StayHomeChance(teacher, school.Catalog!, LessonStart) >= 0.9f); + } + + private static DateTime TuesdayWithStayHome(School school, string teacherId) + { + var teacher = school.Roster!.People.First(row => row.Id == teacherId); + for (var i = 0; i < 60; i++) + { + var candidate = LessonStart.AddDays(i * 7); + if (DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, candidate)) + { + return candidate; + } + } + + throw new InvalidOperationException("Heavy flu should stay home on some Tuesday."); + } + + private static void RebuildDayAt(School school, DateTime lessonInstant) + { + school.PlanDay = null; + school.Clock.JumpTo(DateTime.SpecifyKind(lessonInstant.Date.AddHours(6), DateTimeKind.Utc)); + school.Tick(0.2d, 5d); + } + + private static bool IsOnCampus(School school, string personId) + { + var on = false; + var query = new QueryDescription().WithAll(); + school.World.Query( + in query, + (ref PersonIdentity identity, ref Presence presence) => + { + if (identity.Id.Equals(personId, StringComparison.Ordinal)) + { + on = presence.IsOnCampus; + } + }); + return on; + } + + private static LessonMarkRecord? MarkOf(School school, string pupilId) => + school.Roster!.People.First(row => row.Id == pupilId).LessonMarks?.LastOrDefault(); + + private static void AdvanceTo(School school, DateTime until) + { + while (school.Clock.Time < until) + { + school.Tick(0.2d, 5d); + } + } + + private static void SetPlace(School school, string personId, string? nodeId) + { + var query = new QueryDescription().WithAll(); + school.World.Query( + in query, + (ref PersonIdentity identity, ref Presence presence) => + { + if (!identity.Id.Equals(personId, StringComparison.Ordinal)) + { + return; + } + + presence = nodeId is null + ? Presence.OffCampus + : new Presence(nodeId, 0f, nodeId, false, []); + }); + } + + private static float SkillOf(School school, string personId, string skill) + { + var value = float.NaN; + var query = new QueryDescription().WithAll(); + school.World.Query( + in query, + (ref PersonIdentity identity, ref PersonSkills skills) => + { + if (identity.Id.Equals(personId, StringComparison.Ordinal)) + { + value = skills.Values.GetValueOrDefault(skill); + } + }); + return value; + } + + private static (School School, string Homeroom, string PupilId, string TeacherId) StaffedMath() + { + var (catalog, map) = Vanilla(); + var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", TuesdayMorning); + var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", TuesdayMorning); + var hired = Staffing.Hire(catalog, map, roster, pool, pool.Applicants[0].Person.Id, Staffing.TeacherPosition, 1_000_000f); + Assert.Equal(StaffingError.None, hired.Error); + roster = hired.Roster; + pool = hired.Pool; + var hiredId = roster.People.First(person => person.IsStaff).Id; + 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, "Больной учитель", TuesdayMorning, catalog, map); + school.InstallPeople(roster, seed: 1, "Russia", pool); + school.SetTimetable(new Timetable( + [new LessonPlacement(schoolClass.Id, "Mathematics", hiredId, schoolClass.RoomId, Day: 1, Period: 1)], + [])); + school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); + var pupil = schoolClass.PupilIds + .Select(id => school.Roster!.People.First(person => person.Id == id)) + .First(person => !person.Traits.Contains("Lazy")); + return (school, schoolClass.RoomId, pupil.Id, hiredId); + } + + private static (DefCatalog Catalog, MapLayout Map) Vanilla() + { + var root = Path.Combine(AppContext.BaseDirectory, "vanilla"); + var documents = new List(); + 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); + } +}