Various code linting changes

This commit is contained in:
Chomp
2025-01-18 11:49:21 +00:00
parent e926379b4a
commit 566deba507
23 changed files with 213 additions and 198 deletions
+6 -4
View File
@@ -59,9 +59,11 @@ public class ItemEventCallbacks
public int? GetErrorCode(List<Warning> warnings)
{
if (warnings[0].Code != null)
return int.Parse(warnings[0]?.Code);
return int.Parse(BackendErrorCodes.UNKNOWN_ERROR.ToString());
if (warnings[0].Code is null)
{
return int.Parse(BackendErrorCodes.UNKNOWN_ERROR.ToString());
}
return int.Parse(warnings[0]?.Code);
}
}
+2 -3
View File
@@ -333,12 +333,11 @@ public class CustomizationController
/// <summary>
/// Applies a purchased suit to the players doll
/// </summary>
/// <param name="customization">Suit to apply to profile</param>
/// <param name="customisation">Suit to apply to profile</param>
/// <param name="pmcData">Profile to update</param>
private void ApplyClothingItemToProfile(CustomizationSetOption customisation, PmcData pmcData)
{
var dbSuit = _databaseService.GetCustomization()[customisation?.Id];
if (dbSuit == null)
if (!_databaseService.GetCustomization().TryGetValue(customisation?.Id, out var dbSuit))
{
_logger.Error($"Unable to find suit customisation id: {customisation?.Id}, cannot apply clothing to player profile: {pmcData.Id}");
return;
+3 -4
View File
@@ -167,11 +167,10 @@ public class DialogueController
var profile = _saveServer.GetProfile(sessionId);
// User to user messages are special in that they need the player to exist in them, add if they don't
if (
messageType == MessageType.USER_MESSAGE &&
!dialog.Users.Any((userDialog) => userDialog.Id == profile.CharacterData.PmcData.SessionId))
if (messageType == MessageType.USER_MESSAGE &&
dialog.Users.All(userDialog => userDialog.Id != profile.CharacterData.PmcData.SessionId))
{
// nullguard
// Nullguard
dialog.Users ??= [];
dialog.Users.Add( new UserDialogInfo
+1
View File
@@ -184,6 +184,7 @@ public class HideoutController
{
foreach (var poseKvP in request.Poses)
{
// Nullguard
pmcData.Hideout.MannequinPoses ??= new Dictionary<string, string>();
pmcData.Hideout.MannequinPoses[poseKvP.Key] = poseKvP.Value;
}
+7 -7
View File
@@ -84,7 +84,7 @@ public class LauncherController
{
var result = new Dictionary<string, string>();
var dbProfiles = _databaseService.GetProfiles();
foreach (var templatesProperty in typeof(ProfileTemplates).GetProperties().Where(p => p.CanWrite == true))
foreach (var templatesProperty in typeof(ProfileTemplates).GetProperties().Where(p => p.CanWrite))
{
var propertyValue = templatesProperty.GetValue(dbProfiles);
if (propertyValue == null) {
@@ -106,10 +106,10 @@ public class LauncherController
public string? Login(LoginRequestData info)
{
foreach (var sessionID in _saveServer.GetProfiles()) {
var account = _saveServer.GetProfile(sessionID.Key).ProfileInfo;
foreach (var kvp in _saveServer.GetProfiles()) {
var account = _saveServer.GetProfile(kvp.Key).ProfileInfo;
if (info.Username == account.Username) {
return sessionID.Key;
return kvp.Key;
}
}
@@ -118,8 +118,8 @@ public class LauncherController
public string Register(RegisterData info)
{
foreach (var sessionID in _saveServer.GetProfiles()) {
if (info.Username == _saveServer.GetProfile(sessionID.Key).ProfileInfo.Username) {
foreach (var kvp in _saveServer.GetProfiles()) {
if (info.Username == _saveServer.GetProfile(kvp.Key).ProfileInfo.Username) {
return "";
}
}
@@ -131,7 +131,7 @@ public class LauncherController
{
var profileId = GenerateProfileId();
var scavId = GenerateProfileId();
var newProfileDetails = new Info(){
var newProfileDetails = new Info{
ProfileId = profileId,
ScavengerId = scavId,
Aid = _hashUtil.GenerateAccountId(),
+3 -3
View File
@@ -43,12 +43,12 @@ public class LocationController
// keyed by _id location property
var locationResult = new Dictionary<string, LocationBase>();
foreach (var location in maps)
foreach (var kvp in maps)
{
var mapBase = location.Value?.Base;
var mapBase = kvp.Value?.Base;
if (mapBase == null)
{
_logger.Debug($"Map: {location} has no base json file, skipping generation");
_logger.Debug($"Map: {kvp} has no base json file, skipping generation");
continue;
}
+3 -3
View File
@@ -32,12 +32,12 @@ public class PresetController
{
var presets = _databaseService.GetGlobals().ItemPresets;
var reverse = new Dictionary<string, List<string>>();
foreach (var (id, preset) in presets)
foreach (var (key, preset) in presets)
{
if (id != preset.Id)
if (key != preset.Id)
{
this._logger.Error(
$"Preset for template tpl: '{preset.Items[0].Template} {preset.Name}' has invalid key: ({id} != {preset.Id}). Skipping"
$"Preset for template tpl: '{preset.Items[0].Template} {preset.Name}' has invalid key: ({key} != {preset.Id}). Skipping"
);
continue;
@@ -304,11 +304,11 @@ public class RepeatableQuestController
var locations = GetAllowedLocationsForPmcLevel(repeatableConfig.Locations, pmcLevel.Value);
// Populate Exploration and Pickup quest locations
foreach (var location in locations) {
if (location.Key != ELocationName.any)
foreach (var (location, value) in locations) {
if (location != ELocationName.any)
{
questPool.Pool.Exploration.Locations[location.Key] = location.Value;
questPool.Pool.Pickup.Locations[location.Key] = location.Value;
questPool.Pool.Exploration.Locations[location] = value;
questPool.Pool.Pickup.Locations[location] = value;
}
}
@@ -374,9 +374,9 @@ public class RepeatableQuestController
{
var allowedLocation = new Dictionary<ELocationName, List<string>>();
foreach (var locationKvP in locations) {
foreach (var (location, value) in locations) {
var locationNames = new List<string>();
foreach (var locationName in locationKvP.Value) {
foreach (var locationName in value) {
if (IsPmcLevelAllowedOnLocation(locationName, pmcLevel))
{
locationNames.Add(locationName);
@@ -385,7 +385,7 @@ public class RepeatableQuestController
if (locationNames.Count > 0)
{
allowedLocation[locationKvP.Key] = locationNames;
allowedLocation[location] = locationNames;
}
}
+20 -21
View File
@@ -97,9 +97,9 @@ public class TraderController
// Adjust price by traderPriceMultipler config property
if (_traderConfig.TraderPriceMultipler != 1)
{
foreach (var scheme in trader.Value?.Assort?.BarterScheme)
foreach (var kvp in trader.Value?.Assort?.BarterScheme)
{
var barterSchemeItem = scheme.Value[0][0];
var barterSchemeItem = kvp.Value[0][0];
if (barterSchemeItem != null && _paymentHelper.IsMoneyTpl(barterSchemeItem?.Template))
{
@@ -130,26 +130,28 @@ public class TraderController
/// <returns></returns>
public bool Update()
{
foreach (var trader in _databaseService.GetTables().Traders)
foreach (var (traderId, data) in _databaseService.GetTables().Traders)
{
if (trader.Key == "ragfair" || trader.Key == Traders.LIGHTHOUSEKEEPER)
continue;
if (trader.Key == Traders.FENCE)
switch (traderId)
{
if (_fenceService.NeedsPartialRefresh())
_fenceService.GenerateFenceAssorts();
case Traders.LIGHTHOUSEKEEPER:
continue;
case Traders.FENCE:
{
if (_fenceService.NeedsPartialRefresh())
_fenceService.GenerateFenceAssorts();
continue;
continue;
}
}
// Trader needs to be refreshed
if (_traderAssortHelper.TraderAssortsHaveExpired(trader.Key))
if (_traderAssortHelper.TraderAssortsHaveExpired(traderId))
{
_traderAssortHelper.ResetExpiredTrader(trader.Value);
_traderAssortHelper.ResetExpiredTrader(data);
// Reset purchase data per trader as they have independent reset times
_traderPurchasePersisterService.ResetTraderPurchasesStoredInProfile(trader.Key);
_traderPurchasePersisterService.ResetTraderPurchasesStoredInProfile(traderId);
}
}
@@ -165,18 +167,15 @@ public class TraderController
{
var traders = new List<TraderBase>();
var pmcData = _profileHelper.GetPmcProfile(sessionId);
foreach (var trader in _databaseService.GetTables().Traders)
foreach (var (traderId, data) in _databaseService.GetTables().Traders)
{
if (trader.Value.Base.Id == "ragfair")
continue;
traders.Add(_traderHelper.GetTrader(trader.Key, sessionId));
traders.Add(_traderHelper.GetTrader(traderId, sessionId));
if (pmcData?.Info != null)
_traderHelper.LevelUp(trader.Key, pmcData);
_traderHelper.LevelUp(traderId, pmcData);
}
traders.Sort((a, b) => SortByTraderId(a, b));
traders.Sort(SortByTraderId);
return traders;
}
@@ -188,7 +187,7 @@ public class TraderController
/// <returns>1,-1 or 0</returns>
private int SortByTraderId(TraderBase traderA, TraderBase traderB)
{
return string.Compare(traderA.Id, traderB.Id);
return string.CompareOrdinal(traderA.Id, traderB.Id);
}
/// <summary>
+19 -22
View File
@@ -101,16 +101,14 @@ public class BotEquipmentModGenerator
var forceSpawn = shouldForceSpawn;
// Get mod pool for the desired item
var compatibleModsPool = settings.ModPool[parentTemplate.Id];
if (compatibleModsPool is null)
if (!settings.ModPool.TryGetValue(parentTemplate.Id, out var compatibleModsPool))
{
_logger.Warning($"bot: {settings.BotData.Role} lacks a mod slot pool for item: {parentTemplate.Id} {parentTemplate.Name}");
}
// Iterate over mod pool and choose mods to add to item
foreach (var modSlotKvP in compatibleModsPool)
foreach (var (modSlotName, modPool) in compatibleModsPool)
{
var modSlotName = modSlotKvP.Key;
// Get the templates slot object from db
var itemSlotTemplate = GetModItemSlotFromDb(modSlotName, parentTemplate);
if (itemSlotTemplate is null)
@@ -138,7 +136,7 @@ public class BotEquipmentModGenerator
settings.BotEquipmentConfig
);
// Rolled to skip mod and it shouldnt be force-spawned
// Rolled to skip mod and it shouldn't be force-spawned
if (modSpawnResult == ModSpawn.SKIP && !forceSpawn)
{
continue;
@@ -151,7 +149,7 @@ public class BotEquipmentModGenerator
}
// Get pool of items we can add for this slot
var modPoolToChooseFrom = modSlotKvP.Value;
var modPoolToChooseFrom = modPool;
// Filter the pool of items in blacklist
var filteredModPool = FilterModsByBlacklist(modPoolToChooseFrom, specificBlacklist, modSlotName);
@@ -173,18 +171,17 @@ public class BotEquipmentModGenerator
compatibleModsPool[modSlotName],
parentTemplate
);
if (plateSlotFilteringOutcome.Result is Result.UNKNOWN_FAILURE or Result.NO_DEFAULT_FILTER)
switch (plateSlotFilteringOutcome.Result)
{
_logger.Debug($"Plate slot: {modSlotName} selection for armor: {parentTemplate.Id} failed: {plateSlotFilteringOutcome.Result}, skipping");
case Result.UNKNOWN_FAILURE or Result.NO_DEFAULT_FILTER:
_logger.Debug($"Plate slot: {modSlotName} selection for armor: {parentTemplate.Id} failed: {plateSlotFilteringOutcome.Result}, skipping");
continue;
}
if (plateSlotFilteringOutcome.Result == Result.LACKS_PLATE_WEIGHTS)
{
_logger.Warning(
$"Plate slot: {modSlotName} lacks weights for armor: {parentTemplate.Id}, unable to adjust plate choice, using existing data"
);
continue;
case Result.LACKS_PLATE_WEIGHTS:
_logger.Warning(
$"Plate slot: {modSlotName} lacks weights for armor: {parentTemplate.Id}, unable to adjust plate choice, using existing data"
);
break;
}
// Replace mod pool with pool of chosen plate items
@@ -1145,12 +1142,12 @@ public List<Item> GenerateModsForWeapon(string sessionId, GenerateWeaponRequest
_logger.Debug($"{request.BotData.Role} No default: {request.ModSlot} mod found for: {weaponTemplate.Name}, using existing pool");
}
// Couldnt find default in globals, use existing mod pool data
// Couldn't find default in globals, use existing mod pool data
return request.ItemModPool[request.ModSlot];
}
// Only filter mods down to single default item if it already exists in existing itemModPool, OR the default item has no children
// Filtering mod pool to item that wasnt already there can have problems;
// Filtering mod pool to item that wasn't already there can have problems;
// You'd have a mod being picked without any sub-mods in its chain, possibly resulting in missing required mods not being added
// Mod is in existing mod pool
if (request.ItemModPool[request.ModSlot].Contains(matchingModFromPreset.Template))
@@ -1162,11 +1159,11 @@ public List<Item> GenerateModsForWeapon(string sessionId, GenerateWeaponRequest
// Get an array of items that are allowed in slot from parent item
// Check the filter of the slot to ensure a chosen mod fits
var parentSlotCompatibleItems = request.ParentTemplate.Properties.Slots?.FirstOrDefault(
(slot) => slot.Name.ToLower() == request.ModSlot.ToLower()
(slot) => string.Equals(slot.Name.ToLower(), request.ModSlot.ToLower(), StringComparison.Ordinal)
)
?.Props.Filters[0].Filter;
// Mod isnt in existing pool, only add if it has no children and exists inside parent filter
// Mod isn't in existing pool, only add if it has no children and exists inside parent filter
if (
parentSlotCompatibleItems?.Contains(matchingModFromPreset.Template) ??
false &&
@@ -1208,10 +1205,10 @@ public List<Item> GenerateModsForWeapon(string sessionId, GenerateWeaponRequest
return request.ItemModPool[request.ModSlot];
}
public Item GetMatchingModFromPreset(ModToSpawnRequest request, TemplateItem weaponTemplate)
public Item? GetMatchingModFromPreset(ModToSpawnRequest request, TemplateItem weaponTemplate)
{
var matchingPreset = GetMatchingPreset(weaponTemplate, request.ParentTemplate.Id);
return matchingPreset?.Items.FirstOrDefault((item) => item?.SlotId?.ToLower() == request.ModSlot.ToLower());
return matchingPreset?.Items?.FirstOrDefault((item) => item?.SlotId?.ToLower() == request.ModSlot.ToLower());
}
/// <summary>
+7 -7
View File
@@ -416,11 +416,11 @@ public class BotGenerator
return;
}
foreach (var equipmentKvP in blacklist.Gear)
foreach (var (equipmentSlot, blacklistedTpls) in blacklist.Gear)
{
var equipmentDict = botJsonTemplate.BotInventory.Equipment[equipmentKvP.Key];
var equipmentDict = botJsonTemplate.BotInventory.Equipment[equipmentSlot];
foreach (var blacklistedTpl in equipmentKvP.Value)
foreach (var blacklistedTpl in blacklistedTpls)
{
// Set weighting to 0, will never be picked
equipmentDict[blacklistedTpl] = 0;
@@ -452,7 +452,7 @@ public class BotGenerator
// Remove blacklisted loot from loot containers
foreach (var lootContainerKey in lootContainersToFilter)
{
var prop = props.FirstOrDefault(x => x.Name.ToLower() == lootContainerKey.ToLower());
var prop = props.FirstOrDefault(x => string.Equals(x.Name, lootContainerKey, StringComparison.CurrentCultureIgnoreCase));
var propValue = (Dictionary<string, double>)prop.GetValue(botInventory.Items);
// No container, skip
@@ -462,11 +462,11 @@ public class BotGenerator
}
List<string> tplsToRemove = [];
foreach (var item in propValue)
foreach (var (key, _) in propValue)
{
if (_itemFilterService.IsLootableItemBlacklisted(item.Key))
if (_itemFilterService.IsLootableItemBlacklisted(key))
{
tplsToRemove.Add(item.Key);
tplsToRemove.Add(key);
}
}
+15 -16
View File
@@ -221,19 +221,19 @@ public class BotInventoryGenerator
// Iterate over all equipment slots of bot, do it in specifc order to reduce conflicts
// e.g. ArmorVest should be generated after TactivalVest
// or FACE_COVER before HEADWEAR
foreach (var equipmentSlotKvP in templateInventory.Equipment)
foreach (var (equipmentSlot, value) in templateInventory.Equipment)
{
// Skip some slots as they need to be done in a specific order + with specific parameter values
// e.g. Weapons
if (excludedSlots.Contains(equipmentSlotKvP.Key))
if (excludedSlots.Contains(equipmentSlot))
{
continue;
}
GenerateEquipment(new GenerateEquipmentProperties
{
RootEquipmentSlot = equipmentSlotKvP.Key,
RootEquipmentPool = equipmentSlotKvP.Value,
RootEquipmentSlot = equipmentSlot,
RootEquipmentPool = value,
ModPool = templateInventory.Mods,
SpawnChances = wornItemChances,
BotData = new BotData { Role = botRole, Level = botLevel, EquipmentRole = botEquipmentRole },
@@ -372,11 +372,10 @@ public class BotInventoryGenerator
/// <summary>
/// Remove armored rigs from parameter data
/// </summary>
/// <param name="templateEquipment">Equpiment to filter TacticalVest of</param>
/// <param name="templateEquipment">Equipment to filter TacticalVest by</param>
/// <param name="botRole">Role of bot vests are being filtered for</param>
/// <param name="allowEmptyRequest">Should the function return all rigs when 0 unarmored are found</param>
public void FilterRigsToThoseWithoutProtection(Dictionary<EquipmentSlots, Dictionary<string, double>> templateEquipment, string botRole,
bool allowEmptyResult = true)
/// <param name="allowEmptyResult">Should the function return all rigs when 0 unarmored are found</param>
public void FilterRigsToThoseWithoutProtection(Dictionary<EquipmentSlots, Dictionary<string, double>> templateEquipment, string botRole, bool allowEmptyResult = true)
{
var tacVestsWithoutArmor = templateEquipment[EquipmentSlots.TacticalVest].Where(kvp => !_itemHelper.ItemHasSlots(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
@@ -537,7 +536,7 @@ public class BotInventoryGenerator
var blacklistedMods = equipmentBlacklist[modSlot] ?? [];
var filteredMods = modPool[modSlot].Where((slotName) => !blacklistedMods.Contains(slotName));
if (filteredMods.Count() > 0)
if (filteredMods.Any())
{
modPool[modSlot] = filteredMods.ToList();
}
@@ -561,14 +560,14 @@ public class BotInventoryGenerator
string botRole, bool isPmc, Generation itemGenerationLimitsMinMax, int botLevel)
{
var weaponSlotsToFill = GetDesiredWeaponsForBot(equipmentChances);
foreach (var weaponSlot in weaponSlotsToFill)
foreach (var desiredWeapons in weaponSlotsToFill)
{
// Add weapon to bot if true and bot json has something to put into the slot
if (weaponSlot.ShouldSpawn && templateInventory.Equipment[weaponSlot.Slot].Any())
if (desiredWeapons.ShouldSpawn && templateInventory.Equipment[desiredWeapons.Slot].Any())
{
AddWeaponAndMagazinesToInventory(
sessionId,
weaponSlot,
desiredWeapons,
templateInventory,
botInventory,
equipmentChances,
@@ -586,7 +585,7 @@ public class BotInventoryGenerator
/// </summary>
/// <param name="equipmentChances">Chances bot has certain equipment</param>
/// <returns>What slots bot should have weapons generated for</returns>
public List<DesiredWeapons> GetDesiredWeaponsForBot(Chances equipmentChances) // TODO: Type fuckery { slot: EquipmentSlots; shouldSpawn: boolean }[]
public List<DesiredWeapons> GetDesiredWeaponsForBot(Chances equipmentChances)
{
var shouldSpawnPrimary = _randomUtil.GetChance100(equipmentChances.EquipmentChances["FirstPrimaryWeapon"]);
return
@@ -628,7 +627,7 @@ public class BotInventoryGenerator
Chances equipmentChances, string botRole,
bool isPmc, Generation itemGenerationWeights, int botLevel)
{
var generatedweapon = _botWeaponGenerator.GenerateRandomWeapon(
var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon(
sessionId,
weaponSlot.Slot.ToString(),
templateInventory,
@@ -639,10 +638,10 @@ public class BotInventoryGenerator
botLevel
);
botInventory.Items.AddRange(generatedweapon.Weapon);
botInventory.Items.AddRange(generatedWeapon.Weapon);
_botWeaponGenerator.AddExtraMagazinesToInventory(
generatedweapon,
generatedWeapon,
itemGenerationWeights.Items.Magazines,
botInventory,
botRole);
+35 -32
View File
@@ -684,10 +684,10 @@ public class BotLootGenerator
/// Add generated weapons to inventory as loot
/// </summary>
/// <param name="sessionId"></param>
/// <param name="botInventory">inventory to add preset to</param>
/// <param name="equipmentSlot">slot to place the preset in (backpack)</param>
/// <param name="templateInventory">bots template, assault.json</param>
/// <param name="modsChances">chances for mods to spawn on weapon</param>
/// <param name="botInventory">Inventory to add preset to</param>
/// <param name="equipmentSlot">Slot to place the preset in (backpack)</param>
/// <param name="templateInventory">Bots template, assault.json</param>
/// <param name="modChances">Chances for mods to spawn on weapon</param>
/// <param name="botRole">bots role .e.g. pmcBot</param>
/// <param name="isPmc">are we generating for a pmc</param>
/// <param name="botLevel"></param>
@@ -714,33 +714,36 @@ public class BotLootGenerator
(int)_pmcConfig.LooseWeaponInBackpackLootMinMax.Min,
(int)_pmcConfig.LooseWeaponInBackpackLootMinMax.Max
);
if (randomisedWeaponCount > 0)
{
for (var i = 0; i < randomisedWeaponCount; i++)
{
var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon(
sessionId,
chosenWeaponType,
templateInventory,
botInventory.Equipment,
modChances,
botRole,
isPmc,
botLevel
);
var result = _botGeneratorHelper.AddItemWithChildrenToEquipmentSlot(
[equipmentSlot],
generatedWeapon.Weapon[0].Id,
generatedWeapon.Weapon[0].Template,
generatedWeapon.Weapon,
botInventory,
containersIdFull
);
if (result != ItemAddedResult.SUCCESS)
{
_logger.Debug($"Failed to add additional weapon {generatedWeapon.Weapon[0].Id} to bot backpack, reason: {result.ToString()}");
}
if (randomisedWeaponCount <= 0)
{
return;
}
for (var i = 0; i < randomisedWeaponCount; i++)
{
var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon(
sessionId,
chosenWeaponType,
templateInventory,
botInventory.Equipment,
modChances,
botRole,
isPmc,
botLevel
);
var result = _botGeneratorHelper.AddItemWithChildrenToEquipmentSlot(
[equipmentSlot],
generatedWeapon.Weapon[0].Id,
generatedWeapon.Weapon[0].Template,
generatedWeapon.Weapon,
botInventory,
containersIdFull
);
if (result != ItemAddedResult.SUCCESS)
{
_logger.Debug($"Failed to add additional weapon {generatedWeapon.Weapon[0].Id} to bot backpack, reason: {result.ToString()}");
}
}
}
@@ -768,7 +771,7 @@ public class BotLootGenerator
/// <param name="botRole">Bot type</param>
/// <param name="itemSpawnLimits"></param>
/// <returns>true if item has reached spawn limit</returns>
public bool ItemHasReachedSpawnLimit(TemplateItem itemTemplate, string botRole, ItemSpawnLimitSettings itemSpawnLimits)
public bool ItemHasReachedSpawnLimit(TemplateItem itemTemplate, string botRole, ItemSpawnLimitSettings? itemSpawnLimits)
{
// PMCs and scavs have different sections of bot config for spawn limits
if (itemSpawnLimits is not null && itemSpawnLimits.GlobalLimits?.Count == 0) {
@@ -884,7 +887,7 @@ public class BotLootGenerator
return itemTemplate.Parent;
}
// parentId and tplid not found
// parentId and tplId not found
return null;
}
}
+5 -4
View File
@@ -339,13 +339,14 @@ public class BotWeaponGenerator
);
List<Item> weaponMods = [];
// TODO: Right now, preset weapons trigger a lot of warnings regarding missing ammo in magazines & such
// TODO: Preset weapons trigger a lot of warnings regarding missing ammo in magazines & such
Preset preset = null;
foreach (var presetObj in _databaseService.GetGlobals().ItemPresets)
foreach (var (_, itemPreset) in _databaseService.GetGlobals().ItemPresets)
{
if (presetObj.Value.Items[0].Template == weaponTemplate)
if (itemPreset.Items[0].Template == weaponTemplate)
{
preset = _cloner.Clone(presetObj.Value);
preset = _cloner.Clone(itemPreset);
break;
}
}
@@ -92,8 +92,13 @@ namespace Core.Generators
* @param rewardTplBlacklist OPTIONAL: list of tpls to NOT use when picking a reward
* @returns IQuestRewards
*/
public QuestRewards GenerateReward(int pmcLevel, double difficulty, string traderId, RepeatableQuestConfig repeatableConfig,
EliminationConfig eliminationConfig, BaseQuestConfig baseQuestConfig, List<string>? rewardTplBlacklist = null)
public QuestRewards GenerateReward(
int pmcLevel,
double difficulty,
string traderId,
RepeatableQuestConfig repeatableConfig,
EliminationConfig eliminationConfig,
List<string>? rewardTplBlacklist = null)
{
// Get vars to configure rewards with
var rewardParams = GetQuestRewardValues(repeatableConfig.RewardScaling, difficulty, pmcLevel);
@@ -208,7 +213,7 @@ namespace Core.Generators
// Chance of adding skill reward
if (_randomUtil.GetChance100((double)rewardParams.SkillRewardChance * 100))
{
var targetSkill = _randomUtil.GetArrayValue(baseQuestConfig.PossibleSkillRewards);
var targetSkill = _randomUtil.GetArrayValue(eliminationConfig.PossibleSkillRewards);
Reward reward = new()
{
Id = _hashUtil.Generate(),
+6 -6
View File
@@ -1434,10 +1434,10 @@ public class ItemHelper
List<Item> magazine,
TemplateItem magTemplate,
Dictionary<string, List<StaticAmmoDetails>> staticAmmoDist,
string caliber = null,
string? caliber = null,
double minSizePercent = 0.25,
string defaultCartridgeTpl = null,
TemplateItem weapon = null)
string? defaultCartridgeTpl = null,
TemplateItem? weapon = null)
{
var chosenCaliber = caliber ?? GetRandomValidCaliber(magTemplate);
@@ -1456,7 +1456,7 @@ public class ItemHelper
);
if (cartridgeTpl is null)
{
_logger.Debug($"Unable to fill item: {magazine[0].Id} {magTemplate.Name} with cartrides as none were found.");
_logger.Debug($"Unable to fill item: {magazine[0].Id} {magTemplate.Name} with cartridges, none found.");
return;
}
@@ -1523,7 +1523,7 @@ public class ItemHelper
var cartridgeCountToAdd =
desiredStackCount <= cartridgeMaxStackSize ? desiredStackCount : cartridgeMaxStackSize;
// Ensure we don't go over the max stackcount size
// Ensure we don't go over the max stackCount size
var remainingSpace = desiredStackCount - currentStoredCartridgeCount;
if (cartridgeCountToAdd > remainingSpace)
{
@@ -1545,7 +1545,7 @@ public class ItemHelper
location++;
}
// Only one cartridge stack added, remove location property as its only used for 2 or more stacks
// Only one cartridge stack added, remove location property as it's only used for 2 or more stacks
if (location == 1)
{
magazineWithChildCartridges[1].Location = null;
+5 -5
View File
@@ -8,28 +8,28 @@ public class QuestConditionHelper
{
public List<QuestCondition> GetQuestConditions(
List<QuestCondition> questConditions,
Func<QuestCondition, List<QuestCondition>> furtherFilter = null)
Func<QuestCondition, List<QuestCondition>>? furtherFilter = null)
{
return FilterConditions(questConditions, "Quest", furtherFilter);
}
public List<QuestCondition> GetLevelConditions(
List<QuestCondition> questConditions,
Func<QuestCondition, List<QuestCondition>> furtherFilter = null)
Func<QuestCondition, List<QuestCondition>>? furtherFilter = null)
{
return FilterConditions(questConditions, "Level", furtherFilter);
}
public List<QuestCondition> GetLoyaltyConditions(
List<QuestCondition> questConditions,
Func<QuestCondition, List<QuestCondition>> furtherFilter = null)
Func<QuestCondition, List<QuestCondition>>? furtherFilter = null)
{
return FilterConditions(questConditions, "TraderLoyalty", furtherFilter);
}
public List<QuestCondition> GetStandingConditions(
List<QuestCondition> questConditions,
Func<QuestCondition, List<QuestCondition>> furtherFilter = null)
Func<QuestCondition, List<QuestCondition>>? furtherFilter = null)
{
return FilterConditions(questConditions, "TraderStanding", furtherFilter);
}
@@ -37,7 +37,7 @@ public class QuestConditionHelper
protected List<QuestCondition> FilterConditions(
List<QuestCondition> questConditions,
string questType,
Func<QuestCondition, List<QuestCondition>> furtherFilter = null)
Func<QuestCondition, List<QuestCondition>>? furtherFilter = null)
{
var filteredQuests = questConditions.Where((c) => {
if (c.ConditionType == questType)
+34 -27
View File
@@ -101,31 +101,31 @@ public class QuestHelper
/// <returns>true if player level is greater than or equal to quest</returns>
public bool DoesPlayerLevelFulfilCondition(double playerLevel, QuestCondition condition)
{
if (condition.ConditionType == "Level")
if (condition.ConditionType != "Level")
{
var conditionValue = double.Parse(condition.Value.ToString());
switch (condition.CompareMethod)
{
case ">=":
return playerLevel >= conditionValue;
case ">":
return playerLevel > conditionValue;
case "<":
return playerLevel < conditionValue;
case "<=":
return playerLevel <= conditionValue;
case "=":
return playerLevel == conditionValue;
default:
_logger.Error(
_localisationService.GetText("quest-unable_to_find_compare_condition", condition.CompareMethod)
);
return false;
}
return true;
}
return true;
var conditionValue = double.Parse(condition.Value.ToString());
switch (condition.CompareMethod)
{
case ">=":
return playerLevel >= conditionValue;
case ">":
return playerLevel > conditionValue;
case "<":
return playerLevel < conditionValue;
case "<=":
return playerLevel <= conditionValue;
case "=":
return playerLevel == conditionValue;
default:
_logger.Error(
_localisationService.GetText("quest-unable_to_find_compare_condition", condition.CompareMethod)
);
return false;
}
}
/// <summary>
@@ -858,8 +858,14 @@ public class QuestHelper
*/
public List<Quest> GetClientQuests(string sessionID)
{
List<Quest> questsToShowPlayer = new List<Quest>();
List<Quest> questsToShowPlayer = [];
var profile = _profileHelper.GetPmcProfile(sessionID);
if (profile is null)
{
_logger.Error($"Profile {sessionID} not found, unable to return quests");
return [];
}
var allQuests = GetQuestsFromDb();
foreach (var quest in allQuests)
@@ -873,7 +879,7 @@ public class QuestHelper
continue;
}
// Filter out bear quests for usec and vice versa
// Filter out bear quests for USEC and vice versa
if (QuestIsForOtherSide(profile.Info.Side, quest.Id))
{
continue;
@@ -911,11 +917,12 @@ public class QuestHelper
// Check the status of each quest condition, if any are not completed
// then this quest should not be visible
bool haveCompletedPreviousQuest = true;
var haveCompletedPreviousQuest = true;
foreach (var conditionToFulfil in questRequirements)
{
// If the previous quest isn't in the user profile, it hasn't been completed or started
var prerequisiteQuest = profile.Quests.FirstOrDefault(profileQuest => (conditionToFulfil.Target as string[]).Contains(profileQuest.QId));
var questIdsToFulfil = conditionToFulfil.Target as string[] ?? [];
var prerequisiteQuest = profile.Quests.FirstOrDefault(profileQuest => questIdsToFulfil.Contains(profileQuest.QId));
if (prerequisiteQuest is null)
{
@@ -1068,7 +1075,7 @@ public class QuestHelper
* @returns QuestStatusChange array
*/
protected List<QuestStatus> GetQuestsWithDifferentStatuses(
List<QuestStatus> preQuestStatusus,
List<QuestStatus> preQuestStatuses,
List<QuestStatus> postQuestStatuses
)
{
+1 -2
View File
@@ -408,8 +408,7 @@ public class QuestRewardHelper
foreach (var target in targets)
{
// This has all the original id relations since we reset the id to the original after the splitStack
var itemsClone = new List<Item>();
itemsClone.Add(_cloner.Clone(target));
var itemsClone = new List<Item> { _cloner.Clone(target) };
// Here we generate a new id for the root item
target.Id = _hashUtil.Generate();
+3 -5
View File
@@ -1,7 +1,5 @@
using System.Reflection;
using System.Text.Json.Serialization;
using Core.Models.Eft.Common.Tables;
using Core.Models.Eft.Common;
using System.Text.Json.Serialization;
namespace Core.Models.Spt.Server;
@@ -71,7 +69,7 @@ public record Locations
{
return (Eft.Common.Location?)GetType()
.GetProperties()
.First(p => p.Name.ToLower() == _locationMappings[key].ToLower())
.First(p => string.Equals(p.Name, _locationMappings[key], StringComparison.CurrentCultureIgnoreCase))
.GetGetMethod()?
.Invoke(this, null) ?? null;
}
@@ -79,7 +77,7 @@ public record Locations
{
GetType()
.GetProperties()
.First(p => p.Name.ToLower() == key.ToLower())
.First(p => string.Equals(p.Name, key, StringComparison.CurrentCultureIgnoreCase))
.GetSetMethod()
?
.Invoke(this, [value]);
+15 -14
View File
@@ -70,46 +70,47 @@ public class BotLootCacheService
}
Dictionary<string, double> result = null;
var botRoleCache = _lootCache[botRole];
switch (lootType)
{
case LootCacheType.Special:
result = _lootCache[botRole].SpecialItems;
result = botRoleCache.SpecialItems;
break;
case LootCacheType.Backpack:
result = _lootCache[botRole].BackpackLoot;
result = botRoleCache.BackpackLoot;
break;
case LootCacheType.Pocket:
result = _lootCache[botRole].PocketLoot;
result = botRoleCache.PocketLoot;
break;
case LootCacheType.Vest:
result = _lootCache[botRole].VestLoot;
result = botRoleCache.VestLoot;
break;
case LootCacheType.Secure:
result = _lootCache[botRole].SecureLoot;
result = botRoleCache.SecureLoot;
break;
case LootCacheType.Combined:
result = _lootCache[botRole].CombinedPoolLoot;
result = botRoleCache.CombinedPoolLoot;
break;
case LootCacheType.HealingItems:
result = _lootCache[botRole].HealingItems;
result = botRoleCache.HealingItems;
break;
case LootCacheType.GrenadeItems:
result = _lootCache[botRole].GrenadeItems;
result = botRoleCache.GrenadeItems;
break;
case LootCacheType.DrugItems:
result = _lootCache[botRole].DrugItems;
result = botRoleCache.DrugItems;
break;
case LootCacheType.FoodItems:
result = _lootCache[botRole].FoodItems;
result = botRoleCache.FoodItems;
break;
case LootCacheType.DrinkItems:
result = _lootCache[botRole].DrinkItems;
result = botRoleCache.DrinkItems;
break;
case LootCacheType.CurrencyItems:
result = _lootCache[botRole].CurrencyItems;
result = botRoleCache.CurrencyItems;
break;
case LootCacheType.StimItems:
result = _lootCache[botRole].StimItems;
result = botRoleCache.StimItems;
break;
default:
_logger.Error(
@@ -161,7 +162,7 @@ public class BotLootCacheService
/// Generate loot for a bot and store inside a private class property
/// </summary>
/// <param name="botRole">bots role (assault / pmcBot etc)</param>
/// <param name="isPmc">Is the bot a PMC (alteres what loot is cached)</param>
/// <param name="isPmc">Is the bot a PMC (alters what loot is cached)</param>
/// <param name="botJsonTemplate">db template for bot having its loot generated</param>
protected void AddLootToCache(string botRole, bool isPmc, BotType botJsonTemplate)
{
+2 -2
View File
@@ -819,8 +819,8 @@ public class SeasonalEventService
/// <param name="giftKey">Key of gift to give</param>
protected void GiveGift(string playerId, string giftKey)
{
var gitftData = _giftService.GetGiftById(giftKey);
if (!_profileHelper.PlayerHasRecievedMaxNumberOfGift(playerId, giftKey, gitftData.MaxToSendPlayer ?? 5))
var giftData = _giftService.GetGiftById(giftKey);
if (!_profileHelper.PlayerHasRecievedMaxNumberOfGift(playerId, giftKey, giftData.MaxToSendPlayer ?? 5))
{
_giftService.SendGiftToPlayer(playerId, giftKey);
}
+6 -1
View File
@@ -15,4 +15,9 @@
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Gifter/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=peacefull/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tagilla/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=USEC/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Zryachiy/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>