Repository navigation
Expand file tree
/
Copy pathAnimal.java
More file actions
executable file
·101 lines (89 loc) · 2.28 KB
/
Copy pathAnimal.java
File metadata and controls
executable file
·101 lines (89 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.List;
import java.util.Random;
/**
* Common elements of foxes and rabbits.
*
* @author David J. Barnes and Michael Kölling
* @version 7.0
*/
public abstract class Animal
{
// Whether the animal is alive or not.
private boolean alive;
// The animal's position.
private Location location;
private boolean infected;
private static Random rand = new Random();
/**
* Constructor for objects of class Animal.
* @param location The animal's location.
*/
public Animal(Location location)
{
this.alive = true;
this.location = location;
this.infected = false;
}
/**
* Act.
* @param currentField The current state of the field.
* @param nextFieldState The new state being built.
*/
abstract public void act(Field currentField, Field nextFieldState);
/**
* Check whether the animal is alive or not.
* @return true if the animal is still alive.
*/
public boolean isAlive()
{
return alive;
}
/**
* Indicate that the animal is no longer alive.
*/
protected void setDead()
{
alive = false;
location = null;
}
public boolean isInfected(){
return infected;
}
public void infect() {
infected = true;
}
public void riskDisease(){
if (infected) {
if (rand.nextDouble() < 0.25) {
setDead();
}
}
}
/**
* Return the animal's location.
* @return The animal's location.
*/
public Location getLocation()
{
return location;
}
/**
* Set the animal's location.
* @param location The new location.
*/
protected void setLocation(Location location)
{
this.location = location;
}
public void spreadDisease(Field currentField){
if (infected) {
List<Location> adjacentLocations = currentField.getAdjacentLocations(getLocation());
for (Location loc : adjacentLocations) {
Animal nearby = currentField.getAnimalAt(loc);
if (nearby != null && !nearby.isInfected() && rand.nextDouble() < 0.2) { // 20% chance to spread
nearby.infect();
}
}
}
}
}