library RGradient;

{ Variace na typ organismu "jezdí a exponenciálně se množí". Po narození si
  vytýčí bod, kamdojede atam se pak pohybuje jen o 1 políčko za krok simulace a
  to ve směru kde je nejvíc potravy. Při tom se každých 10 okének množí. Je
  agresivní a útočí na ostatní organismy.

  Životní styl tohoto organismu se zajímavě odráží v jeho grafu a v tom, jak
  vypadá oblast protředí, kterou projel. }

{$R *.RES}

uses
  Windows, SysUtils,
  OrgInterface;

const
  // BEGIN UR
  TargetX = 0;
  TargetY = 1;
  State = 2;
    sRunning = 0;
    sSleeping = 1;
  // END UR

  Radius = 20;

procedure OrgRun(Organism: IVLFOrganism); stdcall;
var
  Org: string;
  AX, AY, BX, BY: Integer;
  I, MX, MY, Max, Food: Integer;
begin
  with Organism do
  begin
    if (Age = 0) then
    begin
      AllocUR(3);
      SetColor(255, 255, 0);
      AX := X + Random(2 * Radius) - Radius;
      if AX < 0 then AX := 0;
      if AX > MaxX then AX := MaxX;
      AY := Y + Random(2 * Radius) - Radius;
      if AY < 0 then AY := 0;
      if AY > MaxY then AY := MaxY;
      SetUR(TargetX, AX);
      SetUR(TargetY, AY);
    end;

    if Mass < 20 then
    begin
      Eat(20);
      Build(20)
    end;
    if Energy < 20 then
    begin
      Eat(20);
      Digest(20);
    end;

    case UR(State) of
      sRunning:
      begin
        if UR(TargetX) < X then Move(W, 1)
        else if UR(TargetX) > X then Move(E, 1)
        else if UR(TargetY) < Y then Move(N, 1)
        else if UR(TargetY) > Y then Move(S, 1)
        else SetUR(State, sSleeping);
      end;
      sSleeping:
      begin
        MX := 0;
        MY := 0;
        Max := 0;
        for BX := - 1 to + 1 do
          for BY := - 1 to + 1 do
          begin
            Food := FoodAt(BX, BY);
            if Food > Max then
            begin
              MX := BX;
              MY := BY;
              Max := Food;
            end;
          end;

        case MX of
          - 1: Move(E, 1);
          + 1: Move(W, 1);
        end;
        case MY of
          - 1: Move(N, 1);
          + 1: Move(S, 1);
        end;

        Org := OrgAt(0, 0);
        if (Org <> '') and (Org <> Species) then
        begin
          SetColor(255, 0, 0);
          for I := 0 to ForeignAllocedURCount - 1  do
            SetForeignUR(I, Random(256));
          Eat(FoodAt(0, 0));
          Build(FoodIn div 2);
          Digest(FoodIn div 2);
          Attack;
        end
        else
          if Age mod 10 = 0 then DivCell;
      end;
    end;
  end;
end;

exports
  OrgRequiredVersion,
  OrgRun;

end.
