unit c_towers;

interface

uses
  c_mobs, defs;

type
  Tbullet = object
    X, Y : Single;
    dX, dY : Single;
    Damage : Word;
    targetX, targetY : Single;
    dead : Boolean;
    procedure Process(delta : single);
  end;

  TTower = object
    X, Y : Word;
    Damage : Word;
    speed : Single;
    lastshoot : single;
    radius : Word;
    complete : Byte;
    completes : Single;
  end;

  TSimpleTower = object(TTower)
    targetX,
    targetY : word;
    procedure process(delta : Single);
  end;

  Procedure AddTower(nX, nY : word);
  procedure AddBullet(nX, nY, ndX, ndY, tX, tY  : Single; Damage : Word);

var
  towers : array of TSimpleTower;
  bullets : array of Tbullet;

implementation

uses Math;

procedure AddTower(nX, nY : word);
begin
  SetLength(towers, length(towers)+1);
  towers[High(towers)].X:= nX;
  towers[High(towers)].Y:= nY;

  towers[High(towers)].radius:= 200;
  towers[High(towers)].speed:= 50;
  towers[High(towers)].complete:= 0;
  towers[High(towers)].completes:= 0;
end;

procedure AddBullet(nX, nY, ndX, ndY, tX, tY : Single; Damage : Word);
begin
  SetLength(bullets, length(bullets)+1);
  bullets[High(bullets)].X:= nX;
  bullets[High(bullets)].Y:= nY;


  bullets[High(bullets)].dX:= ndX;
  bullets[High(bullets)].dY:= ndY;
  bullets[High(bullets)].targetX:= tX;
  bullets[High(bullets)].targetY:= tY;
  bullets[High(bullets)].Damage:= Damage;
end;

procedure Tbullet.Process(delta : single);
var
  i : integer;
  curr : Single;
begin
  if dead then exit;

  if (abs(targetX - X) < 16) and (abs(targetY - Y) < 16) then
  begin
    pEngine.AddExplosionEx(X, Y, 0, 0, 256);
    for i:=0 to mobcount-1 do
    begin
      if abs(X - test[i].X + 16) > 64 then Continue;
      curr:= sqrt(sqr(X + 16 - test[i].X) + sqr(Y + 16 - test[i].Y));
      if (curr < 64) then
      begin
        test[i].health:= test[i].health - 64 + trunc(curr);
      end;
    end;
    dead:= true;
  end;

  X:= X + dX / (delta*10);
  Y:= Y + dY / (delta*10);
end;

procedure TSimpleTower.process(delta : Single);
var
  i : integer;
  minr : Single;
  curr : Single;
  kk : Integer;
  alpha : Single;
begin
  if completes < 255 then
  begin
    completes:= completes + delta;
    complete:= trunc(completes);
    exit;
  end;

  lastshoot:= lastshoot + delta;
  if lastshoot < speed then exit;
  lastshoot:= 0;

  kk:= MaxInt;
  minr:= MaxSingle;
  for i:=0 to mobcount-1 do
  begin
    if abs(X - test[i].X + 16) > radius then Continue;
    curr:= sqrt(sqr(X + 16 - test[i].X) + sqr(Y + 16 - test[i].Y));
    if (curr < minr) and (curr < radius) then
    begin
      minr:= curr;
      targetX:= trunc(test[i].X);
      targetY:= trunc(test[i].Y);
      kk:= i;
    end;
  end;


  if kk = MaxInt then exit;

  alpha:= ArcTan2((test[kk].Y-Y-16),(test[kk].X-X-16));

  AddBullet(X+16, Y+16, cos((alpha))*speed, sin((alpha))*speed, test[kk].X, test[kk].Y, Damage);
end;

end.
