Hi all

I´m working updating this code since 2020 but i get into a trouble where i can´t bypass two things.

I would like to know if anybody has enough experience to work out with me about this.

I would like to add two functions but i dont have enough experience to make it work so here it comes!

When player stay surrounded by enemies (dont walk) then search for more enemies 1 block near (melee case) and if is inCombat but is not walking means is a wall between enemie and player
Is this even possible to make it? Thanks

Simba Code:
program Rucoy;
{$loadlib tap}
{$loadlib LibMufasaLayer} {$DEFINE LAYER}
{$DEFINE SRL6}

 var
  _w, _h, _hh, _d: Int32;
  tx, ty, tx1, ty1, i, x, y: integer;
  monsterColor, monsterColor1: TPointArray;
  monsters, monsters1: T2DPointArray;
  monsterPoint, monsterPoint1: TPoint;
  clickPoint: TPoint;
  check1, check2 : boolean;
  enemies_dtm_array: TIntegerArray;


//noxplayer custom size: 798x482
const
  MELEE = True; //SETUP
  MAGIC = False; //SETUP
  RANGE = False; //SETUP

  //add new Tiles if you want
  TILE_BROWN       = 2504765;  //mummies?
  TILE_GRASS       = 4757576;  //crows
  TILE_DIRT_PATH   = 4749448;  //
  TILE_SKELETONS_75 = 1065293; //esqueletos
  TILE_SAND        = 10076395; //scorpions, snakes
  TILE_MUD         = 2376788;  //
  TILE_GRAVE_MUD   = 1065293;  //
  TILE_GRAVE       = 2843236;  //
  TILE_GRAVE2      = 1852744;
  TILE_STONE       = 5197647;  //
  TILE_GOBLINS     = 2504765;  //goblins??
  TILE_STONE_BLUE  = 5785654;  //vampires
  TILE_STONE_BROWN = 2702658;  //wolves
  TILE_MAZE        = 3497525;  //assassins
  TILE_LVL1        = 4757576;
  TILE_SKULLS      = 12895428;
  TILE_SKULLS1     = 11053224;
  TILE_SKULLS2     = 2500134;
  TILE_SKELLS      = 13224393;
  TILE_OWNTILE     = 14526009;
  TILE_ZOMBIES     = 2843236;
  TILE_SKEELS      = 16777215;
  TILE_SK1_STUCK   = 5785654;
  TILE_DROWS       = 4013373;
  TILE_DROWS2      = 2702658;
  TILE_SAND_LV1    = 10076395;
  TILE_WOLF        = 2649784;

  //Monsters
  RAT_PRIMARY    = 28808;
  RAT_SECONDARY  = 38584;

  WORM_PRIMARY  =  3709180;
  WORM_SECONDARY  = 2649784;

  SCORPION_PRIMARY = 5737410;
  SCORPION_SECONDARY=  10932735;

  COBRA_PRIMARY =  4897310;
  COBRA_SECONDARY= 38584;

  z_PRIMARY =  9539985;
  z_SECONDARY= 13750639;

  SKELL_PRIMARY =  13224393;
  SKELL_SECONDARY= 2500134;


  //SETUP
  PLAYER_LEVEL = 56;
  TILE_COLORS: TIntegerArray = [
                                //TILE_DROWS,
                                //TILE_DROWS2,
                                //TILE_STONE_BLUE,
                                TILE_GRAVE_MUD,
                                TILE_GRAVE2,
                                //TILE_MAZE,
                                //TILE_BROWN,
                                //TILE_STONE_BROWN,
                                //TILE_GRASS,
                                //TILE_DIRT_PATH,
                                //TILE_SAND,
                                //TILE_MUD,
                                TILE_GRAVE
                                //TILE_STONE,
                                //TILE_GOBLINS,
                                //TILE_SKELETONS_75
                                //TILE_SKULLS,
                                //TILE_SKULLS1,
                                //TILE_SKULLS2,
                                //TILE_SKELLS,
                                //TILE_OWNTILE,
                                //TILE_ZOMBIES,
                                //TILE_SKEELS,
                                //TILE_SK1_STUCK,
                                //TILE_LVL1,
                                //TILE_WOLF,
                                //TILE_SAND_LV1
                                ];


  ENEMIES_ARRAY: Array Of TIntegerArray =
                                      [
                                        [RAT_PRIMARY, RAT_SECONDARY],
                                        [SCORPION_PRIMARY, SCORPION_SECONDARY],
                                        [COBRA_PRIMARY, COBRA_SECONDARY],
                                        [WORM_PRIMARY, WORM_SECONDARY],
                                        [SKELL_PRIMARY, SKELL_SECONDARY]

                                      ];

  ENEMIES_PRIMARY_ARRAY = [
                            RAT_PRIMARY,
                            SCORPION_PRIMARY,
                            COBRA_SECONDARY,
                            WORM_SECONDARY,
                            SKELL_PRIMARY
                          ];





  PLAYER_TILE = 67;
  GRID_POINT: TPoint = [52, 72];
  MSX1 = 27;
  MSY1 = 51;
  MSX2 = 777;
  MSY2 = 501;
  MSBOX: TBox = [MSX1, MSY1, MSX2, MSY2];
  SKILL_BOX: TBox = [4, 285, 74, 355];
  MANA_POT_BOX: TBox = [4, 362, 74, 432];
  HP_POT_BOX: TBox = [4, 439, 74, 509];
  LOOT_BOX: TBox = [748, 128, 797, 177];
  MELEE_BOX: TBox = [748, 348, 797, 397];
  RANGE_BOX: TBox = [748, 404, 797, 453];
  MAGIC_BOX: TBox = [748, 460, 797, 509];

  GAME_BOX: TBox = [2, 30, 799, 511];
  BOT_LEFT_BOX: TBox = [0, 282, 78, 513];
  BOT_RIGHT_BOX: TBox = [745, 345, 801, 513];
  TOP_LEFT_BOX: TBox = [0, 0, 250, 67];
  TOP_RIGHT_BOX: TBox = [645, 0, 801, 80];
  LIMIT_BOXES: TBoxArray = [BOT_LEFT_BOX, BOT_RIGHT_BOX, TOP_LEFT_BOX, TOP_RIGHT_BOX];

  MANA_BLUE       = 16563260;
  TEXT_WHITE      = 15987699;
  TEXT_YELLOW     = 65514;
  RED_SQUARE      = 3289807;
  TEXT_RED        = 4013567;
  TEXT_GREEN      = 5171712;
  TEXT_BLUE       = 16563260;
  LOOT_HAND       = 4168184;
  HP_GREEN        = 4897310;
  HP_YELLOW       = 65514;
  HP_GRAY         = 6908265;
  DARK_OUTLINE    = 2500134;

  WAND_BROWN = 28808;
  CLOSE_LIGHT_GRAY = 13224393;
  PLAYER_POINT: TPoint = [403, 295];

  CombatType = 'melee';  //Set to either warrior, range, or mage
  UseAbility = True;     //True or False to use abilities or not.
  ColorOfMonster = z_PRIMARY;  //Enter the first color of the monster
  SecondMonsterColor = z_SECONDARY; //Enter the second color of the monster
  maxDistance = 500;  //Max distance between monster colors ( You can leave this alone )
  waitTimeBetweenClicks = 3000;  //Wait time between clicking monsters in miliseocnds.
  UseHealthPots = True;    //True or False to use Health Pots if Health gets low
  UseManaPots = True;      //True Or False to use Mana Potions When Mana is low
  UseAutoReply = False;     //Use auto reply if someone sends you a message.
  ServerNum = 5;           //Server to switch to if someone messages you (1-6 at the moment)
  reply = 'cant talk right now, sorry';  //The message sent to someone who wispers you)
  closeInterface = True; //Set to false if bot keeps opening and closing interface
  ToleranceOfMonster = 0;

{$IFDEF LAYER}

const
  NPC_COLOR = $0099FF;
  PLAYER_COLOR = $0000FF;
  VALID_TILE_COLOR = $00FF00;
  TARGET_COLOR = $FFFF00;

var
  Layer: TMufasaLayer;

procedure SetupLayer;
var
  W, H: Integer;
begin
  GetClientDimensions(W, H);
  Layer.Init(GetNativeWindow(), True, PluginPath);
  Layer.Bitmap.Init(Client.getMBitmaps());
  Layer.Bitmap.SetPersistentMemory(PtrUInt(Layer.GetBitmapPtr(W, H)), W, H);
  AddOnTerminate('FreeLayer');
end;

procedure FreeLayer;
begin
  Layer.Bitmap.Free;
  Layer.Free;
end;

function MsToTime(MS: Integer): string;
var
  STA: array [0..5] of TVariantArray;
  Time: array of Integer;
  i, t, tl: Integer;
begin
  Result := '';

  tl := 3;
  t := 2;
  SetLength(Time,tl);
  ConvertTime(MS, Time[0], Time[1], Time[2]);

  STA[3] := [':', ':', '', True, 2];

  for i := 0 to t do
    if (Time[i] > 0) or (STA[3][tl]) or (i = t) then
      Result := Result + PadZ(IntToStr(Time[i]), STA[3][tl+1]) + STA[3][i];
end;

procedure DrawClear();
begin
  Layer.Bitmap.DrawClear(0);
  Layer.Bitmap.DrawSystemText(MsToTime(GetTimeRunning()), 'Arial', 20, [344, 0], False, $FFFFFF);
end;

procedure DrawTPA(const TPA: TPointArray; Color: Int32; Clear: Boolean = True);
begin
  if (Length(TPA) < 1) then Exit;
  if Clear then DrawClear();
  Layer.Bitmap.DrawTPA(TPA, Color);
end;

procedure DrawATPA(const ATPA: T2DPointArray; Clear: Boolean = True);
var
  i: Int32;
  Colors: TIntegerArray;
begin
  if (Length(ATPA) < 1) then Exit;
  if Clear then DrawClear();
  SetLength(Colors, Length(ATPA));
  for i := 0 to High(Colors) do Colors[i] := HSLToColor(i * 69 / Length(Colors), 100, 50);
  Layer.Bitmap.DrawATPA(ATPA, Colors);
end;

procedure DrawATPA(const ATPA: T2DPointArray; Color: Int32; Clear: Boolean = True); Overload;
var
  i: Int32;
  Colors: TIntegerArray;
begin
  if (Length(ATPA) < 1) then Exit;
  if Clear then DrawClear();
  SetLength(Colors, Length(ATPA));
  for i := 0 to High(Colors) do Colors[i] := Color;
  Layer.Bitmap.DrawATPA(ATPA, Colors);
end;

procedure DrawBoxes(const Boxes: TBoxArray; Fill: Boolean = False; Clear: Boolean = True);
var
  i: Int32;
  ATPA: T2DPointArray;
begin
  if (Length(Boxes) < 1) then Exit;
  SetLength(ATPA, Length(Boxes));
  for i := 0 to High(ATPA) do
  begin
    if Fill then
      ATPA[i] := TPAFromBox(Boxes[i]) else
      ATPA[i] := EdgeFromBox(Boxes[i]);
  end;
  DrawATPA(ATPA, Clear);
end;

procedure DrawBoxes(const Boxes: TBoxArray; Color: Int32; Fill: Boolean = False; Clear: Boolean = True); Overload;
var
  i: Int32;
  ATPA: T2DPointArray;
begin
  if (Length(Boxes) < 1) then Exit;
  SetLength(ATPA, Length(Boxes));
  for i := 0 to High(ATPA) do
  begin
    if Fill then
      ATPA[i] := TPAFromBox(Boxes[i]) else
      ATPA[i] := EdgeFromBox(Boxes[i]);
  end;
  DrawATPA(ATPA, Color, Clear);
end;

{$ENDIF LAYER}

function BoxWidth(const B: TBox): Int32;
begin
  Result := B.X2 - B.X1 + 1;
end;

function BoxHeight(const B: TBox): Int32;
begin
  Result := B.Y2 - B.Y1 + 1;
end;

function BoxArea(const B: TBox): Int32;
begin
  Result := BoxWidth(B) * BoxHeight(B);
end;

function GridBox(Slot, Columns, Rows, w, h, dX, dY: Int32; StartPoint: TPoint): TBox;
begin
  if (Slot > (Columns * Rows)) then
  begin
    WriteLn('GridBox: Invalid Slot: ', Slot);
    Exit;
  end;

  Result.X1 := (StartPoint.x + ((Slot mod Columns) * dX) - (w div 2));
  Result.Y1 := (StartPoint.y + ((Slot div Columns) * dY) - (h div 2));
  Result.X2 := (Result.X1 + w);
  Result.Y2 := (Result.Y1 + h);
end;

function Grid(Columns, Rows, w, h, dX, dY: Int32; StartPoint: TPoint): TBoxArray;
var
  i: Int32;
begin
  SetLength(Result, (Columns * Rows));

  for i := 0 to High(Result) do
    Result[i] := GridBox(i, Columns, Rows, w, h, dX, dY, StartPoint);
end;

//Éste método configura el Layer del NoxPlayer de acuerdo al tamaño del ancho y
//largo
procedure GetAndSet();
var
  pp: TSysProcArr;
  i, w, h: Int32;
begin
  GetClientDimensions(w, h);
  pp := Client.GetIOManager.GetProcesses;


  for i := 0 to High(pp) do
  begin
    Writeln('Proceses '+ pp[i].Title);
    if Pos('NoxPlayer', pp[i].Title) then
    begin
      SetTarget(pp[i]);
      _hh := pp[i].Handle;
      GetClientDimensions(_w, _h);
      if ((w = _w) and (h = _h)) then
      begin
        WriteLn('Do not target the game directly!');
        TerminateScript;
      end;
      {$IFDEF LAYER} SetupLayer(); {$ENDIF LAYER}
      Exit();
    end;
  end;
  WriteLn('game not found');
  TerminateScript();
end;

procedure Wait(const w1, w2: UInt32) Overload;
begin
  Wait(Random(w1, w2));
end;

procedure Mouse(P: TPoint; Button: Byte = 0);
begin
  tap(_hh, P, Random(44, 88));
end;

procedure MouseBox(B: TBox; Button: Byte = 0);
begin
  Mouse(Point(B.X1 + Random(B.X2 - B.X1), B.Y1 + Random(B.Y2 - B.Y1)), Button);
end;

procedure TBox.Edit(const x1_, y1_, x2_, y2_: Int32);
begin
  Self.X1 := Self.X1 + x1_;
  Self.Y1 := Self.Y1 + y1_;
  Self.X2 := Self.X2 + x2_;
  Self.Y2 := Self.Y2 + y2_;
end;

procedure TBox.Shrink(const Size: Int32);
begin
  Self.Edit(+Size, +Size, -Size, -Size);
end;

procedure TBox.Offset(const p: TPoint);
begin
  Self.X1 := Self.X1 + p.x;
  Self.X2 := Self.X2 + p.x;
  Self.Y1 := Self.Y1 + p.y;
  Self.Y2 := Self.Y2 + p.y;
end;

function ShrinkBox(const B: TBox; ShrinkBy: Int32): TBox;
begin
  Result.X1 := B.X1 + ShrinkBy;
  Result.Y1 := B.Y1 + ShrinkBy;
  Result.X2 := B.X2 - ShrinkBy;
  Result.Y2 := B.Y2 - ShrinkBy;
end;

function ShrinkBoxes(const BB: TBoxArray; ShrinkBy: Int32): TBoxArray;
var
  i: Int32;
begin
  SetLength(Result, Length(BB));
  for i := 0 to High(Result) do Result[i] := ShrinkBox(BB[i], ShrinkBy);
end;

procedure IncludePointsBox(var TPA: TPointArray; const B: TBox);
begin
  FilterPointsBox(TPA, B.X1, B.Y1, B.X2, B.Y2);
end;

procedure ExcludePointsBox(var TPA: TPointArray; const B: TBox);
var
  Temp: TPointArray;
begin
  Temp := TPAFromBox(B);
  TPA := ClearTPAFromTPA(TPA, Temp);
end;

function IsDisconnected(): Boolean;
begin
  Result := (InRange(CountColor(TEXT_WHITE, 0, 0, _w-1, _h-1), 2300, 2350) and
             InRange(CountColor(0, 0, 0, _w-1, _h-1), 382000, 383000));
end;

function IsMagic(): Boolean;
begin
  Result := (CountColor(WAND_BROWN, 745, 460, _w-1, _h-1) > 44);
end;

function GetTiles(): TBoxArray;
begin
  Result := Grid(15, 9, 50, 50, 50, 50, GRID_POINT);
end;

function GetTile(Slot: Int32): TBox;
begin
  if (not InRange(Slot, 0, 134)) then Exit;
  Result := GridBox(Slot, 15, 9, 50, 50, 50, 50, GRID_POINT);
end;

function GetTiles(const Tiles: TIntegerArray): TBoxArray; Overload;
var
  i: Int32;
begin
  if (Length(Tiles) < 1) then Exit;
  SetLength(Result, Length(Tiles));
  for i := 0 to High(Result) do Result[i] := GetTile(Tiles[i]);
end;

function PlayerBox(): TBox;
begin
  Result := GetTile(PLAYER_TILE);
end;

function PointToTile(p: TPoint): Int32;
var
  i: Int32;
  BB: TBoxArray;
begin
  Result := -1;
  BB := GetTiles();
  for i := 0 to High(BB) do if PointInBox(p, BB[i]) then Exit(i);
end;

function GetTileRow(Slot: Int32): Int32;
begin
  Result := Slot div 15;
end;

function GetTileCol(Slot: Int32): Int32;
begin
  Result := Slot mod 15;
end;

function TileDist(t1, t2: Int32): Int32;
var
  r1, r2, c1, c2: Int32;
begin
  r1 := GetTileRow(t1);
  r2 := GetTileRow(t2);
  c1 := GetTileCol(t1);
  c2 := GetTileCol(t2);
  Result := max(r1, r2) - min(r1, r2) + max(c1, c2) - min(c1, c2);
end;

function IsInRange(t: Int32): Boolean;
begin
  Result := (TileDist(PLAYER_TILE, t) <= 4);
end;

function InIntArrayI(const TIA: TIntegerArray; num: Int32): Int32;
var
  i: Int32;
begin
  Result := -1;
  if inIntArray(TIA, num) then for i := 0 to High(TIA) do if (TIA[i] = num) then Exit(i);
end;

//procedure ClickMelee();
//begin
  //MouseBox(MELEE_BOX);
//end;

//procedure ClickRange();
//begin
  //MouseBox(RANGE_BOX);
//end;

//procedure ClickMagic();
//begin
  //MouseBox(MAGIC_BOX);
//end;

function InCombat(out Tile: Int32): Boolean;
var
  i: Int32;
  p: TPoint;
  B: TBox;
  TPA: TPointArray;
  ATPA, Temp: T2DPointArray;
begin
  if FindColors(TPA, RED_SQUARE, MSX1, MSY1, MSX2, MSY2) then
  begin
    ExcludePointsBox(TPA, [0, 0, 255, 75]);
    ExcludePointsBox(TPA, [0, 285, 75, _h-1]);
    ExcludePointsBox(TPA, PlayerBox());
    ATPA := ClusterTPA(TPA, 20);
    FilterTPAsBetween(ATPA, 0, 50);
    if (Length(ATPA) < 1) then Exit;

    for i := 0 to High(ATPA) do
    begin
      p := MiddleTPA(ATPA[i]);
      Tile := PointToTile(p);
      B := [p.x, p.y, p.x, p.y];
      B.Shrink(-20);
      ExcludePointsBox(ATPA[i], B);
      if InRange(Length(ATPA[i]), 100, 800) then
      begin
        {$IFDEF LAYER} DrawTPA(ATPA[i], TARGET_COLOR, True); {$ENDIF LAYER}
        Exit(True);
      end;
    end;
  end;
end;

function Loot(): Boolean;
begin
  if (CountColor(LOOT_HAND, LOOT_BOX.X1, LOOT_BOX.Y1, LOOT_BOX.X2, LOOT_BOX.Y2) > 444) then
    MouseBox(LOOT_BOX);
end;

function Close(): Boolean;
begin
  if InRange(CountColor(CLOSE_LIGHT_GRAY, 745, 35, _w-1, 85), 333, 444) then
  begin
    MouseBox([757, 36, 790, 64]);
    Exit(True);
  end;
end;

function IsWalking(): Boolean
var
  i, BMPA, BMPB: Int32;
begin
  BMPA := BitmapFromClient(0, 0, _w-1, _h-1);
  Wait(122);
  BMPB := BitmapFromClient(0, 0, _w-1, _h-1);
  Result := (CalculatePixelShift(BMPA, BMPB, [0, 0, _w-1, _h-1]) > 12345);
  FreeBitmap(BMPA);
  FreeBitmap(BMPB);
end;

function WalkWait(const Tile: Int32): Boolean;
begin
  Writeln('Moviendose');
  Wait(TileDist(PLAYER_TILE, Tile) * (420 - PLAYER_LEVEL));
end;

function IsMelee(): Boolean;
begin
  Result := (CountColor(13417668, 750, 350, _w-1, _h-1) = 48);
end;

function IsRange(): Boolean;
begin
  Result := (CountColor(13092807, 750, 350, _w-1, _h-1) = 108);
end;

procedure ClickTile(var B: TBox);
begin
  B.Shrink(2);
  MouseBox(B);
end;

procedure ClickTile(Slot: Int32); overload;
var
  B: TBox;
begin
  if (Slot = PLAYER_TILE) then Exit;
  B := GetTile(Slot);
  ClickTile(B);
end;

function OccupiedTile(B: TBox): Boolean;
begin
  B.Shrink(5);
  Result := (CountColor(DARK_OUTLINE, B.X1, B.Y1, B.X2, B.Y2) > 175);
end;

function OccupiedTile(const Tile: Int32): Boolean; overload;
begin
  Result := OccupiedTile(GetTile(Tile));
end;

function ValidTileColor(const B: TBox): Boolean;
var
  i, c: Int32;
begin
  for i := 0 to High(TILE_COLORS) do c += CountColor(TILE_COLORS[i], B.X1, B.Y1, B.X2, B.Y2);
  Result := (c > 9);
end;

function ValidTileColor(Slot: Int32): Boolean; overload;
begin
  if InRange(Slot, 0, 134) then Result := ValidTileColor(GetTile(Slot));
end;

function ValidTile(B: TBox): Boolean;
var
  i, c, a: Int32;
begin
  B.Shrink(5);
  a := BoxArea(B);
  for i := 0 to High(TILE_COLORS) do c += CountColor(TILE_COLORS[i], B.X1, B.Y1, B.X2, B.Y2);
  Result := ((c / a) > 0.60);
end;

function ValidTile(Slot: Int32): Boolean; overload;
begin
  if InRange(Slot, 0, 134) then Result := ValidTile(GetTile(Slot));
end;

function GetAdjacentTileSlots(const Tile: Int32): TIntegerArray;
var
  Row, Col: Int32;
begin
  if (not InRange(Tile, 0, 134)) then
  begin
    WriteLn('GetAdjacentTileSlots: tile not in range');
    Exit;
  end;
  Col := GetTileCol(Tile);
  Row := GetTileRow(Tile);

  if InRange(Col, 0, 13) then Result := Result + (Tile + 1);
  if InRange(Col, 1, 14) then Result := Result + (Tile - 1);

  if InRange(Row, 0, 7) then Result := Result + (Tile + 15);
  if InRange(Row, 1, 8) then Result := Result + (Tile - 15);
end;

function GetAdjacentTileBoxes(const Tile: Int32): TBoxArray;
var
  i: Int32;
  Tiles: TIntegerArray;
begin
  Tiles := GetAdjacentTileSlots(Tile);
  if (Length(Tiles) < 1) then Exit;
  SetLength(Result, Length(Tiles));
  for i := 0 to High(Tiles) do Result[i] := GetTile(Tiles[i]);
end;

{procedure ClickSkill_Box();
begin
  MouseBox(SKILL_BOX);
end;   }


procedure ClickMana_Box();
begin
  MouseBox(MANA_POT_BOX);
end;

function HasMPot(): Boolean;
begin
  Result := (CountColor(16563260, 4, 394, 75, 463) >9 );
end;

procedure ClickMPot();
begin
  MouseBox(MANA_POT_BOX);
end;

function GetManaPercent(): Int32;
var
  TPA: TPointArray;
begin
  Result := 100 * CountColor(MANA_BLUE, 4, 55, 250, 61) div 1470;
end;


function SlotFromCR(const Col, Row: Int32): Int32;
begin
  Result := (Row * 15) + Col;
end;

function GetTileTPA(const c1, r1, c2, r2: Int32): TPointArray;
var
  minR, minC, maxR, maxC, n, i, j: Int32;
begin
  minR := min(r1, r2); maxR := max(r1, r2);
  minC := min(c1, c2); maxC := max(c1, c2);
  SetLength(Result, (maxR-minR+1)*(maxC-minC+1));
  for i := minC to maxC do
  begin
    for j := minR to maxR do
    begin
      Result[n] := [i, j];
      Inc(n);
    end;
  end;
end;

function GetTileTPA(const t1, t2: Int32): TPointArray; overload;
begin
  Result := GetTileTPA(GetTileCol(t1), GetTileRow(t1), GetTileCol(t2), GetTileRow(t2));
end;

function GetValidTileNear(const Slot: Int32): Int32;
var
  i, x, y: Int32;
  B: TBox;
  Tiles: TPointArray;
begin
  Tiles := GetTileTPA(PLAYER_TILE, Slot);
  SortTPAFrom(Tiles, [GetTileCol(Slot), GetTileRow(Slot)]);
  for i := 0 to High(Tiles) do
  begin
    B := GetTile(SlotFromCR(Tiles[i].x, Tiles[i].y));
    B.Shrink(4);
    if (ValidTile(SlotFromCR(Tiles[i].x, Tiles[i].y)) and
        (not FindColor(x, y, RED_SQUARE, B.X1, B.Y1, B.X2, B.Y2))) then
      Exit(SlotFromCR(Tiles[i].x, Tiles[i].y));
  end;
end;

function GetHpBarTPA(): TPointArray;
var
  TPA, TPA2: TPointArray;
begin
  FindColors(TPA, HP_GREEN, MSX1, MSY1, MSX2, MSY2);
  //if FindColors(TPA2, HP_YELLOW, MSX1, MSY1, MSX2, MSY2) then TPA := CombineTPA(TPA, TPA2); //
  if FindColors(TPA2, HP_GRAY, MSX1, MSY1, MSX2, MSY2) then TPA := CombineTPA(TPA, TPA2);
  if FindColors(TPA2, RED_SQUARE, MSX1, MSY1, MSX2, MSY2) then TPA := CombineTPA(TPA, TPA2);
  ExcludePointsBox(TPA, [375, 240, 425, 250]);
  if (Length(TPA) < 1) then Exit;
  Result := CopyTPA(TPA);
end;

function GetHpBarATPA(): T2DPointArray;
var
  i: Int32;
  B: TBox;
  Temp: T2DPointArray;
begin
  Temp := ClusterTPA(GetHpBarTPA, 1);
  FilterTPAsBetween(Temp, 250, 9000);
  FilterTPAsBetween(Temp, 0, 50);
  if (Length(Temp) < 1) then Exit;
  for i := 0 to High(Temp) do
  begin
    B := GetTPABounds(Temp[i]);
    if (InRange(B.Y2 - B.Y1, 3, 6) and InRange(B.X2 - B.X1, 40, 50)) then Result := Result + Temp[i];
  end;
end;

function GetPlayerTileSlots(const ATPA: T2DPointArray): TIntegerArray;
var
  i, Tile: Int32;
  P: TPoint;
  B: TBox;
begin
  for i := 0 to High(ATPA) do
  begin
    B := GetTPABounds(ATPA[i]);
    if ((CountColor(TEXT_BLUE, B.X1, B.Y1 - 12, B.X2, B.Y2) +
         CountColor(TEXT_GREEN, B.X1, B.Y1 - 12, B.X2, B.Y2) +
         CountColor(TEXT_RED, B.X1, B.Y1 - 12, B.X2, B.Y2)) > 70) then
    begin
      P := MiddleTPA(ATPA[i]);
      P.Y += 10;
      Tile := PointToTile(P);
      if (InRange(Tile, 0, 134) and (Tile <> PLAYER_TILE)) then Result := Result + Tile;
    end;
  end;
end;

function GetPlayerTileBoxes(const ATPA: T2DPointArray): TBoxArray;
var
  i: Int32;
  Tiles: TIntegerArray;
begin
  Tiles := GetPlayerTileSlots(ATPA);
  if (Length(Tiles) < 1) then Exit;
  SetLength(Result, Length(Tiles));
  for i := 0 to High(Tiles) do Result[i] := GetTile(Tiles[i]);
end;

function IsTraining(): Boolean;
begin
  Result := (CountColor(TEXT_RED, 257, 357, 542, 375) > 1000);
end;

//Éste método trae donde puedo caminar.
function GetWalkableTileSlots(): TIntegerArray;
var
  i, j, h: Int32;
  TileSlots, IgnoreSlots: TIntegerArray;
  X, Y: integer;
begin
  Writeln('Entro a GetWalkableTileSlots');
  TileSlots := GetAdjacentTileSlots(PLAYER_TILE);
  if (Length(TileSlots) < 1) then Exit;

  for j := 0 to High(TileSlots) do
    if (ValidTile(TileSlots[j]))
    then
      Result := Result + TileSlots[j] else
      IgnoreSlots := IgnoreSlots + TileSlots[j];

  IgnoreSlots := IgnoreSlots + PLAYER_TILE;

  h := High(Result);
  for i := 0 to h do
  begin
    TileSlots := GetAdjacentTileSlots(Result[i]);
    if (Length(TileSlots) < 1) then Continue;
    for j := 0 to High(TileSlots) do
    begin
      if InIntArray(CombineIntArray(Result, IgnoreSlots), TileSlots[j]) then
        Continue;
      for j := 0 to High(TileSlots) do
        if (ValidTile(TileSlots[j]) and (not OccupiedTile(TileSlots[j]))) then
          Result := Result + TileSlots[j] else
          IgnoreSlots := IgnoreSlots + TileSlots[j];
      h := High(Result);
    end;
  end;
  {$IFDEF LAYER} DrawBoxes(ShrinkBoxes(GetTiles(Result), 1), VALID_TILE_COLOR, False, False); {$ENDIF LAYER}
end;

function GetWalkableTileBoxes(): TBoxArray;
var
  i: Int32;
  Slots: TIntegerArray;
begin
  Slots := GetWalkableTileSlots();
  if (Length(Slots) < 1) then Exit;
  SetLength(Result, Length(Slots));
  for i := 0 to High(Result) do Result[i] := GetTile(Slots[i]);
end;

procedure RandomWalk();
var
  r: Int32;
  Tiles: TIntegerArray;
begin
  Tiles := GetWalkableTileSlots();
  if (Length(Tiles) < 1) then Exit;
  r := Tiles[Random(High(Tiles))];
  {$IFDEF LAYER} DrawBoxes([GetTile(r)], VALID_TILE_COLOR, True, False); {$ENDIF LAYER}
  ClickTile(r);
  //ClickClosestNPC();
  WalkWait(r);

end;



procedure lookForMonsters;
var
  randomside: Integer;
  mousex, mousey: Integer;
begin
  GetMousePos(mousex, mousey);
  Writeln('Colour is ' + IntToStr(ColorOfMonster));
  Mouse(Point(RandomRange(150, 1000), RandomRange(139, 600)),0);
   wait(100 + random(100));
  //ClickMouse(RandomRange(150, 1000), RandomRange(139, 600), mouse_Left);
  wait(3000 + random(100));
  if (closeInterface = true) then
  //checkForHealthBar;
  if (UseAutoReply = true) then
  //checkformessages;
end



function FindEnemiesAndAttack() : TIntegerArray;
var
  x, y, x1, y1, j, boxesCount, myRandom,countMonsters: integer;
  Health, testTPointArray: TPointArray;
  distance: Integer;
  TileSlots: TIntegerArray;
  BoxesToCheck: TBoxArray;
  myTBox, MoveTBox: TBox;
  findPrimary, findSecondary: Boolean;
  actualCombatTile: Int32;
  isInCombat: Boolean;
  middleX, middleY : Int32;

begin


  TileSlots := GetWalkableTileSlots();

    BoxesToCheck := GetTiles(TileSlots);

    for boxesCount := 0 to High(BoxesToCheck)
    do
    begin
       myTBox := BoxesToCheck[boxesCount];

       for countMonsters := 0 to High(enemies_dtm_array)
       do
       begin
        { findPrimary := FindColorsTolerance(
                      testTPointArray,
                      ENEMIES_PRIMARY_ARRAY[countMonsters],
                      myTBox.X1,
                      myTBox.Y1,
                      myTBox.X2,
                      myTBox.Y2,
                      0); }

           findPrimary := FindDTM(enemies_dtm_array[countMonsters],x,y,myTBox.X1, myTBox.Y1, myTBox.X2, myTBox.Y2);
           if(findPrimary)
           then
           begin
           //Wait(1000);
           Writeln('Encontre '+ IntToStr(enemies_dtm_array[countMonsters]));
           break;
           end;
       end;


       if(findPrimary)
       then
        begin
            middleX :=  Trunc((myTBox.X1 + myTBox.X2)/2);
            middleY :=  Trunc((myTBox.Y1 + myTBox.Y2)/2);
            Mouse(Point(middleX, middleY),0);
            Wait(1000);
            isInCombat := InCombat(actualCombatTile);
           while(isInCombat)
           do
           begin
            Writeln('Atacando el enemigo');
            isIncombat:= InCombat(actualCombatTile);
           end;

        end;
    end;

     myRandom := Random(1,High(BoxesToCheck));
     MoveTBox :=   BoxesToCheck[myRandom];

     middleX :=  Trunc((MoveTBox.X1 + MoveTBox.X2)/2);
     middleY :=  Trunc((MoveTBox.Y1 + MoveTBox.Y2)/2);

     Mouse(Point(middleX, middleY),0);
     Wait(1000);
     while(IsWalking())
     do
     begin
      Writeln('Esperando llegar a destino')
       for boxesCount := 0 to High(BoxesToCheck)
    do
    begin
       myTBox := BoxesToCheck[boxesCount];

       for countMonsters := 0 to High(enemies_dtm_array)
       do
       begin
        { findPrimary := FindColorsTolerance(
                      testTPointArray,
                      ENEMIES_PRIMARY_ARRAY[countMonsters],
                      myTBox.X1,
                      myTBox.Y1,
                      myTBox.X2,
                      myTBox.Y2,
                      0); }

           findPrimary := FindDTM(enemies_dtm_array[countMonsters],x,y,myTBox.X1, myTBox.Y1, myTBox.X2, myTBox.Y2);
           if(findPrimary)
           then
           begin
           //Wait(1000);
           Writeln('Encontre '+ IntToStr(enemies_dtm_array[countMonsters]));
           break;
           end;
       end;


       if(findPrimary)
       then
        begin
            middleX :=  Trunc((myTBox.X1 + myTBox.X2)/2);
            middleY :=  Trunc((myTBox.Y1 + myTBox.Y2)/2);
            Mouse(Point(middleX, middleY),0);
            Wait(1000);
            isInCombat := InCombat(actualCombatTile);
           while(isInCombat)
           do
           begin
            Writeln('Atacando el enemigo');
            isIncombat:= InCombat(actualCombatTile);
           end;

        end;
    end;
     end;

   Result:= TileSlots;

  end

procedure Mainloop();
var
  TempTile, t: Int32;
  EnemiesArray: TIntegerArray;
begin
  if IsDisconnected() then
  begin
    WriteLn('Disconnected');
    TerminateScript();
  end;
  {$IFDEF LAYER} DrawClear(); {$ENDIF LAYER}
  EnemiesArray := FindEnemiesAndAttack();
  if Close() then Wait(345, 456);
end;

procedure InitializeDTMs();
var
   RAT_DTM : integer;
   //RAT3_DTM : integer;
   CROW_DTM : integer;
   WOLF_DTM : integer;
   SCORPION_DTM : integer;
   //COBRA_DTM : integer;
   WORM_DTM : integer;
   GOBLIN_DTM: integer;
   PHARAOH_AND_MUMMIES_DTM : integer;
   ASSASIN_RED_DTM, ASSASIN_YELLOW_DTM {ASSASIN_GREY_DTM} : integer;
   ZOMBIE_DTM : integer;
   SKELETON_DTM :integer;
   VAMPIRE_DTM : integer;
   DROW_DTM : integer;

begin

  RAT_DTM := DTMFromString('mGQAAAHicY2RAgB3TIDQjiAAAEJcBUQ==');  //DETECTA EL LOOT COMO SI SE TRATASE DEL ENEMIGO

  //RAT3_DTM (LA VEO INUTIL YA QUE ES LA RATA DE NIVEL 3)

  CROW_DTM := DTMFromString('mGQAAAHicY2RAAHd3dzDNCCIACjMA2A==');

  WOLF_DTM := DTMFromString('mLgAAAHicY2LABP8vLmPoKEDwGaGYgQEAU1kDcw==');

  SCORPION_DTM := DTMFromString('mGQAAAHicY2RAgEPd4WCaEUQAABRSAac=');  //CREO QUE EL MISMO SCORPION DETECTA COBRA

  //COBRA_DTM (DETECTADA POR SCORPION_DTM)

  WORM_DTM :=  DTMFromString('mQwAAAHicY2bADf7MsGD4f3EZw448DRRxRiQMBADB8gWX');

  GOBLIN_DTM := DTMFromString('mLgAAAHicY2LABHK7vBgmTpwI5zNCMQMDAEBvAto=');

  PHARAOH_AND_MUMMIES_DTM := DTMFromString('mLgAAAHicY2LABJ8/f2Y4efIknM8IxQwMAHlCBTk=');

  ASSASIN_RED_DTM := DTMFromString('mLgAAAHicY2LABP9tbRmWLVsG5zNCMQMDAE8HA3A=');
  ASSASIN_YELLOW_DTM := DTMFromString('mLgAAAHicY2LABDumMTB0FCD4jFDMwAAANtACSw==');
  //ASSASIN_GREY_DTM :=     //NO LOS ENCUENTRO XD

  ZOMBIE_DTM := DTMFromString('mLgAAAHicY2LABPkXLzJMnDgRzmeEYgYGAFeQA8k=');   //NO ES PERFECTO (MEJORAR)

  SKELETON_DTM := DTMFromString('mLgAAAHicY2LABJ8/f2Y4efIknM8IxQwMAHlCBTk=');

  VAMPIRE_DTM := DTMFromString('mQwAAAHicY2bADT5//szQ/v8/GCMDRiQMBAANwgfq');


  DROW_DTM := DTMFromString('mGQAAAHicY2RAgDl8m8E0I4gAABB8AWA=');


  enemies_dtm_array := [RAT_DTM ,
                     //RAT3_DTM ,
                       CROW_DTM ,
                       WOLF_DTM ,
                       SCORPION_DTM ,
                     //COBRA_DTM ,
                       WORM_DTM ,
                       GOBLIN_DTM ,
                       PHARAOH_AND_MUMMIES_DTM ,
                       ASSASIN_RED_DTM ,
                       ASSASIN_YELLOW_DTM ,
                       //ASSASIN_GREY_DTM ,
                       ZOMBIE_DTM ,
                       SKELETON_DTM ,
                       VAMPIRE_DTM,
                       DROW_DTM
                        ];


end;

begin
  ClearDebug();
  GetAndSet();
  InitializeDTMs();


  while True do Mainloop();
end.