Here is the AI Method.:
public void Move()
{
if (movetimer > 0)
{
movetimer--;
}
if (movetimer == 0)
{
int TargetX;
int TargetY;
List<Vector2> possibleTiles = new List<Vector2>();
List<Vector2> movableTiles = new List<Vector2>();
List<Vector2> movableDesiredTiles = new List<Vector2>();
if (X < Main.map.grid.GetLength(1))
{
possibleTiles.Add(new Vector2(X + 1, Y));
}
possibleTiles.Add(new Vector2(X, Y + 1));
if (X > 0)
{
possibleTiles.Add(new Vector2(X - 1, Y));
}
possibleTiles.Add(new Vector2(X, Y - 1));
foreach (Vector2 tile in possibleTiles)
{
if (tile.X < Main.map.grid.GetLength(1) && tile.Y < Main.map.grid.GetLength(0))
{
if (Main.map.grid[(int)tile.Y, (int)tile.X] != 2)
{
movableTiles.Add(new Vector2(tile.X, tile.Y));
}
}
}
foreach (Vector2 tile in movableTiles)
{
if (Vector2.Distance(new Vector2(tile.X, tile.Y), new Vector2(Main.player.X, Main.player.Y)) < Vector2.Distance(new Vector2(X, Y), new Vector2(Main.player.X, Main.player.Y)))
{
movableDesiredTiles.Add(new Vector2(tile.X, tile.Y));
}
}
if (movableDesiredTiles.Count > 0)
{
Vector2 mostDesiredTile = new Vector2(X, Y);
int distanceX;
int distanceY;
int totalDistance = 100;
foreach (Vector2 tile in movableDesiredTiles)
{
int specificDistance;
distanceX = Main.player.X - X;
if (distanceX < 0)
{
distanceX *= -1;
}
distanceY = Main.player.Y - Y;
if (distanceY < 0)
{
distanceY *= -1;
}
specificDistance = distanceX + distanceY;
if (specificDistance < totalDistance)
{
mostDesiredTile = new Vector2(tile.X, tile.Y);
totalDistance = specificDistance;
}
}
TargetX = (int)mostDesiredTile.X;
TargetY = (int)mostDesiredTile.Y;
X = TargetX;
Y = TargetY;
}
movetimer = 60;
}