Fix action resolution

This commit is contained in:
Andrew Cooper
2022-04-12 17:47:24 +10:00
parent c45fb59747
commit f4fa4f230b
2 changed files with 15 additions and 17 deletions

View File

@@ -13,11 +13,11 @@ internal static class IReadWriteExtensions
} }
} }
private static bool TryReadInteger(this IReadWrite io, string prompt, out int value) private static bool TryReadInteger(this IReadWrite io, string prompt, out int intValue)
{ {
var floatValue = io.ReadNumber(prompt); var floatValue = io.ReadNumber(prompt);
value = (int)floatValue; intValue = (int)floatValue;
return value == floatValue; return intValue == floatValue;
} }
public static Shot? ReadShot(this IReadWrite io, string prompt) public static Shot? ReadShot(this IReadWrite io, string prompt)

View File

@@ -14,28 +14,28 @@ internal struct Probably
private readonly IRandom _random; private readonly IRandom _random;
private readonly bool? _result; private readonly bool? _result;
internal Probably(float defenseFactor, IRandom random, bool? result = false) internal Probably(float defenseFactor, IRandom random, bool? result = null)
{ {
_defenseFactor = defenseFactor; _defenseFactor = defenseFactor;
_random = random; _random = random;
_result = result; _result = result;
} }
public Probably Do(float probability, Func<bool?> action) =>
ShouldResolveAction(probability)
? new Probably(_defenseFactor, _random, _result | Resolve(action))
: this;
public Probably Do(float probability, Action action) => public Probably Do(float probability, Action action) =>
ShouldResolveAction(probability) ShouldResolveAction(probability)
? new Probably(_defenseFactor, _random, _result | Resolve(action)) ? new Probably(_defenseFactor, _random, Resolve(action) ?? false)
: this;
public Probably Do(float probability, Func<bool> action) =>
ShouldResolveAction(probability)
? new Probably(_defenseFactor, _random, Resolve(action) ?? false)
: this; : this;
public Probably Or(float probability, Action action) => Do(probability, action); public Probably Or(float probability, Action action) => Do(probability, action);
public Probably Or(float probability, Func<bool?> action) => Do(probability, action); public Probably Or(float probability, Func<bool> action) => Do(probability, action);
public bool Or(Action action) => _result | Resolve(action) ?? false; public bool Or(Action action) => _result ?? Resolve(action) ?? false;
private bool? Resolve(Action action) private bool? Resolve(Action action)
{ {
@@ -43,10 +43,8 @@ internal struct Probably
return _result; return _result;
} }
private bool? Resolve(Func<bool?> action) => action.Invoke(); private bool? Resolve(Func<bool> action) => action.Invoke();
private readonly bool ShouldResolveAction(float probability) private readonly bool ShouldResolveAction(float probability) =>
{ _result is null && _random.NextFloat() <= probability * _defenseFactor;
return _result is null && _random.NextFloat() <= probability * _defenseFactor;
}
} }