Co-authored-by: moonheart08 <moonheart08@users.noreply.github.com>
This commit is contained in:
metalgearsloth
2022-05-19 14:44:24 +10:00
committed by GitHub
parent a6a25e30e5
commit 8d6a3ecea7
12 changed files with 133 additions and 22 deletions

View File

@@ -1,4 +1,5 @@
using Content.Shared.Dataset;
using System.Linq;
using Content.Shared.Dataset;
using Robust.Shared.Random;
namespace Content.Shared.Random.Helpers
@@ -9,5 +10,28 @@ namespace Content.Shared.Random.Helpers
{
return random.Pick(prototype.Values);
}
public static string Pick(this WeightedRandomPrototype prototype, IRobustRandom? random = null)
{
IoCManager.Resolve(ref random);
var picks = prototype.Weights;
var sum = picks.Values.Sum();
var accumulated = 0f;
var rand = random.NextFloat() * sum;
foreach (var (key, weight) in picks)
{
accumulated += weight;
if (accumulated >= rand)
{
return key;
}
}
// Shouldn't happen
throw new InvalidOperationException($"Invalid weighted pick for {prototype.ID}!");
}
}
}