BotGenerator/Generator/Helpers/DifficultyHelper.cs

72 lines
2.8 KiB
C#
Raw Normal View History

using Common.Models.Output;
using Common.Models.Output.Difficulty;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
2021-08-12 16:52:06 +01:00
namespace Generator.Helpers
{
public static class DifficultyHelper
{
private static readonly string[] _difficulties = new[] { "easy", "normal", "hard", "impossible" };
2021-09-05 12:27:17 +01:00
public static void AddDifficultySettings(Bot botToUpdate, List<string> difficultyFilePaths)
2021-08-12 16:52:06 +01:00
{
// Read bot setting files from assets folder that match this bots type
// Save into dictionary with difficulty as key
var difficultySettingsJsons = new Dictionary<string, DifficultySettings>();
2021-09-05 12:27:17 +01:00
foreach (var path in difficultyFilePaths.Where(x=>x.Contains($"_{botToUpdate.botType}", System.StringComparison.InvariantCultureIgnoreCase)))
2021-08-12 16:52:06 +01:00
{
var json = File.ReadAllText(path);
var serialisedObject = JsonConvert.DeserializeObject<DifficultySettings>(json);
2021-08-12 16:52:06 +01:00
var difficultyOfFile = GetFileDifficultyFromPath(path);
difficultySettingsJsons.Add(difficultyOfFile, serialisedObject);
}
2021-08-12 16:52:06 +01:00
// Find each difficulty in dictionary and save into bot
foreach (var difficulty in _difficulties)
2021-08-12 16:52:06 +01:00
{
var settings = difficultySettingsJsons.FirstOrDefault(x => x.Key.Contains(difficulty));
// No difficulty settings found, find any settings file and use that
// This is required for many bot types that only have 'normal' difficulty settings
if (settings.Key == null)
{
settings = difficultySettingsJsons.FirstOrDefault(x => x.Key != null);
}
2021-09-05 12:27:17 +01:00
SaveSettingsIntoBotFile(botToUpdate, difficulty, settings.Value);
}
2021-08-12 16:52:06 +01:00
}
private static string GetFileDifficultyFromPath(string path)
{
// Split path into parts and find the last part (filename)
// Split filename and take the first part (difficulty, easy/normal etc)
var splitPath = path.Split("\\");
return splitPath.Last().Split("_")[0];
}
2021-09-05 12:27:17 +01:00
private static void SaveSettingsIntoBotFile(Bot botToUpdate, string difficulty, DifficultySettings settings)
{
switch (difficulty)
{
case "easy":
2021-09-05 12:27:17 +01:00
botToUpdate.difficulty.easy = settings;
break;
case "normal":
2021-09-05 12:27:17 +01:00
botToUpdate.difficulty.normal = settings;
break;
case "hard":
2021-09-05 12:27:17 +01:00
botToUpdate.difficulty.hard = settings;
break;
case "impossible":
2021-09-05 12:27:17 +01:00
botToUpdate.difficulty.impossible = settings;
break;
}
}
2021-08-12 16:52:06 +01:00
}
}