summaryrefslogtreecommitdiff
path: root/MorgSimulator/Framework/Entity.cs
diff options
context:
space:
mode:
Diffstat (limited to 'MorgSimulator/Framework/Entity.cs')
-rw-r--r--MorgSimulator/Framework/Entity.cs85
1 files changed, 85 insertions, 0 deletions
diff --git a/MorgSimulator/Framework/Entity.cs b/MorgSimulator/Framework/Entity.cs
new file mode 100644
index 0000000..d415fdd
--- /dev/null
+++ b/MorgSimulator/Framework/Entity.cs
@@ -0,0 +1,85 @@
+using System.Collections.Generic;
+
+namespace MorgSimulator.Framework
+{
+ public abstract class Entity(int id, (int x, int y) location, (int x, int y) direction)
+ {
+ public int Id { get; set; } = id;
+ public string Type { get; set; } = string.Empty;
+ public (int x, int y) Location { get; set; } = location;
+ public (int x, int y) Direction { get; set; } = direction;
+ public bool IsAlive { get; set; } = true;
+ public IMovementStrategy MovementStrategy { get; set; } = null!;
+ public IFeedingStrategy FeedingStrategy { get; set; } = null!;
+ public List<string> PreyTypes { get; set; } = [];
+#nullable enable
+ public Entity? Prey { get; set; }
+#nullable disable
+
+ private readonly List<Entity> _observers = [];
+
+ public void Attach(Entity observer)
+ {
+ if (!_observers.Contains(observer))
+ _observers.Add(observer);
+ }
+
+ public void Detach(Entity observer)
+ {
+ _observers.Remove(observer);
+ }
+
+ public void Notify()
+ {
+ foreach (var observer in _observers)
+ observer.Update(this);
+ }
+
+ public virtual void Update(Entity subject)
+ {
+ Direction = CalculateDirectionToTarget(subject.Location);
+ }
+
+ public virtual void Move()
+ {
+ if (!IsAlive) return;
+
+ var newLocation = (Location.x + Direction.x, Location.y + Direction.y);
+
+ MovementStrategy.Move(this, newLocation);
+ Notify();
+ }
+
+ public virtual void Feed()
+ {
+ if (!IsAlive || Prey == null || !Prey.IsAlive) return;
+
+ FeedingStrategy.Feed(this, Prey);
+
+ Prey = null;
+ }
+
+ public bool CanEat(string targetType)
+ {
+ return PreyTypes.Contains(targetType);
+ }
+
+ public (int x, int y) CalculateDirectionToTarget((int x, int y) target)
+ {
+ int deltaX = target.x - Location.x;
+ int deltaY = target.y - Location.y;
+ int directionX = deltaX > 0 ? 1 : (deltaX < 0 ? -1 : 0);
+ int directionY = deltaY > 0 ? 1 : (deltaY < 0 ? -1 : 0);
+
+ return (directionX, directionY);
+ }
+
+ public double DistanceTo((int x, int y) target)
+ {
+ int deltaX = target.x - Location.x;
+ int deltaY = target.y - Location.y;
+
+ return System.Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
+ }
+ }
+}