package functions;
import environment.Cell;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author Marco Celesti
*/
public class EnvironmentFunction {
public static Set<Cell> getSurroundings(Cell[][] grid, Cell cell, int distance, int cols, int rows, boolean borders) {
Set<Cell> surroundings = new HashSet<Cell>();
for (int i = (cell.getX() - distance); i <= (cell.getX() + distance); i++) {
for (int j = (cell.getY() - distance); j <= (cell.getY() + distance); j++) {
int x = i;
int y = j;
if (x < 0 || y < 0 || x >= cols || y >= rows) {
if (!borders) {
if (x < 0) {
x = cols - 1;
}
if (y < 0) {
y = rows - 1;
}
if (x >= cols) {
x = 0;
}
if (y >= rows) {
y = 0;
}
surroundings.add(grid[x][y]);
}
} else {
surroundings.add(grid[x][y]);
}
}
}
return surroundings;
}
public static short getNormalizedMovement(short a, short lines) {
if (a > lines / 2) {
a -= lines;
} else if (a < -lines / 2) {
a += lines;
}
return a;
}
public static short getNormalizedX(short x, short cols) {
if (x < 0) {
x = (short) (x + cols);
} else if (x >= cols) {
x = (short) (x - cols);
}
return x;
}
public static short getNormalizedY(short y, short rows) {
if (y < 0) {
y = (short) (y + rows);
} else if (y >= rows) {
y = (short) (y - rows);
}
return y;
}
public static List<Cell> getSortedOutline(Set<Cell> shape, Cell unitCell, short cols, short rows) {
List<Cell> listCell = new ArrayList<Cell>();
shape.remove(unitCell);
listCell.add(unitCell);
while (!shape.isEmpty()) {
Cell nearestCell = getNearestCell(shape, listCell.get(listCell.size() - 1), cols, rows);
shape.remove(nearestCell);
listCell.add(nearestCell);
}
listCell.remove(0);
return listCell;
}
private static double getDistance(Cell shapeCell, Cell unitCell, short cols, short rows) {
short x = (short) (shapeCell.getX() - unitCell.getX());
x = getNormalizedMovement(x, cols);
short y = (short) (shapeCell.getY() - unitCell.getY());
y = getNormalizedMovement(y, rows);
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
private static Cell getNearestCell(Set<Cell> shape, Cell unitCell, short cols, short rows) {
Cell nearestCell = null;
double nearestDistance = 0.0;
if (shape.size() == 1) {
Cell c = shape.iterator().next();
return new Cell(c.getX(), c.getY());
}
for (Cell c : shape) {
double dist = getDistance(c, unitCell, cols, rows);
if (nearestCell == null) {
nearestDistance = dist;
nearestCell = new Cell(c.getX(), c.getY());
if (dist == 1.0) {
break;
}
} else {
if (dist < nearestDistance) {
nearestDistance = dist;
nearestCell = new Cell(c.getX(), c.getY());
}
}
}
return nearestCell;
}
}