OOP_Letourneux_Lopategui_Pi.../Sheep.java

93 lines
2.3 KiB
Java

package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
public class Sheep extends Agent {
int hunger;
Random rand;
Sheep(int x,int y){
//first we call the constructor of the superClass(Animal)
super(x,y,Color.white, 20, 3);
hunger = 0;
rand = new Random();
}
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
// color darken the more it is starved
if(hunger<=100 && hunger>0) {
Color color = new Color((int)(255-2.54*hunger), (int)(255-2.54*hunger), (int)(255-2.54*hunger));
this.changeColor(color);
}
if(this.searchFood(triggerRadius, world).isEmpty()) { // no food nearby ?
this.moveRandom(world);
hunger++;
}
else { // go to food !
this.moveToFood(this.searchFood(triggerRadius, world).get(0), this.searchFood(triggerRadius, world).get(1), world);
if(world.getCell(x, y)==1) {
world.setCell(x, y, 0);
if(hunger > 30) {hunger = hunger - 30;}
}
}
return hunger>100;
}
private ArrayList<Integer> searchFood(int radius, Simulator world) { // targets the nearest food (= cell alive)
ArrayList<Integer> coordinates = new ArrayList<Integer>();
for(int x = this.x - radius; x < this.x + radius; x++) {
for(int y = this.y - radius; y < this.y + radius; y++) {
if(x > 0 && x < world.getWidth() && y > 0 && y < world.getHeight() && isInArea(x, y, radius) && world.getCell(x, y) == 1) {
coordinates.add(x);
coordinates.add(y);
}
}
}
return coordinates;
}
private void moveRandom(Simulator world) {
int direction = rand.nextInt(4);
if(direction == 0 && x < world.getWidth()-1) {
x+=1;
}
if(direction == 1 && y < world.getHeight()-1) {
y+=1;
}
if(direction == 2 && x > 0) {
x-=1;
}
if(direction == 3 && y > 0) {
y-=1;
}
}
private void moveToFood(int x, int y, Simulator world) {
int clever = rand.nextInt(6 - this.intelligence);
if(this.intelligence == 0) {
this.moveRandom(world);
}
if(clever == 0) {
if(this.x < x && x < world.getWidth()-1) {
this.x+=1;
}
if(this.y < y && y < world.getHeight()-1) {
this.y+=1;
}
if(this.x > x && x > 0) {
this.x-=1;
}
if(this.y > y && y > 0) {
this.y-=1;
}
}
else {this.moveRandom(world);}
}
}