I got this code where the sheep should move away from the Wolf. I have managed to get the Wolf to hunt the sheep but I am not sure how I would go about to get the Sheep to avoid wolves.
The Code for the Wolf is here below, maybe I could just reverse it in some way for the sheep so it avoids the wolf instead?
The pasture itself is a grid with a set height/width and each entity can only move 1 Point at the time in a direction.
How would the calculation look like to move away from something?
@Override
public void tick() {
// Decrement timers
super.tick();
if(currMoveDelay <= 0) {
Point entityPos = pasture.getEntityPosition(this);
List<Point> freeNeightbours = pasture.getFreeNeighbours(this);
// Choose the entry with the highest score.
Map.Entry<Point, Double> valueableEntry = null;
//Previous coordinates of this entity.
int lastX = previousCoordinate.x;
int lastY = previousCoordinate.y;
// Get all entities within this animals line of sight.
List<Entity> spottedEntities = pasture.getEntitiesWithinDistance(entityPos, lineOfSight);
// Score each prey and store the position and the score in a Map.
Map<Point, Double> availableNeighbours = new HashMap<Point, Double>();
// Loop through all the free neightbours.
for(Point neighbour : freeNeightbours) {
Double score = 0.0;
//For each entity, calculate distance and factor that when determening the score.
for( Entity e : spottedEntities ) {
Point currentEntityPosition = pasture.getEntityPosition(e);
Double distance = neighbour.distance(currentEntityPosition);
if(e instanceof Animal && ((Animal) e).getAnimalType() == AnimalType.Herbivore) {
score += 100 / (1 + distance);
}
}
//Put this new neighbour and score in the available ones.
availableNeighbours.put(neighbour, score);
}
for (Map.Entry<Point, Double> closest : availableNeighbours.entrySet() ) {
if (valueableEntry == null || closest.getValue().compareTo(valueableEntry.getValue()) > 0) {
valueableEntry = closest;
}
}
// Store the preferred neighbour
Point moveTowardsThisPoint = valueableEntry.getKey();
// If it is not possible to move, continue like normal.
if(freeNeightbours.contains(moveTowardsThisPoint) == false) {
moveTowardsThisPoint = new Point(entityPos.x + lastX, entityPos.y + lastY);
}
// If that is not possible, move in a random direction.
if(freeNeightbours.contains(moveTowardsThisPoint) == false) {
moveTowardsThisPoint = Utils.getRandomMember(pasture.getFreeNeighbours(this));
}
// Update last position to the new one.
lastX = moveTowardsThisPoint.x - entityPos.x;
lastY = moveTowardsThisPoint.y - entityPos.y;
// Move entity and reset timer.
pasture.moveEntity(this, moveTowardsThisPoint);
for(Entity e : pasture.getEntitiesAt(entityPos)) {
//Find all possible preys at current position and EAT THEM
if(!(e instanceof Plant) && ((Animal) e).getAnimalType() == AnimalType.Herbivore) {
eat(e);
}
else{
continue;
}
}
currMoveDelay = MOVE_DELAY;
}
}