summaryrefslogtreecommitdiff
path: root/MorgSimulator/Framework/Simulator.cs
diff options
context:
space:
mode:
Diffstat (limited to 'MorgSimulator/Framework/Simulator.cs')
-rw-r--r--MorgSimulator/Framework/Simulator.cs69
1 files changed, 69 insertions, 0 deletions
diff --git a/MorgSimulator/Framework/Simulator.cs b/MorgSimulator/Framework/Simulator.cs
new file mode 100644
index 0000000..6e8c694
--- /dev/null
+++ b/MorgSimulator/Framework/Simulator.cs
@@ -0,0 +1,69 @@
+using System.Collections.Generic;
+
+namespace MorgSimulator.Framework
+{
+ public abstract class Simulator<T> where T : Entity
+ {
+ protected readonly List<T> _entities = [];
+ protected const double FEEDING_DISTANCE = 1.0;
+
+ public void AddEntity(T entity)
+ {
+ _entities.Add(entity);
+ }
+
+ public IEnumerable<T> GetAllEntities()
+ {
+ return _entities;
+ }
+
+ public IEntityIterator<T> CreateIterator()
+ {
+ return new EntityIterator<T>(_entities);
+ }
+
+ public void Run(int runTime)
+ {
+ for (int timeStep = 0; timeStep < runTime; timeStep++)
+ ProcessTimeStep();
+ }
+
+ protected virtual void ProcessTimeStep()
+ {
+ foreach (var entity in _entities)
+ if (entity.IsAlive)
+ {
+ FindPreyIfNeeded(entity);
+ entity.Move();
+ CheckAndFeed(entity);
+ }
+ }
+
+ protected virtual void FindPreyIfNeeded(T entity)
+ {
+ if (entity.Prey == null || !entity.Prey.IsAlive)
+ {
+ var nearestPrey = FindNearestPrey(entity);
+
+ if (nearestPrey != null)
+ {
+ nearestPrey.Attach(entity);
+
+ entity.Prey = nearestPrey as T;
+ entity.Direction = entity.CalculateDirectionToTarget(nearestPrey.Location);
+ }
+ }
+ }
+
+ protected virtual void CheckAndFeed(T entity)
+ {
+ if (entity.Prey != null && entity.Prey.IsAlive &&
+ entity.DistanceTo(entity.Prey.Location) <= FEEDING_DISTANCE)
+ entity.Feed();
+ }
+
+#nullable enable
+ protected abstract Entity? FindNearestPrey(T predator);
+#nullable disable
+ }
+}