OneNightDuel/FNAF_Server/Enemies/MovementOpportunity.cs

61 lines
No EOL
1.6 KiB
C#

using System.Diagnostics;
namespace FNAF_Server.Enemies;
public class MovementOpportunity {
public int Interval{ get; set; }
// public double ChanceDenominator;
public double MovementChance{ get; set; }
public bool Running => stopwatch.IsRunning;
public bool ConstantChance{ get; private set; }
private Stopwatch stopwatch = new();
private long stopwatchOffset = 0;
private Random random = new();
public MovementOpportunity(int intervalMs, double movementChance) {
Interval = intervalMs;
MovementChance = movementChance;
GuaranteeSuccess(false);
ConstantChance = true; // unused
}
public MovementOpportunity(int intervalMs) {
Interval = intervalMs;
GuaranteeSuccess(true);
MovementChance = 1;
}
public void Start() {
stopwatch.Start();
}
public void Stop() {
stopwatch.Stop();
}
public bool Check() {
if (stopwatch.ElapsedMilliseconds - stopwatchOffset >= Interval){
int overshoot = (int)(stopwatch.ElapsedMilliseconds - stopwatchOffset - Interval);
stopwatchOffset = stopwatch.ElapsedMilliseconds - overshoot;
// stopwatch.Restart();
return true;
}
return false;
}
public bool Roll() => roll();
private Func<bool> roll = () => true;
public bool CheckAndRoll() {
if (Check()) return Roll();
return false;
}
public void GuaranteeSuccess(bool value) {
roll = value ? () => true : () => random.NextDouble() <= MovementChance;
}
}