Deconstructed dictionaries to improve readability

This commit is contained in:
Chomp
2025-06-27 23:21:44 +01:00
parent 6f4bbe02fe
commit d2267847a8
12 changed files with 76 additions and 72 deletions
@@ -51,7 +51,7 @@ public class AchievementController(
)
{
var profilesHaveAchievement = 0;
foreach (var (profileId, profile) in profiles)
foreach (var (_, profile) in profiles)
{
if (profile.CharacterData?.PmcData?.Achievements is null)
{
@@ -209,14 +209,14 @@ public class CustomizationController(
var traders = _databaseService.GetTraders();
var result = new List<Suit>();
foreach (var trader in traders)
foreach (var (traderId, trader) in traders)
{
if (
trader.Value.Base?.CustomizationSeller is not null
&& trader.Value.Base.CustomizationSeller.Value
trader.Base?.CustomizationSeller is not null
&& trader.Base.CustomizationSeller.Value
)
{
result.AddRange(GetTraderSuits(trader.Key, sessionId));
result.AddRange(GetTraderSuits(traderId, sessionId));
}
}
@@ -127,10 +127,9 @@ public class DialogueController(
public virtual List<DialogueInfo> GenerateDialogueList(string sessionId)
{
var data = new List<DialogueInfo>();
foreach (var dialogueId in _dialogueHelper.GetDialogsForProfile(sessionId))
foreach (var (_, dialog) in _dialogueHelper.GetDialogsForProfile(sessionId))
{
var dialogueInfo = GetDialogueInfo(dialogueId.Key, sessionId);
var dialogueInfo = GetDialogueInfo(dialog, sessionId);
if (dialogueInfo is null)
{
continue;
@@ -153,6 +152,17 @@ public class DialogueController(
var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId);
var dialogue = dialogs!.GetValueOrDefault(dialogueId);
return GetDialogueInfo(dialogue, sessionId);
}
/// <summary>
/// Get the content of a dialogue
/// </summary>
/// <param name="dialogue">Dialog</param>
/// <param name="sessionId">Session Id</param>
/// <returns>DialogueInfo</returns>
public virtual DialogueInfo? GetDialogueInfo(Dialogue dialogue, string sessionId)
{
if (!dialogue.Messages.Any())
{
return null;
@@ -160,7 +170,7 @@ public class DialogueController(
var result = new DialogueInfo
{
Id = dialogueId,
Id = dialogue.Id,
Type = dialogue?.Type ?? MessageType.NpcTraderMessage,
Message = _dialogueHelper.GetMessagePreview(dialogue),
New = dialogue?.New,
@@ -555,9 +565,9 @@ public class DialogueController(
/// <param name="sessionId">Session id</param>
protected void RemoveExpiredItemsFromMessages(string sessionId)
{
foreach (var dialogueId in _dialogueHelper.GetDialogsForProfile(sessionId))
foreach (var (dialogId, _) in _dialogueHelper.GetDialogsForProfile(sessionId))
{
RemoveExpiredItemsFromMessage(sessionId, dialogueId.Key);
RemoveExpiredItemsFromMessage(sessionId, dialogId);
}
}
@@ -412,26 +412,26 @@ public class GameController(
}
// Look for effects
foreach (var effectKvP in bodyPart.Effects)
foreach (var (effectId, effect) in bodyPart.Effects)
{
// remove effects below 1, .e.g. bleeds at -1
if (effectKvP.Value.Time < 1)
if (effect.Time < 1)
{
// More than 30 minutes has passed
if (diffSeconds > 1800)
{
bodyPart.Effects.Remove(effectKvP.Key);
bodyPart.Effects.Remove(effectId);
}
continue;
}
// Decrement effect time value by difference between current time and time health was last updated
effectKvP.Value.Time -= diffSeconds;
if (effectKvP.Value.Time < 1)
effect.Time -= diffSeconds;
if (effect.Time < 1)
// Effect time was sub 1, set floor it can be
{
effectKvP.Value.Time = 1;
effect.Time = 1;
}
}
}
@@ -103,11 +103,11 @@ public class HealthController(
if (itemRemovesEffects && bodyPartToHeal.Effects is not null)
{
// Can remove effects and limb has effects to remove
foreach (var effectKvP in bodyPartToHeal.Effects)
foreach (var (effectId, _) in bodyPartToHeal.Effects)
{
// Check enum has effectType
if (!Enum.TryParse<DamageEffectType>(effectKvP.Key, out var effect))
// Enum doesnt contain this key
if (!Enum.TryParse<DamageEffectType>(effectId, out var effect))
// Enum doesn't contain this key
{
continue;
}
@@ -126,7 +126,7 @@ public class HealthController(
// Adjust limb heal amount based on if it's fixing an effect (request.count is TOTAL cost of hp resource on heal item, NOT amount to heal limb)
amountToHealLimb -= (int)(matchingEffectFromHealingItem.Cost ?? 0);
bodyPartToHeal.Effects.Remove(effectKvP.Key);
bodyPartToHeal.Effects.Remove(effectId);
}
}
@@ -965,20 +965,22 @@ public class HideoutController(
// Validate that we have a matching production
var productionDict = pmcData.Hideout.Production;
string? prodId = null;
foreach (var production in productionDict)
foreach (var (productionId, production) in productionDict)
{
// Skip undefined production objects
if (production.Value is null)
if (production is null)
{
continue;
}
if (production.RecipeId != request.RecipeId)
{
continue;
}
// Production or ScavCase
if (production.Value.RecipeId == request.RecipeId)
{
prodId = production.Key; // Set to objects key
break;
}
prodId = productionId; // Set to objects key
break;
}
// If we're unable to find the production, send an error to the client
@@ -1794,17 +1796,17 @@ public class HideoutController(
/// </summary>
public void Update()
{
foreach (var sessionID in _saveServer.GetProfiles())
foreach (var (sessionId, profile) in _saveServer.GetProfiles())
{
if (
sessionID.Value.CharacterData.PmcData.Hideout is not null
profile.CharacterData.PmcData.Hideout is not null
&& _profileActivityService.ActiveWithinLastMinutes(
sessionID.Key,
sessionId,
_hideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes
)
)
{
_hideoutHelper.UpdatePlayerHideout(sessionID.Key);
_hideoutHelper.UpdatePlayerHideout(sessionId);
}
}
}
@@ -497,10 +497,10 @@ public class InsuranceController(
_mathUtil,
_cloner
);
foreach (var attachmentTpl in weightedAttachmentByPrice)
foreach (var (itemTpl, price) in weightedAttachmentByPrice)
{
attachmentsProbabilityArray.Add(
new ProbabilityObject<string, double?>(attachmentTpl.Key, attachmentTpl.Value, null)
new ProbabilityObject<string, double?>(itemTpl, price, null)
);
}
@@ -90,12 +90,12 @@ public class LauncherController(
/// <returns></returns>
public string? Login(LoginRequestData? info)
{
foreach (var kvp in _saveServer.GetProfiles())
foreach (var (sessionId, profile) in _saveServer.GetProfiles())
{
var account = _saveServer.GetProfile(kvp.Key).ProfileInfo;
var account = profile.ProfileInfo;
if (info?.Username == account?.Username)
{
return kvp.Key;
return sessionId;
}
}
@@ -108,9 +108,9 @@ public class LauncherController(
/// <returns></returns>
public async Task<string> Register(RegisterData info)
{
foreach (var kvp in _saveServer.GetProfiles())
foreach (var (_, profile) in _saveServer.GetProfiles())
{
if (info.Username == _saveServer.GetProfile(kvp.Key).ProfileInfo?.Username)
if (info.Username == profile.ProfileInfo?.Username)
{
return "";
}
@@ -281,13 +281,12 @@ public class LauncherController(
// Find the highest versioned mod and add to results array
var result = new List<ModDetails>();
foreach (var modName in modsGroupedByName)
foreach (var (modName, modDatas) in modsGroupedByName)
{
var modDatas = modsGroupedByName[modName.Key];
var modVersions = modDatas.Select(x => x.Version);
// var highestVersion = MaxSatisfying(modVersions, "*"); ?? TODO: Node used SemVer here
var chosenVersion = modDatas.FirstOrDefault(x => x.Name == modName.Key); // && x.Version == highestVersion
var chosenVersion = modDatas.FirstOrDefault(x => x.Name == modName); // && x.Version == highestVersion
if (chosenVersion is null)
{
continue;
@@ -76,9 +76,9 @@ public class LauncherV2Controller(
/// <returns></returns>
public async Task<bool> Register(RegisterData info)
{
foreach (var session in _saveServer.GetProfiles())
foreach (var (_, profile) in _saveServer.GetProfiles())
{
if (info.Username == _saveServer.GetProfile(session.Key).ProfileInfo!.Username)
if (info.Username == profile.ProfileInfo!.Username)
{
return false;
}
@@ -150,14 +150,10 @@ public class LauncherV2Controller(
/// <returns></returns>
public Dictionary<string, AbstractModMetadata> LoadedMods()
{
var result = new Dictionary<string, AbstractModMetadata>();
foreach (var sptMod in _loadedMods)
{
result.Add(sptMod.ModMetadata.Name, sptMod.ModMetadata);
}
return result;
return _loadedMods.ToDictionary(
sptMod => sptMod.ModMetadata.Name,
sptMod => sptMod.ModMetadata
);
}
/// <summary>
@@ -205,14 +201,14 @@ public class LauncherV2Controller(
protected string? GetSessionId(LoginRequestData info)
{
foreach (var profile in _saveServer.GetProfiles())
foreach (var (sessionId, profile) in _saveServer.GetProfiles())
{
if (
info.Username == profile.Value.ProfileInfo!.Username
&& info.Password == profile.Value.ProfileInfo.Password
info.Username == profile.ProfileInfo!.Username
&& info.Password == profile.ProfileInfo.Password
)
{
return profile.Key;
return sessionId;
}
}
@@ -31,14 +31,14 @@ public class LocationController(
// keyed by _id location property
var locationResult = new Dictionary<string, LocationBase>();
foreach (var kvp in maps)
foreach (var (locationId, location) in maps)
{
var mapBase = kvp.Value.Base;
var mapBase = location.Base;
if (mapBase == null)
{
if (_logger.IsLogEnabled(LogLevel.Debug))
{
_logger.Debug($"Map: {kvp} has no base json file, skipping generation");
_logger.Debug($"Map: {locationId} has no base json file, skipping generation");
}
continue;
@@ -141,15 +141,15 @@ public class TraderController(
{
var traders = new List<TraderBase>();
var pmcData = profileHelper.GetPmcProfile(sessionId);
foreach (var (traderId, _) in databaseService.GetTables().Traders)
foreach (var (traderId, trader) in databaseService.GetTables().Traders)
{
var traderToAdd = traderHelper.GetTrader(traderId, sessionId);
if (traderToAdd is null)
traderHelper.GetTrader(traderId, sessionId);
if (trader.Base is null)
{
logger.Warning($"No trader with id: {traderId} found, skipping");
continue;
}
traders.Add(traderToAdd);
traders.Add(trader.Base);
if (pmcData?.Info != null)
{
@@ -648,27 +648,24 @@ public class BotInventoryGenerator(
)
{
var modPool = _botEquipmentModPoolService.GetModsForGearSlot(itemTpl);
foreach (var modSlot in modPool)
foreach (var (modSlot, modsForSlot) in modPool)
{
// Get blacklist
if (!equipmentBlacklist.TryGetValue(modSlot.Key, out var blacklistedMods))
if (!equipmentBlacklist.TryGetValue(modSlot, out var blacklistedMods))
{
blacklistedMods = [];
}
;
// Get mods not on blacklist
var filteredMods = modPool[modSlot.Key]
.Where(slotName => !blacklistedMods.Contains(slotName));
var filteredMods = modsForSlot.Where(slotName => !blacklistedMods.Contains(slotName));
if (!filteredMods.Any())
{
_logger.Warning(
$"Filtering {modSlot.Key} pool resulting in 0 items, skipping filter"
);
_logger.Warning($"Filtering {modSlot} pool resulting in 0 items, skipping filter");
continue;
}
modPool[modSlot.Key] = filteredMods.ToHashSet();
modsForSlot.Clear();
modsForSlot.UnionWith(filteredMods);
}
return modPool.ToDictionary();