1
0

RandomSystem.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Robust.Shared.Random;
  2. using Robust.Shared.Utility;
  3. namespace Content.Shared.Random;
  4. public sealed class RandomSystem : EntitySystem
  5. {
  6. public IBudgetEntry? GetBudgetEntry(ref float budget, ref float probSum, IList<IBudgetEntry> entries, System.Random random)
  7. {
  8. DebugTools.Assert(budget > 0f);
  9. if (entries.Count == 0)
  10. return null;
  11. // - Pick an entry
  12. // - Remove the cost from budget
  13. // - If our remaining budget is under maxCost then start pruning unavailable entries.
  14. random.Shuffle(entries);
  15. var budgetEntry = (IBudgetEntry) GetProbEntry(entries, probSum, random);
  16. budget -= budgetEntry.Cost;
  17. // Prune invalid entries.
  18. for (var i = 0; i < entries.Count; i++)
  19. {
  20. var entry = entries[i];
  21. if (entry.Cost < budget)
  22. continue;
  23. entries.RemoveSwap(i);
  24. i--;
  25. probSum -= entry.Prob;
  26. }
  27. return budgetEntry;
  28. }
  29. /// <summary>
  30. /// Gets a random entry based on each entry having a different probability.
  31. /// </summary>
  32. public IProbEntry GetProbEntry(IEnumerable<IProbEntry> entries, float probSum, System.Random random)
  33. {
  34. var value = random.NextFloat() * probSum;
  35. foreach (var entry in entries)
  36. {
  37. value -= entry.Prob;
  38. if (value < 0f)
  39. {
  40. return entry;
  41. }
  42. }
  43. throw new InvalidOperationException();
  44. }
  45. }