Add probabilistic branching helper

This commit is contained in:
Andrew Cooper
2022-04-05 05:06:17 +10:00
parent 029e27cd2c
commit aaaadc04ea
2 changed files with 122 additions and 182 deletions

View File

@@ -0,0 +1,32 @@
using Games.Common.Randomness;
namespace Basketball;
internal struct Probably
{
private readonly float _defenseFactor;
private readonly IRandom _random;
private readonly bool _done;
internal Probably(float defenseFactor, IRandom random, bool done = false)
{
_defenseFactor = defenseFactor;
_random = random;
_done = done;
}
public Probably Do(float probability, Action action)
{
if (!_done && _random.NextFloat() <= probability * _defenseFactor)
{
action.Invoke();
return new Probably(_defenseFactor, _random, true);
}
return this;
}
public Probably Or(float probability, Action action) => Do(probability, action);
public Probably Or(Action action) => Do(1f, action);
}