Add talk circles with TopicDef, staff/phone chat, and opinion outcomes.
This commit is contained in:
+38
-16
@@ -41,7 +41,8 @@ public readonly record struct ActorState(
|
||||
IReadOnlyDictionary<string, float> Needs,
|
||||
Intent Intent,
|
||||
bool LunchWindowOpen = false,
|
||||
ApparelActor Apparel = default);
|
||||
ApparelActor Apparel = default,
|
||||
TalkPlannerContext Talk = default);
|
||||
|
||||
/// <summary>
|
||||
/// Picks a goal by weight and plans walk-then-do. No world, no clock — a table of inputs to an
|
||||
@@ -254,6 +255,16 @@ public static class DecisionPlanner
|
||||
return Intent.None;
|
||||
}
|
||||
|
||||
if (state.BoundToLesson && TalkCircles.BlocksOnLesson(action.DefName))
|
||||
{
|
||||
return Intent.None;
|
||||
}
|
||||
|
||||
if (action.DefName.Equals(TalkActions.PhoneChat, StringComparison.Ordinal) && !state.Talk.HasPhone)
|
||||
{
|
||||
return Intent.None;
|
||||
}
|
||||
|
||||
if (RoomFor(catalog, map, walks, state, occupied, action) is null)
|
||||
{
|
||||
return Intent.None;
|
||||
@@ -396,8 +407,9 @@ public static class DecisionPlanner
|
||||
}
|
||||
|
||||
string? best = null;
|
||||
var bestCost = float.PositiveInfinity;
|
||||
var bestScore = float.NegativeInfinity;
|
||||
var from = state.NodeId ?? walks.TerritoryId;
|
||||
var candidates = new List<string>();
|
||||
foreach (var room in map.Rooms)
|
||||
{
|
||||
if (!action.Room.Equals(room.Def, StringComparison.Ordinal))
|
||||
@@ -410,27 +422,37 @@ public static class DecisionPlanner
|
||||
continue;
|
||||
}
|
||||
|
||||
var cost = walks.Minutes(from, room.Id);
|
||||
if (float.IsInfinity(cost) || cost > bestCost)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cost < bestCost || best is null || string.CompareOrdinal(room.Id, best) < 0)
|
||||
{
|
||||
best = room.Id;
|
||||
bestCost = cost;
|
||||
}
|
||||
candidates.Add(room.Id);
|
||||
}
|
||||
|
||||
if (map.Territory is { } territory
|
||||
&& action.Room.Equals(territory.Def, StringComparison.Ordinal)
|
||||
&& HasSlot(catalog, map, occupied, territory.Id, action.Thing))
|
||||
{
|
||||
var cost = walks.Minutes(from, territory.Id);
|
||||
if (!float.IsInfinity(cost) && (best is null || cost < bestCost || (cost == bestCost && string.CompareOrdinal(territory.Id, best) < 0)))
|
||||
candidates.Add(territory.Id);
|
||||
}
|
||||
|
||||
var hasAlternative = candidates.Count > 1;
|
||||
foreach (var nodeId in candidates)
|
||||
{
|
||||
if (action.Lunch
|
||||
&& TalkCircles.LunchNodeBlockedByEnemy(nodeId, state.Talk.SelfId ?? "", state.Talk, hasAlternative))
|
||||
{
|
||||
best = territory.Id;
|
||||
continue;
|
||||
}
|
||||
|
||||
var cost = walks.Minutes(from, nodeId);
|
||||
if (float.IsInfinity(cost))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var score = -cost + TalkCircles.NodeFriendScore(nodeId, state.Talk.SelfId ?? "", state.Talk);
|
||||
if (score > bestScore
|
||||
|| (score == bestScore && (best is null || string.CompareOrdinal(nodeId, best) < 0)))
|
||||
{
|
||||
best = nodeId;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
using HSchool.Content;
|
||||
using HSchool.People;
|
||||
|
||||
namespace HSchool.Ai;
|
||||
|
||||
/// <summary>Inputs the planner needs for friend pull and lunch avoidance. Built in simulation.</summary>
|
||||
public readonly record struct TalkPlannerContext(
|
||||
string? SelfId,
|
||||
IReadOnlyDictionary<string, int> Opinions,
|
||||
IReadOnlyDictionary<string, string> PersonNodes,
|
||||
string? ClassId,
|
||||
bool HasPhone,
|
||||
bool FriendPullActive,
|
||||
BehaviorDef? Rules);
|
||||
|
||||
/// <summary>
|
||||
/// Pure talk-circle rules: who joins, which topic, opinion and skill math. No world access.
|
||||
/// </summary>
|
||||
public static class TalkCircles
|
||||
{
|
||||
public static bool BlocksOnLesson(string actionId) => TalkActions.IsTalk(actionId);
|
||||
|
||||
public static int MaxSize(string actionId, BehaviorDef? rules, IReadOnlyList<string> traitIds, DefCatalog catalog)
|
||||
{
|
||||
if (actionId.Equals(TalkActions.PhoneChat, StringComparison.Ordinal))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
var max = rules?.TalkCircleMax ?? 4;
|
||||
foreach (var traitId in traitIds)
|
||||
{
|
||||
if (catalog.Traits.TryGetValue(traitId, out var trait))
|
||||
{
|
||||
max += trait.TalkCircleBonus;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.Clamp(max, rules?.TalkCircleMin ?? 2, 4);
|
||||
}
|
||||
|
||||
public static bool IsFriend(int? opinion, BehaviorDef? rules) =>
|
||||
opinion >= (rules?.TalkFriendThreshold ?? 40);
|
||||
|
||||
public static bool IsEnemy(int? opinion, BehaviorDef? rules) =>
|
||||
opinion <= (rules?.TalkEnemyThreshold ?? -40);
|
||||
|
||||
public static bool HasPhone(IReadOnlyList<InventoryItem> items) =>
|
||||
items.Any(item =>
|
||||
item.Def.Equals("Phone", StringComparison.Ordinal)
|
||||
&& item.Location.Equals(ItemLocations.Bag, StringComparison.Ordinal));
|
||||
|
||||
public static float Initiative(IReadOnlyList<string> traitIds, DefCatalog catalog)
|
||||
{
|
||||
var weight = 1f;
|
||||
foreach (var traitId in traitIds)
|
||||
{
|
||||
if (catalog.Traits.TryGetValue(traitId, out var trait) && trait.TalkInitiative > 0f)
|
||||
{
|
||||
weight *= trait.TalkInitiative;
|
||||
}
|
||||
}
|
||||
|
||||
return weight;
|
||||
}
|
||||
|
||||
public static float OpinionMultiplier(IReadOnlyList<string> traitIds, DefCatalog catalog)
|
||||
{
|
||||
var mult = 1f;
|
||||
foreach (var traitId in traitIds)
|
||||
{
|
||||
if (catalog.Traits.TryGetValue(traitId, out var trait) && trait.TalkOpinionMultiplier > 0f)
|
||||
{
|
||||
mult *= trait.TalkOpinionMultiplier;
|
||||
}
|
||||
}
|
||||
|
||||
return mult;
|
||||
}
|
||||
|
||||
/// <summary>Score a room node for friend pull on break or lunch.</summary>
|
||||
public static float NodeFriendScore(
|
||||
string nodeId,
|
||||
string selfId,
|
||||
TalkPlannerContext context)
|
||||
{
|
||||
if (!context.FriendPullActive)
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
|
||||
var score = 0f;
|
||||
foreach (var (personId, otherNode) in context.PersonNodes)
|
||||
{
|
||||
if (personId.Equals(selfId, StringComparison.Ordinal) || otherNode != nodeId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
context.Opinions.TryGetValue(personId, out var opinion);
|
||||
if (IsFriend(opinion, context.Rules))
|
||||
{
|
||||
score += 2f;
|
||||
}
|
||||
else if (IsEnemy(opinion, context.Rules))
|
||||
{
|
||||
score -= 3f;
|
||||
}
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/// <summary>True when this lunch node should be avoided because an enemy sits there.</summary>
|
||||
public static bool LunchNodeBlockedByEnemy(
|
||||
string nodeId,
|
||||
string selfId,
|
||||
TalkPlannerContext context,
|
||||
bool hasAlternative)
|
||||
{
|
||||
if (!hasAlternative)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (personId, otherNode) in context.PersonNodes)
|
||||
{
|
||||
if (personId.Equals(selfId, StringComparison.Ordinal) || otherNode != nodeId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
context.Opinions.TryGetValue(personId, out var opinion);
|
||||
if (IsEnemy(opinion, context.Rules))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool RoleFitsTopic(TopicDef topic, bool isStudent, bool isStaff, bool isParent)
|
||||
{
|
||||
if (topic.Roles.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (var role in topic.Roles)
|
||||
{
|
||||
if (role.Equals(PersonRoles.Student, StringComparison.OrdinalIgnoreCase) && isStudent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (role.Equals(PersonRoles.Staff, StringComparison.OrdinalIgnoreCase) && isStaff)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (role.Equals(PersonRoles.Parent, StringComparison.OrdinalIgnoreCase) && isParent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool AgeFits(TopicDef topic, int age)
|
||||
{
|
||||
if (topic.Age is not { } range)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return age >= range.Min && age <= range.Max;
|
||||
}
|
||||
|
||||
public static string? PickTopic(
|
||||
DefCatalog catalog,
|
||||
Person picker,
|
||||
int age,
|
||||
int seed)
|
||||
{
|
||||
var candidates = new List<(TopicDef Topic, float Weight)>();
|
||||
foreach (var topic in catalog.Topics.Values)
|
||||
{
|
||||
if (topic.Abstract
|
||||
|| !RoleFitsTopic(topic, picker.IsStudent, picker.IsStaff, picker.IsParent)
|
||||
|| !AgeFits(topic, age))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var weight = 1f;
|
||||
foreach (var traitId in picker.Traits)
|
||||
{
|
||||
if (!catalog.Traits.TryGetValue(traitId, out var trait))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var bias in trait.TalkTagWeights)
|
||||
{
|
||||
if (topic.Tags.Contains(bias.Tag, StringComparer.Ordinal))
|
||||
{
|
||||
weight *= bias.Weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates.Add((topic, weight));
|
||||
}
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var total = candidates.Sum(pair => pair.Weight);
|
||||
var roll = (seed & int.MaxValue) % Math.Max(1, (int)(total * 1000)) / 1000f;
|
||||
var cursor = 0f;
|
||||
foreach (var (topic, weight) in candidates.OrderBy(pair => pair.Topic.DefName, StringComparer.Ordinal))
|
||||
{
|
||||
cursor += weight / total;
|
||||
if (roll <= cursor)
|
||||
{
|
||||
return topic.DefName;
|
||||
}
|
||||
}
|
||||
|
||||
return candidates[^1].Topic.DefName;
|
||||
}
|
||||
|
||||
/// <summary>Best shared language skill id among participants, or null.</summary>
|
||||
public static string? SharedLanguage(
|
||||
DefCatalog catalog,
|
||||
IReadOnlyList<Person> participants,
|
||||
BehaviorDef? rules)
|
||||
{
|
||||
var threshold = rules?.TalkLanguageThreshold ?? 25;
|
||||
string? best = null;
|
||||
var bestLevel = 0f;
|
||||
foreach (var skill in catalog.Skills.Values.Where(def =>
|
||||
!def.Abstract
|
||||
&& !def.DefName.Equals("Communication", StringComparison.Ordinal)
|
||||
&& (def.AdultChance > 0f || def.DefName.EndsWith("Language", StringComparison.Ordinal))))
|
||||
{
|
||||
var min = float.MaxValue;
|
||||
foreach (var person in participants)
|
||||
{
|
||||
if (!person.Skills.TryGetValue(skill.DefName, out var level) || level < threshold)
|
||||
{
|
||||
min = 0f;
|
||||
break;
|
||||
}
|
||||
|
||||
min = Math.Min(min, level);
|
||||
}
|
||||
|
||||
if (min >= threshold && min > bestLevel)
|
||||
{
|
||||
bestLevel = min;
|
||||
best = skill.DefName;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
public static int AppearanceModifier(ApparelIssue issues) =>
|
||||
issues == ApparelIssue.None ? 2 : issues.HasFlag(ApparelIssue.Formality) ? -2 : 0;
|
||||
|
||||
public static int OpinionDelta(
|
||||
Person from,
|
||||
Person to,
|
||||
TopicDef topic,
|
||||
float communication,
|
||||
bool sharedLanguage,
|
||||
string actionId,
|
||||
ApparelIssue targetAppearance,
|
||||
BehaviorDef? rules,
|
||||
DefCatalog catalog)
|
||||
{
|
||||
var baseShift = topic.OpinionShift;
|
||||
if (topic.Tags.Contains(TopicTags.Appearance, StringComparer.Ordinal))
|
||||
{
|
||||
baseShift += AppearanceModifier(targetAppearance);
|
||||
}
|
||||
|
||||
var commScale = 1f + (communication / 100f) * (rules?.TalkCommunicationOpinionScale ?? 0.5f);
|
||||
var mult = OpinionMultiplier(from.Traits.ToList(), catalog) * commScale;
|
||||
if (!sharedLanguage)
|
||||
{
|
||||
mult *= rules?.TalkNoLanguageOpinionMultiplier ?? 0.15f;
|
||||
if (baseShift > 0)
|
||||
{
|
||||
baseShift = Math.Max(1, baseShift / 3);
|
||||
}
|
||||
}
|
||||
|
||||
if (actionId.Equals(TalkActions.PhoneChat, StringComparison.Ordinal))
|
||||
{
|
||||
mult *= rules?.TalkPhoneOpinionMultiplier ?? 0.5f;
|
||||
}
|
||||
|
||||
var delta = (int)Math.Round(baseShift * mult, MidpointRounding.AwayFromZero);
|
||||
if (!sharedLanguage && delta > 0)
|
||||
{
|
||||
delta = Math.Min(delta, 1);
|
||||
}
|
||||
else if (!sharedLanguage && delta == 0 && baseShift <= 0)
|
||||
{
|
||||
delta = -1;
|
||||
}
|
||||
|
||||
return Math.Clamp(delta, -20, 20);
|
||||
}
|
||||
|
||||
public static float CommunicationGain(
|
||||
float current,
|
||||
SkillDef skill,
|
||||
float hours,
|
||||
BehaviorDef? rules) =>
|
||||
Math.Clamp(current + (rules?.TalkSkillPerHour ?? 0.02f) * hours, skill.Range.Min, skill.Range.Max);
|
||||
|
||||
public static float LanguageGain(
|
||||
float current,
|
||||
SkillDef skill,
|
||||
float hours,
|
||||
BehaviorDef? rules) =>
|
||||
Math.Clamp(current + (rules?.TalkLanguageSkillPerHour ?? 0.005f) * hours, skill.Range.Min, skill.Range.Max);
|
||||
|
||||
/// <summary>Invite priority: friends, classmates, others. Enemies never invited.</summary>
|
||||
public static IReadOnlyList<string> RankInvitees(
|
||||
Person initiator,
|
||||
IReadOnlyList<Candidate> candidates,
|
||||
BehaviorDef? rules)
|
||||
{
|
||||
return candidates
|
||||
.Where(candidate => !candidate.Id.Equals(initiator.Id, StringComparison.Ordinal))
|
||||
.Where(candidate =>
|
||||
{
|
||||
initiator.Opinions.TryGetValue(candidate.Id, out var opinion);
|
||||
return !IsEnemy(opinion, rules);
|
||||
})
|
||||
.OrderByDescending(candidate =>
|
||||
{
|
||||
initiator.Opinions.TryGetValue(candidate.Id, out var opinion);
|
||||
if (IsFriend(opinion, rules))
|
||||
{
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (initiator.ClassId is not null
|
||||
&& candidate.ClassId is not null
|
||||
&& initiator.ClassId.Equals(candidate.ClassId, StringComparison.Ordinal))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
return 1;
|
||||
})
|
||||
.ThenBy(candidate => candidate.Id, StringComparer.Ordinal)
|
||||
.Select(candidate => candidate.Id)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public readonly record struct Candidate(
|
||||
string Id,
|
||||
string? ClassId,
|
||||
bool IsIdle,
|
||||
bool InCircle,
|
||||
bool HasPhone);
|
||||
}
|
||||
@@ -315,6 +315,7 @@ public sealed class CatalogLoader
|
||||
var holidays = new Dictionary<string, HolidayDef>(StringComparer.Ordinal);
|
||||
var behavior = new Dictionary<string, BehaviorDef>(StringComparer.Ordinal);
|
||||
var colors = new Dictionary<string, ColorDef>(StringComparer.Ordinal);
|
||||
var topics = new Dictionary<string, TopicDef>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var (key, json) in resolved)
|
||||
{
|
||||
@@ -380,6 +381,9 @@ public sealed class CatalogLoader
|
||||
case DefKind.Color:
|
||||
colors[key.Name] = Jsonc.Deserialize<ColorDef>(json);
|
||||
break;
|
||||
case DefKind.Topic:
|
||||
topics[key.Name] = Jsonc.Deserialize<TopicDef>(json);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,6 +409,7 @@ public sealed class CatalogLoader
|
||||
holidays,
|
||||
behavior,
|
||||
colors,
|
||||
topics,
|
||||
ru,
|
||||
en);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed class DefCatalog
|
||||
IReadOnlyDictionary<string, HolidayDef> holidays,
|
||||
IReadOnlyDictionary<string, BehaviorDef> behavior,
|
||||
IReadOnlyDictionary<string, ColorDef> colors,
|
||||
IReadOnlyDictionary<string, TopicDef> topics,
|
||||
IReadOnlyDictionary<string, string> ru,
|
||||
IReadOnlyDictionary<string, string> en)
|
||||
{
|
||||
@@ -52,6 +53,7 @@ public sealed class DefCatalog
|
||||
Holidays = holidays;
|
||||
Behavior = behavior;
|
||||
Colors = colors;
|
||||
Topics = topics;
|
||||
_ru = ru;
|
||||
_en = en;
|
||||
AnyNeedDecays = needs.Values.Any(need => !need.Abstract && need.DecayPerHour > 0f);
|
||||
@@ -109,6 +111,8 @@ public sealed class DefCatalog
|
||||
|
||||
public IReadOnlyDictionary<string, ColorDef> Colors { get; }
|
||||
|
||||
public IReadOnlyDictionary<string, TopicDef> Topics { get; }
|
||||
|
||||
/// <summary>The one concrete staffing ruleset, or null when a pack has not defined it.</summary>
|
||||
public StaffingDef? StaffingRules => Staffing.Values.FirstOrDefault(def => !def.Abstract);
|
||||
|
||||
@@ -145,6 +149,7 @@ public sealed class DefCatalog
|
||||
DefKind.Holiday => Holidays.GetValueOrDefault(defName),
|
||||
DefKind.Behavior => Behavior.GetValueOrDefault(defName),
|
||||
DefKind.Color => Colors.GetValueOrDefault(defName),
|
||||
DefKind.Topic => Topics.GetValueOrDefault(defName),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -225,6 +230,7 @@ public sealed class DefCatalog
|
||||
HolidayDef => DefKind.Holiday,
|
||||
BehaviorDef => DefKind.Behavior,
|
||||
ColorDef => DefKind.Color,
|
||||
TopicDef => DefKind.Topic,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(def)),
|
||||
};
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ public enum DefKind
|
||||
Holiday,
|
||||
Behavior,
|
||||
Color,
|
||||
Topic,
|
||||
}
|
||||
|
||||
/// <summary>Shared JSONC fields. Kind comes from the folder under <c>defs/</c>, not from the file.</summary>
|
||||
|
||||
@@ -129,6 +129,9 @@ internal static class PackPaths
|
||||
case "colors":
|
||||
kind = DefKind.Color;
|
||||
return true;
|
||||
case "topics":
|
||||
kind = DefKind.Topic;
|
||||
return true;
|
||||
default:
|
||||
kind = default;
|
||||
return false;
|
||||
|
||||
@@ -65,6 +65,13 @@ internal static class PeopleDefValidator
|
||||
ValidateBehavior(behavior, log);
|
||||
}
|
||||
|
||||
foreach (var topic in catalog.Topics.Values)
|
||||
{
|
||||
ValidateTopic(topic, catalog);
|
||||
}
|
||||
|
||||
RequireTalkTopics(catalog);
|
||||
|
||||
if (catalog.Staffing.Values.Count(def => !def.Abstract) > 1)
|
||||
{
|
||||
throw new ContentLoadException("A catalog may only have one concrete StaffingDef.");
|
||||
@@ -550,6 +557,63 @@ internal static class PeopleDefValidator
|
||||
log.Warning(
|
||||
$"BehaviorDef '{behavior.DefName}' lunchWeight {behavior.LunchWeight} is above dutyLessonWeight {behavior.DutyLessonWeight}; pupils will leave class for lunch.");
|
||||
}
|
||||
|
||||
if (behavior.TalkCircleMin < 2 || behavior.TalkCircleMax < behavior.TalkCircleMin)
|
||||
{
|
||||
throw new ContentLoadException(
|
||||
$"BehaviorDef '{behavior.DefName}' talk circle size must be at least 2 with max ≥ min.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateTopic(TopicDef topic, DefCatalog catalog)
|
||||
{
|
||||
if (topic.Abstract)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (topic.Tags.Count == 0)
|
||||
{
|
||||
throw new ContentLoadException($"TopicDef '{topic.DefName}' needs at least one tag.");
|
||||
}
|
||||
|
||||
if (topic.Age is { Min: var min, Max: var max } && min > max)
|
||||
{
|
||||
throw new ContentLoadException($"TopicDef '{topic.DefName}' age min cannot exceed max.");
|
||||
}
|
||||
|
||||
foreach (var role in topic.Roles)
|
||||
{
|
||||
if (!PersonRoles.IsKnown(role))
|
||||
{
|
||||
throw new ContentLoadException($"TopicDef '{topic.DefName}' has unknown role '{role}'.");
|
||||
}
|
||||
}
|
||||
|
||||
if (topic.Language is not null && !catalog.Skills.ContainsKey(topic.Language))
|
||||
{
|
||||
throw new ContentLoadException($"TopicDef '{topic.DefName}' references unknown SkillDef '{topic.Language}'.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A catalog with circle actions but no topics would silently solo-chat — refuse load.</summary>
|
||||
private static void RequireTalkTopics(DefCatalog catalog)
|
||||
{
|
||||
var hasTalkAction = catalog.Actions.Values.Any(action =>
|
||||
!action.Abstract
|
||||
&& (action.DefName.Equals(TalkActions.Chat, StringComparison.Ordinal)
|
||||
|| action.DefName.Equals(TalkActions.StaffChat, StringComparison.Ordinal)
|
||||
|| action.DefName.Equals(TalkActions.PhoneChat, StringComparison.Ordinal)));
|
||||
if (!hasTalkAction)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!catalog.Topics.Values.Any(topic => !topic.Abstract))
|
||||
{
|
||||
throw new ContentLoadException(
|
||||
"A catalog with talk actions requires at least one concrete TopicDef.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateConditionBands(BehaviorDef behavior)
|
||||
|
||||
@@ -162,6 +162,14 @@ public sealed class TraitSkillModifier
|
||||
public int Offset { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Biases topic pick toward a tag. Used on gossip and similar traits.</summary>
|
||||
public sealed class TopicTagWeight
|
||||
{
|
||||
public required string Tag { get; init; }
|
||||
|
||||
public float Weight { get; init; } = 1f;
|
||||
}
|
||||
|
||||
public sealed class TraitDef : Def
|
||||
{
|
||||
public int Weight { get; init; } = 1;
|
||||
@@ -190,6 +198,39 @@ public sealed class TraitDef : Def
|
||||
/// cold-loving is negative.
|
||||
/// </summary>
|
||||
public float ComfortTemperatureOffset { get; init; }
|
||||
|
||||
/// <summary>How often this person initiates talk. Quiet below 1, leader above.</summary>
|
||||
public float TalkInitiative { get; init; } = 1f;
|
||||
|
||||
/// <summary>Extra seats preferred in a circle. Social trait raises it.</summary>
|
||||
public int TalkCircleBonus { get; init; }
|
||||
|
||||
/// <summary>Multiplies opinion shift from talk. Gossip above 1.</summary>
|
||||
public float TalkOpinionMultiplier { get; init; } = 1f;
|
||||
|
||||
/// <summary>Pull toward topics carrying these tags when this person picks the subject.</summary>
|
||||
public IReadOnlyList<TopicTagWeight> TalkTagWeights { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Conversation subject. Tags gate appropriateness; language is optional skill help.</summary>
|
||||
public sealed class TopicDef : Def
|
||||
{
|
||||
/// <summary>Vanilla tags: study, games, food, family, sport, gossip, rude, appearance.</summary>
|
||||
public IReadOnlyList<string> Tags { get; init; } = [];
|
||||
|
||||
public IntRange? Age { get; init; }
|
||||
|
||||
/// <summary>Empty means every role.</summary>
|
||||
public IReadOnlyList<string> Roles { get; init; } = [];
|
||||
|
||||
/// <summary>Allowed as whisper on lesson — phase 43 uses this; ordinary Chat does not.</summary>
|
||||
public bool WhisperOnLesson { get; init; }
|
||||
|
||||
/// <summary>Skill that helps when shared above threshold. Null — any language works equally.</summary>
|
||||
public string? Language { get; init; }
|
||||
|
||||
/// <summary>Base opinion shift toward each other participant when talk succeeds.</summary>
|
||||
public int OpinionShift { get; init; } = 2;
|
||||
}
|
||||
|
||||
public sealed class StaffingDef : Def
|
||||
@@ -329,6 +370,36 @@ public sealed class BehaviorDef : Def
|
||||
/// </summary>
|
||||
public IReadOnlyList<OpinionBand> OpinionBands { get; init; } = DefaultOpinionBands;
|
||||
|
||||
/// <summary>Skill points Communication gains per game hour of talk — less than a lesson.</summary>
|
||||
public float TalkSkillPerHour { get; init; } = 0.02f;
|
||||
|
||||
/// <summary>Language used in talk, when not already at skill max.</summary>
|
||||
public float TalkLanguageSkillPerHour { get; init; } = 0.005f;
|
||||
|
||||
/// <summary>Minimum shared language skill for full opinion shift.</summary>
|
||||
public int TalkLanguageThreshold { get; init; } = 25;
|
||||
|
||||
/// <summary>Opinion multiplier when participants share no language above threshold.</summary>
|
||||
public float TalkNoLanguageOpinionMultiplier { get; init; } = 0.15f;
|
||||
|
||||
/// <summary>Opinion multiplier for phone chat vs live circle.</summary>
|
||||
public float TalkPhoneOpinionMultiplier { get; init; } = 0.5f;
|
||||
|
||||
/// <summary>How much Communication scales opinion shift (per 100 points).</summary>
|
||||
public float TalkCommunicationOpinionScale { get; init; } = 0.5f;
|
||||
|
||||
/// <summary>Minimum circle size. Below this Chat does not start.</summary>
|
||||
public int TalkCircleMin { get; init; } = 2;
|
||||
|
||||
/// <summary>Maximum people in one live circle.</summary>
|
||||
public int TalkCircleMax { get; init; } = 4;
|
||||
|
||||
/// <summary>Opinion at or above — friend for invites and node pull.</summary>
|
||||
public int TalkFriendThreshold { get; init; } = 40;
|
||||
|
||||
/// <summary>Opinion at or below — enemy; never invited, lunch nodes avoided.</summary>
|
||||
public int TalkEnemyThreshold { get; init; } = -40;
|
||||
|
||||
public static IReadOnlyList<OpinionBand> DefaultOpinionBands { get; } =
|
||||
[
|
||||
new() { Min = 70, Id = "OpinionCloseFriend" },
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace HSchool.Content;
|
||||
|
||||
/// <summary>Leisure actions that form talk circles. Names match ActionDef ids in core.</summary>
|
||||
public static class TalkActions
|
||||
{
|
||||
public const string Chat = "Chat";
|
||||
public const string StaffChat = "StaffChat";
|
||||
public const string PhoneChat = "PhoneChat";
|
||||
|
||||
public static bool IsTalk(string? actionId) =>
|
||||
actionId is not null
|
||||
&& (actionId.Equals(Chat, StringComparison.Ordinal)
|
||||
|| actionId.Equals(StaffChat, StringComparison.Ordinal)
|
||||
|| actionId.Equals(PhoneChat, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>Vanilla topic tags from the social slice design doc.</summary>
|
||||
public static class TopicTags
|
||||
{
|
||||
public const string Study = "study";
|
||||
public const string Games = "games";
|
||||
public const string Food = "food";
|
||||
public const string Family = "family";
|
||||
public const string Sport = "sport";
|
||||
public const string Gossip = "gossip";
|
||||
public const string Rude = "rude";
|
||||
public const string Appearance = "appearance";
|
||||
}
|
||||
@@ -36,6 +36,24 @@
|
||||
"roles": ["student", "staff"],
|
||||
"weight": 3,
|
||||
},
|
||||
{
|
||||
"defName": "StaffChat",
|
||||
"room": "TeachersRoom",
|
||||
"minutes": 8,
|
||||
"need": "Social",
|
||||
"needGain": 0.4,
|
||||
"roles": ["staff"],
|
||||
"weight": 3,
|
||||
},
|
||||
{
|
||||
"defName": "PhoneChat",
|
||||
"room": "Corridor",
|
||||
"minutes": 6,
|
||||
"need": "Social",
|
||||
"needGain": 0.25,
|
||||
"roles": ["student"],
|
||||
"weight": 2,
|
||||
},
|
||||
{
|
||||
"defName": "WalkCorridor",
|
||||
"room": "Corridor",
|
||||
|
||||
@@ -62,4 +62,15 @@
|
||||
{ "min": -40, "id": "OpinionDislike" },
|
||||
{ "min": -100, "id": "OpinionEnemy" },
|
||||
],
|
||||
// Talk circles (slice 9 phase 42). Communication per hour is well below lessonSkillPerHour.
|
||||
"talkSkillPerHour": 0.02,
|
||||
"talkLanguageSkillPerHour": 0.005,
|
||||
"talkLanguageThreshold": 25,
|
||||
"talkNoLanguageOpinionMultiplier": 0.15,
|
||||
"talkPhoneOpinionMultiplier": 0.5,
|
||||
"talkCommunicationOpinionScale": 0.5,
|
||||
"talkCircleMin": 2,
|
||||
"talkCircleMax": 4,
|
||||
"talkFriendThreshold": 40,
|
||||
"talkEnemyThreshold": -40,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
[
|
||||
{
|
||||
"defName": "TopicStudy",
|
||||
"tags": ["study"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": 2,
|
||||
},
|
||||
{
|
||||
"defName": "TopicGames",
|
||||
"tags": ["games"],
|
||||
"roles": ["student"],
|
||||
"age": { "min": 7, "max": 18 },
|
||||
"opinionShift": 3,
|
||||
},
|
||||
{
|
||||
"defName": "TopicFood",
|
||||
"tags": ["food"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": 2,
|
||||
},
|
||||
{
|
||||
"defName": "TopicFamily",
|
||||
"tags": ["family"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": 2,
|
||||
},
|
||||
{
|
||||
"defName": "TopicSport",
|
||||
"tags": ["sport"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": 3,
|
||||
},
|
||||
{
|
||||
"defName": "TopicGossip",
|
||||
"tags": ["gossip"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": 1,
|
||||
},
|
||||
{
|
||||
"defName": "TopicRude",
|
||||
"tags": ["rude"],
|
||||
"roles": ["student", "staff"],
|
||||
"opinionShift": -3,
|
||||
},
|
||||
{
|
||||
"defName": "TopicAppearance",
|
||||
"tags": ["appearance"],
|
||||
"roles": ["student"],
|
||||
"age": { "min": 11, "max": 18 },
|
||||
"opinionShift": 1,
|
||||
},
|
||||
]
|
||||
@@ -34,12 +34,14 @@
|
||||
"weight": 7,
|
||||
"incompatible": ["Leader", "Bully"],
|
||||
"wageAsk": -8,
|
||||
"talkInitiative": 0.45,
|
||||
},
|
||||
{
|
||||
"defName": "Leader",
|
||||
"weight": 4,
|
||||
"incompatible": ["Quiet"],
|
||||
"wageAsk": 10,
|
||||
"talkInitiative": 1.6,
|
||||
"skillModifiers": [
|
||||
{ "skill": "History", "offset": 4 },
|
||||
],
|
||||
@@ -92,4 +94,18 @@
|
||||
"incompatible": ["HeatLoving"],
|
||||
"comfortTemperatureOffset": -4,
|
||||
},
|
||||
{
|
||||
"defName": "Gossip",
|
||||
"weight": 5,
|
||||
"roles": ["student", "staff"],
|
||||
"talkOpinionMultiplier": 1.5,
|
||||
"talkTagWeights": [{ "tag": "gossip", "weight": 3 }],
|
||||
},
|
||||
{
|
||||
"defName": "Outgoing",
|
||||
"weight": 6,
|
||||
"incompatible": ["Quiet"],
|
||||
"talkInitiative": 1.4,
|
||||
"talkCircleBonus": 1,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
"UseToilet": "Restroom",
|
||||
"RecessRest": "Recess",
|
||||
"Chat": "Chat",
|
||||
"StaffChat": "Staff chat",
|
||||
"PhoneChat": "Phone chat",
|
||||
"WalkCorridor": "Walk the corridor",
|
||||
"WalkYard": "Walk the yard",
|
||||
"Behavior": "Behavior rules",
|
||||
@@ -139,6 +141,8 @@
|
||||
"Curious": "Curious",
|
||||
"HotTempered": "Hot-tempered",
|
||||
"Kind": "Kind",
|
||||
"Gossip": "Gossip",
|
||||
"Outgoing": "Outgoing",
|
||||
"Neat": "Neat",
|
||||
"Staffing": "Staffing",
|
||||
"Height": "Height",
|
||||
@@ -189,6 +193,15 @@
|
||||
"OpinionEnemy": "enemies",
|
||||
"ActionStarted": "started: {0}",
|
||||
"ActionEnded": "finished: {0}",
|
||||
"TalkEnded": "talked about {0}",
|
||||
"TopicStudy": "schoolwork",
|
||||
"TopicGames": "games",
|
||||
"TopicFood": "food",
|
||||
"TopicFamily": "family",
|
||||
"TopicSport": "sport",
|
||||
"TopicGossip": "gossip",
|
||||
"TopicRude": "rough talk",
|
||||
"TopicAppearance": "looks",
|
||||
"ApparelReplaced": "got a new {0}",
|
||||
"ApparelChanged": "changed clothes: {0}",
|
||||
"core": "Core",
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
"UseToilet": "Туалет",
|
||||
"RecessRest": "Перемена",
|
||||
"Chat": "Разговор",
|
||||
"StaffChat": "Разговор в учительской",
|
||||
"PhoneChat": "Разговор по телефону",
|
||||
"WalkCorridor": "Прогулка по коридору",
|
||||
"WalkYard": "Прогулка во дворе",
|
||||
"Behavior": "Правила поведения",
|
||||
@@ -139,6 +141,8 @@
|
||||
"Curious": "Любопытный",
|
||||
"HotTempered": "Вспыльчивый",
|
||||
"Kind": "Добрый",
|
||||
"Gossip": "Сплетник",
|
||||
"Outgoing": "Общительный",
|
||||
"Neat": "Аккуратный",
|
||||
"Staffing": "Штат",
|
||||
"Height": "Рост",
|
||||
@@ -189,6 +193,15 @@
|
||||
"OpinionEnemy": "враги",
|
||||
"ActionStarted": "начал: {0}",
|
||||
"ActionEnded": "закончил: {0}",
|
||||
"TalkEnded": "говорил о {0}",
|
||||
"TopicStudy": "учёбе",
|
||||
"TopicGames": "играх",
|
||||
"TopicFood": "еде",
|
||||
"TopicFamily": "семье",
|
||||
"TopicSport": "спорте",
|
||||
"TopicGossip": "сплетнях",
|
||||
"TopicRude": "грубом",
|
||||
"TopicAppearance": "внешности",
|
||||
"ApparelReplaced": "получил новую {0}",
|
||||
"ApparelChanged": "переоделся: {0}",
|
||||
"core": "Базовая игра",
|
||||
|
||||
@@ -21,6 +21,11 @@ internal static class ActivitySystem
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TalkActions.IsTalk(actionId))
|
||||
{
|
||||
return TalkCircleSystem.TryStart(school, personId, actionId);
|
||||
}
|
||||
|
||||
if (!school.Catalog.Actions.TryGetValue(actionId, out var action) || action.Abstract)
|
||||
{
|
||||
return false;
|
||||
@@ -114,6 +119,11 @@ internal static class ActivitySystem
|
||||
return;
|
||||
}
|
||||
|
||||
if (TalkActions.IsTalk(activity.ActionId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var location = school.Map?.NodeDef(presence.NodeId ?? "");
|
||||
if (location is null || !location.Equals(action.Room, StringComparison.Ordinal))
|
||||
{
|
||||
|
||||
@@ -12,6 +12,7 @@ public static class PersonLogTypes
|
||||
{
|
||||
public const string ActionStarted = "action-started";
|
||||
public const string ActionEnded = "action-ended";
|
||||
public const string TalkEnded = "talk-ended";
|
||||
public const string ApparelReplaced = "apparel-replaced";
|
||||
public const string ApparelChanged = "apparel-changed";
|
||||
}
|
||||
@@ -58,6 +59,14 @@ public sealed record PersonLogEvent(string PersonId, DateTime Time, string Type,
|
||||
return string.Format(CultureInfo.InvariantCulture, catalog.Text(locale, key), name);
|
||||
}
|
||||
|
||||
if (Type.Equals(PersonLogTypes.TalkEnded, StringComparison.Ordinal))
|
||||
{
|
||||
var topic = catalog.Topics.TryGetValue(ThingDef ?? "", out var def)
|
||||
? catalog.Label(locale, def)
|
||||
: ThingDef ?? Type;
|
||||
return string.Format(CultureInfo.InvariantCulture, catalog.Text(locale, "TalkEnded"), topic);
|
||||
}
|
||||
|
||||
return Type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,6 +324,23 @@ internal static class PresenceSystem
|
||||
{
|
||||
var now = school.Clock.Time;
|
||||
var walks = school.Walks!;
|
||||
var slot = SchoolDay.At(school.Catalog!, now, school.SchoolWeekDays);
|
||||
var weekday = SchoolDay.WeekdayIndex(now);
|
||||
var lessons = Duty.LessonsToday(person, ClassOf(school, person), school.Timetable, weekday);
|
||||
var bound = Duty.IsOtherStaff(person)
|
||||
? slot.Kind != DaySlotKind.Outside
|
||||
: slot.Kind == DaySlotKind.Lesson && lessons.Any(lesson => lesson.Period == slot.Index);
|
||||
if (activity.IsActive && TalkActions.IsTalk(activity.ActionId))
|
||||
{
|
||||
if (!bound)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
TalkCircleSystem.Interrupt(school, person.Id);
|
||||
activity = PersonActivity.Idle;
|
||||
}
|
||||
|
||||
if (!presence.IsOnCampus)
|
||||
{
|
||||
intent = Intent.None;
|
||||
@@ -369,16 +386,11 @@ internal static class PresenceSystem
|
||||
return null;
|
||||
}
|
||||
|
||||
var slot = SchoolDay.At(school.Catalog!, now, school.SchoolWeekDays);
|
||||
var weekday = SchoolDay.WeekdayIndex(now);
|
||||
var lessons = Duty.LessonsToday(person, ClassOf(school, person), school.Timetable, weekday);
|
||||
var bound = Duty.IsOtherStaff(person)
|
||||
? slot.Kind != DaySlotKind.Outside
|
||||
: slot.Kind == DaySlotKind.Lesson && lessons.Any(lesson => lesson.Period == slot.Index);
|
||||
var frame = school.Catalog!.DayFrame;
|
||||
var lunchOpen = frame is not null
|
||||
&& SchoolDay.IsLunchWindow(frame, slot, ClassOf(school, person)?.Year);
|
||||
var apparel = ApparelPresence.Build(school, person, ClassOf(school, person));
|
||||
var talk = BuildTalkContext(school, person, bound, lunchOpen, slot);
|
||||
var state = new ActorState(
|
||||
presence.NodeId,
|
||||
presence.DestinationId,
|
||||
@@ -392,7 +404,8 @@ internal static class PresenceSystem
|
||||
needs.Values,
|
||||
intent,
|
||||
lunchOpen,
|
||||
apparel);
|
||||
apparel,
|
||||
talk);
|
||||
var decision = DecisionPlanner.Decide(
|
||||
school.Catalog!,
|
||||
school.Map!,
|
||||
@@ -401,17 +414,19 @@ internal static class PresenceSystem
|
||||
(node, thing) => occupied.GetValueOrDefault((node, thing)));
|
||||
|
||||
var changing = activity.IsActive && ActivitySystem.IsChangeClothes(activity.ActionId);
|
||||
var inTalk = activity.IsActive && TalkActions.IsTalk(activity.ActionId);
|
||||
|
||||
if (decision.WalkTo is not null
|
||||
&& !decision.WalkTo.Equals(presence.NodeId, StringComparison.Ordinal)
|
||||
&& activity.IsActive
|
||||
&& !changing)
|
||||
&& !changing
|
||||
&& !inTalk)
|
||||
{
|
||||
activity = PersonActivity.Idle;
|
||||
}
|
||||
|
||||
intent = decision.Intent;
|
||||
if (decision.WalkTo is not null && !changing)
|
||||
if (decision.WalkTo is not null && !changing && !inTalk)
|
||||
{
|
||||
presence = PresenceStepper.StartWalk(presence, walks, decision.WalkTo, headingHome: false);
|
||||
}
|
||||
@@ -523,6 +538,40 @@ internal static class PresenceSystem
|
||||
return new Intent(kind, row.GoalId, row.GoalWeight, row.GoalAction);
|
||||
}
|
||||
|
||||
private static TalkPlannerContext BuildTalkContext(
|
||||
School school,
|
||||
Person person,
|
||||
bool boundToLesson,
|
||||
bool lunchOpen,
|
||||
DaySlot slot)
|
||||
{
|
||||
var opinions = person.Opinions as IReadOnlyDictionary<string, int> ?? new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var nodes = SnapshotPersonNodes(school);
|
||||
var friendPull = !boundToLesson && (slot.Kind == DaySlotKind.Break || lunchOpen);
|
||||
return new TalkPlannerContext(
|
||||
person.Id,
|
||||
opinions,
|
||||
nodes,
|
||||
person.ClassId,
|
||||
TalkCircles.HasPhone(person.Items),
|
||||
friendPull,
|
||||
school.Catalog?.BehaviorRules);
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> SnapshotPersonNodes(School school)
|
||||
{
|
||||
var nodes = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var world = school.World;
|
||||
world.Query(in People, (ref PersonIdentity identity, ref Presence presence) =>
|
||||
{
|
||||
if (presence.IsOnCampus && presence.NodeId is not null)
|
||||
{
|
||||
nodes[identity.Id] = presence.NodeId;
|
||||
}
|
||||
});
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private static SchoolClass? ClassOf(School school, Person person)
|
||||
{
|
||||
if (person.ClassId is null)
|
||||
|
||||
@@ -131,6 +131,10 @@ public sealed class School : IDisposable
|
||||
|
||||
internal Dictionary<string, string?> LoggedActivity { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
internal Dictionary<string, ActiveTalkCircle> TalkCirclesById { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
internal Dictionary<string, string> TalkCircleByPerson { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
internal void ResetDayLog()
|
||||
{
|
||||
_dayLog.Clear();
|
||||
@@ -339,6 +343,11 @@ public sealed class School : IDisposable
|
||||
PresenceSystem.Enqueue(this, id);
|
||||
}
|
||||
|
||||
foreach (var id in TalkCircleSystem.Apply(this, gameMinutes))
|
||||
{
|
||||
PresenceSystem.Enqueue(this, id);
|
||||
}
|
||||
|
||||
PersonDayLog.Sync(this);
|
||||
|
||||
if (Catalog is not null)
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
using Arch.Core;
|
||||
using HSchool.Ai;
|
||||
using HSchool.Content;
|
||||
using HSchool.People;
|
||||
|
||||
namespace HSchool.Simulation;
|
||||
|
||||
internal sealed class ActiveTalkCircle
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string ActionId { get; init; }
|
||||
|
||||
public required string TopicId { get; init; }
|
||||
|
||||
public required string NodeId { get; init; }
|
||||
|
||||
public required List<string> Members { get; init; }
|
||||
|
||||
public float RemainingMinutes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Forms 2–4 person talk circles, applies outcomes, writes topic log lines.</summary>
|
||||
internal static class TalkCircleSystem
|
||||
{
|
||||
private static readonly QueryDescription People =
|
||||
new QueryDescription().WithAll<PersonIdentity, PersonRoles, PersonTraits, PersonSkills, PersonNeeds, Presence, PersonActivity>();
|
||||
|
||||
public static bool IsInCircle(School school, string personId) =>
|
||||
school.TalkCircleByPerson.ContainsKey(personId);
|
||||
|
||||
/// <summary>Ends an active circle when duty overrides break talk (bell rang).</summary>
|
||||
public static void Interrupt(School school, string personId)
|
||||
{
|
||||
if (!school.TalkCircleByPerson.TryGetValue(personId, out var circleId)
|
||||
|| !school.TalkCirclesById.TryGetValue(circleId, out var circle))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Finish(school, circle);
|
||||
}
|
||||
|
||||
public static bool TryStart(School school, string personId, string actionId)
|
||||
{
|
||||
if (school.Catalog is null || school.Map is null || school.Roster is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TalkActions.IsTalk(actionId) || !school.Catalog.Actions.TryGetValue(actionId, out var action) || action.Abstract)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (school.TalkCircleByPerson.ContainsKey(personId))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var person = school.Roster.People.FirstOrDefault(row => row.Id.Equals(personId, StringComparison.Ordinal));
|
||||
if (person is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string? nodeId = null;
|
||||
var busy = false;
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref Presence presence, ref PersonActivity activity) =>
|
||||
{
|
||||
if (!identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
nodeId = presence.NodeId;
|
||||
busy = activity.IsActive;
|
||||
});
|
||||
|
||||
if (nodeId is null || busy)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var location = school.Map.NodeDef(nodeId);
|
||||
if (location is null || !location.Equals(action.Room, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (action.DefName.Equals(TalkActions.PhoneChat, StringComparison.Ordinal))
|
||||
{
|
||||
return TryStartPhone(school, person, nodeId, action);
|
||||
}
|
||||
|
||||
var existing = FindOpenCircle(school, nodeId, actionId);
|
||||
if (existing is not null)
|
||||
{
|
||||
return JoinCircle(school, existing, personId, action);
|
||||
}
|
||||
|
||||
return TryStartGroup(school, person, nodeId, action);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> Apply(School school, double gameMinutes)
|
||||
{
|
||||
if (gameMinutes <= 0 || school.Catalog is null || school.Roster is null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var minutes = (float)gameMinutes;
|
||||
var completed = new List<string>();
|
||||
foreach (var circle in school.TalkCirclesById.Values.ToArray())
|
||||
{
|
||||
circle.RemainingMinutes -= minutes;
|
||||
SyncActivity(school, circle);
|
||||
if (circle.RemainingMinutes > 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Finish(school, circle);
|
||||
completed.AddRange(circle.Members);
|
||||
}
|
||||
|
||||
completed.Sort(StringComparer.Ordinal);
|
||||
return completed;
|
||||
}
|
||||
|
||||
private static bool TryStartPhone(School school, Person initiator, string nodeId, ActionDef action)
|
||||
{
|
||||
if (!TalkCircles.HasPhone(initiator.Items))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var candidates = GatherCandidates(school, initiator.Id, nodeId, requirePhone: true);
|
||||
var ranked = TalkCircles.RankInvitees(initiator, candidates, school.Catalog!.BehaviorRules);
|
||||
if (ranked.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var partnerId = ranked[0];
|
||||
var partner = school.Roster!.People.First(row => row.Id.Equals(partnerId, StringComparison.Ordinal));
|
||||
if (!TalkCircles.HasPhone(partner.Items))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var topicId = TalkCircles.PickTopic(
|
||||
school.Catalog!,
|
||||
initiator,
|
||||
initiator.AgeOn(school.Clock.Time),
|
||||
Seed.Mix(school.PeopleSeed, initiator.Id, DateOnly.FromDateTime(school.Clock.Time).DayNumber, Seed.ApparelSalt + 20))
|
||||
?? school.Catalog!.Topics.Values.First(topic => !topic.Abstract).DefName;
|
||||
|
||||
var circle = new ActiveTalkCircle
|
||||
{
|
||||
Id = $"phone-{initiator.Id}-{partnerId}",
|
||||
ActionId = action.DefName,
|
||||
TopicId = topicId,
|
||||
NodeId = nodeId,
|
||||
Members = [initiator.Id, partnerId],
|
||||
RemainingMinutes = action.Minutes,
|
||||
};
|
||||
Register(school, circle, action);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryStartGroup(School school, Person initiator, string nodeId, ActionDef action)
|
||||
{
|
||||
var rules = school.Catalog!.BehaviorRules;
|
||||
var max = TalkCircles.MaxSize(action.DefName, rules, initiator.Traits, school.Catalog);
|
||||
var candidates = GatherCandidates(school, initiator.Id, nodeId, requirePhone: false);
|
||||
var ranked = TalkCircles.RankInvitees(initiator, candidates, rules);
|
||||
var members = new List<string> { initiator.Id };
|
||||
foreach (var id in ranked)
|
||||
{
|
||||
if (members.Count >= max)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
members.Add(id);
|
||||
}
|
||||
|
||||
var min = rules?.TalkCircleMin ?? 2;
|
||||
if (members.Count < min)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var topicId = TalkCircles.PickTopic(
|
||||
school.Catalog,
|
||||
initiator,
|
||||
initiator.AgeOn(school.Clock.Time),
|
||||
Seed.Mix(school.PeopleSeed, initiator.Id, DateOnly.FromDateTime(school.Clock.Time).DayNumber, Seed.ApparelSalt + 21))
|
||||
?? school.Catalog.Topics.Values.First(topic => !topic.Abstract).DefName;
|
||||
|
||||
var circle = new ActiveTalkCircle
|
||||
{
|
||||
Id = $"talk-{initiator.Id}-{nodeId}-{school.Clock.Time.Ticks}",
|
||||
ActionId = action.DefName,
|
||||
TopicId = topicId,
|
||||
NodeId = nodeId,
|
||||
Members = members,
|
||||
RemainingMinutes = action.Minutes,
|
||||
};
|
||||
Register(school, circle, action);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool JoinCircle(School school, ActiveTalkCircle circle, string personId, ActionDef action)
|
||||
{
|
||||
var rules = school.Catalog!.BehaviorRules;
|
||||
var person = school.Roster!.People.First(row => row.Id.Equals(personId, StringComparison.Ordinal));
|
||||
var max = TalkCircles.MaxSize(action.DefName, rules, person.Traits, school.Catalog);
|
||||
if (circle.Members.Count >= max || circle.Members.Contains(personId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
circle.Members.Add(personId);
|
||||
circle.Members.Sort(StringComparer.Ordinal);
|
||||
school.TalkCircleByPerson[personId] = circle.Id;
|
||||
SetActivity(school, personId, action.DefName, circle.TopicId, circle.RemainingMinutes);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ActiveTalkCircle? FindOpenCircle(School school, string nodeId, string actionId)
|
||||
{
|
||||
foreach (var circle in school.TalkCirclesById.Values)
|
||||
{
|
||||
if (circle.NodeId.Equals(nodeId, StringComparison.Ordinal)
|
||||
&& circle.ActionId.Equals(actionId, StringComparison.Ordinal)
|
||||
&& circle.RemainingMinutes > 0)
|
||||
{
|
||||
var rules = school.Catalog!.BehaviorRules;
|
||||
var max = rules?.TalkCircleMax ?? 4;
|
||||
if (circle.Members.Count < max)
|
||||
{
|
||||
return circle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<TalkCircles.Candidate> GatherCandidates(
|
||||
School school,
|
||||
string exceptId,
|
||||
string nodeId,
|
||||
bool requirePhone)
|
||||
{
|
||||
var roster = school.Roster!.People.ToDictionary(person => person.Id, StringComparer.Ordinal);
|
||||
var list = new List<TalkCircles.Candidate>();
|
||||
school.World.Query(
|
||||
in People,
|
||||
(ref PersonIdentity identity, ref PersonRoles roles, ref Presence presence, ref PersonActivity activity) =>
|
||||
{
|
||||
if (identity.Id.Equals(exceptId, StringComparison.Ordinal)
|
||||
|| presence.NodeId is null
|
||||
|| !presence.NodeId.Equals(nodeId, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!roster.TryGetValue(identity.Id, out var person))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (requirePhone && !TalkCircles.HasPhone(person.Items))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
list.Add(new TalkCircles.Candidate(
|
||||
identity.Id,
|
||||
roles.ClassId,
|
||||
!activity.IsActive && !school.TalkCircleByPerson.ContainsKey(identity.Id),
|
||||
school.TalkCircleByPerson.ContainsKey(identity.Id),
|
||||
TalkCircles.HasPhone(person.Items)));
|
||||
});
|
||||
|
||||
return list.Where(candidate => candidate.IsIdle).ToArray();
|
||||
}
|
||||
|
||||
private static void Register(School school, ActiveTalkCircle circle, ActionDef action)
|
||||
{
|
||||
school.TalkCirclesById[circle.Id] = circle;
|
||||
foreach (var member in circle.Members)
|
||||
{
|
||||
school.TalkCircleByPerson[member] = circle.Id;
|
||||
SetActivity(school, member, action.DefName, circle.TopicId, circle.RemainingMinutes);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetActivity(School school, string personId, string actionId, string topicId, float remaining)
|
||||
{
|
||||
school.World.Query(
|
||||
in People,
|
||||
(ref PersonIdentity identity, ref PersonActivity activity) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
activity = new PersonActivity(actionId, topicId, remaining);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void SyncActivity(School school, ActiveTalkCircle circle)
|
||||
{
|
||||
foreach (var member in circle.Members)
|
||||
{
|
||||
SetActivity(school, member, circle.ActionId, circle.TopicId, Math.Max(0f, circle.RemainingMinutes));
|
||||
}
|
||||
}
|
||||
|
||||
private static void Finish(School school, ActiveTalkCircle circle)
|
||||
{
|
||||
var catalog = school.Catalog!;
|
||||
var rules = catalog.BehaviorRules;
|
||||
var roster = school.Roster!;
|
||||
var people = circle.Members
|
||||
.Select(id => roster.People.First(person => person.Id.Equals(id, StringComparison.Ordinal)))
|
||||
.ToArray();
|
||||
if (!catalog.Topics.TryGetValue(circle.TopicId, out var topic))
|
||||
{
|
||||
topic = catalog.Topics.Values.First(def => !def.Abstract);
|
||||
}
|
||||
|
||||
if (!catalog.Actions.TryGetValue(circle.ActionId, out var action))
|
||||
{
|
||||
action = catalog.Actions[TalkActions.Chat];
|
||||
}
|
||||
|
||||
var hours = action.Minutes / 60f;
|
||||
var sharedLanguage = TalkCircles.SharedLanguage(catalog, people, rules) is not null;
|
||||
var language = TalkCircles.SharedLanguage(catalog, people, rules);
|
||||
|
||||
foreach (var person in people)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(action.Need)
|
||||
&& catalog.Needs.TryGetValue(action.Need, out var need))
|
||||
{
|
||||
var current = NeedOf(school, person.Id, action.Need);
|
||||
if (float.IsNaN(current))
|
||||
{
|
||||
current = need.Min;
|
||||
}
|
||||
|
||||
var next = ActionStepper.ApplyNeedGain(current, action, need);
|
||||
MutateNeed(school, person.Id, action.Need, next);
|
||||
}
|
||||
|
||||
if (catalog.Skills.TryGetValue("Communication", out var communicationSkill))
|
||||
{
|
||||
var level = SkillOf(school, person.Id, "Communication");
|
||||
var next = TalkCircles.CommunicationGain(level, communicationSkill, hours, rules);
|
||||
MutateSkill(school, person.Id, "Communication", next);
|
||||
}
|
||||
|
||||
if (language is not null
|
||||
&& catalog.Skills.TryGetValue(language, out var languageSkill)
|
||||
&& SkillOf(school, person.Id, language) < languageSkill.Range.Max)
|
||||
{
|
||||
var level = SkillOf(school, person.Id, language);
|
||||
var next = TalkCircles.LanguageGain(level, languageSkill, hours, rules);
|
||||
MutateSkill(school, person.Id, language, next);
|
||||
}
|
||||
|
||||
foreach (var other in people)
|
||||
{
|
||||
if (other.Id.Equals(person.Id, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var communication = SkillOf(school, person.Id, "Communication");
|
||||
var appearance = AppearanceOf(school, other);
|
||||
var delta = TalkCircles.OpinionDelta(
|
||||
person,
|
||||
other,
|
||||
topic,
|
||||
communication,
|
||||
sharedLanguage,
|
||||
circle.ActionId,
|
||||
appearance,
|
||||
rules,
|
||||
catalog);
|
||||
if (delta == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var current = OpinionStore.Get(person, other.Id) ?? 0;
|
||||
OpinionStore.Set(person, other.Id, current + delta);
|
||||
}
|
||||
|
||||
school.AppendDayLog(new PersonLogEvent(
|
||||
person.Id,
|
||||
school.Clock.Time,
|
||||
PersonLogTypes.TalkEnded,
|
||||
circle.TopicId));
|
||||
}
|
||||
|
||||
foreach (var member in circle.Members)
|
||||
{
|
||||
school.TalkCircleByPerson.Remove(member);
|
||||
ClearActivity(school, member);
|
||||
}
|
||||
|
||||
school.TalkCirclesById.Remove(circle.Id);
|
||||
}
|
||||
|
||||
private static ApparelIssue AppearanceOf(School school, Person person)
|
||||
{
|
||||
var schoolClass = person.ClassId is { } classId
|
||||
? school.Roster!.Classes.FirstOrDefault(row => row.Id.Equals(classId, StringComparison.Ordinal))
|
||||
: null;
|
||||
var mode = ApparelPresence.ModeAt(school, person, schoolClass);
|
||||
return ApparelDresser.CurrentIssues(school, person, mode);
|
||||
}
|
||||
|
||||
private static float NeedOf(School school, string personId, string need)
|
||||
{
|
||||
var value = float.NaN;
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref PersonNeeds needs) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
value = needs.Values.GetValueOrDefault(need, float.NaN);
|
||||
}
|
||||
});
|
||||
return value;
|
||||
}
|
||||
|
||||
private static float SkillOf(School school, string personId, string skill)
|
||||
{
|
||||
var value = 0f;
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref PersonSkills skills) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
value = skills.Values.GetValueOrDefault(skill);
|
||||
}
|
||||
});
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void MutateSkill(School school, string personId, string skill, float value)
|
||||
{
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref PersonSkills skills) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
skills.Values[skill] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void MutateNeed(School school, string personId, string need, float value)
|
||||
{
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref PersonNeeds needs) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
needs.Values[need] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void ClearActivity(School school, string personId)
|
||||
{
|
||||
school.World.Query(in People, (ref PersonIdentity identity, ref PersonActivity activity) =>
|
||||
{
|
||||
if (identity.Id.Equals(personId, StringComparison.Ordinal))
|
||||
{
|
||||
activity = PersonActivity.Idle;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user