Add IRobustRandom extension to get a random value from a data set (#3260)
* Add extension to pick a random element from a dataset * Add tests
This commit is contained in:
13
Content.Shared/Utility/SharedRandomExtensions.cs
Normal file
13
Content.Shared/Utility/SharedRandomExtensions.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using Content.Shared.Prototypes;
|
||||
using Robust.Shared.Random;
|
||||
|
||||
namespace Content.Shared.Utility
|
||||
{
|
||||
public static class SharedRandomExtensions
|
||||
{
|
||||
public static string Pick(this IRobustRandom random, DatasetPrototype prototype)
|
||||
{
|
||||
return random.Pick(prototype.Values);
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Content.Tests/Shared/Utility/RandomExtensionsTests.cs
Normal file
38
Content.Tests/Shared/Utility/RandomExtensionsTests.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Content.Shared.Prototypes;
|
||||
using Content.Shared.Utility;
|
||||
using NUnit.Framework;
|
||||
using Robust.Shared.IoC;
|
||||
using Robust.Shared.Prototypes;
|
||||
using Robust.Shared.Random;
|
||||
|
||||
namespace Content.Tests.Shared.Utility
|
||||
{
|
||||
[TestFixture]
|
||||
[TestOf(typeof(SharedRandomExtensions))]
|
||||
public class RandomExtensionsTests : ContentUnitTest
|
||||
{
|
||||
private const string TestDatasetId = "TestDataset";
|
||||
|
||||
private static readonly string Prototypes = $@"
|
||||
- type: dataset
|
||||
id: {TestDatasetId}
|
||||
values:
|
||||
- A";
|
||||
|
||||
[Test]
|
||||
public void RandomDataSetValueTest()
|
||||
{
|
||||
var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
|
||||
|
||||
prototypeManager.LoadFromStream(new StringReader(Prototypes));
|
||||
|
||||
var dataSet = prototypeManager.Index<DatasetPrototype>(TestDatasetId);
|
||||
var random = IoCManager.Resolve<IRobustRandom>();
|
||||
var id = random.Pick(dataSet);
|
||||
|
||||
Assert.NotNull(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user