-
Notifications
You must be signed in to change notification settings - Fork 0
/
Species.java
110 lines (89 loc) · 2.56 KB
/
Species.java
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
102
103
104
105
106
107
108
109
110
public abstract class Species extends Thread {
protected String disp; // character to display in printed grid
protected int life; // final lifespan value between 0 - max life
protected double fitness;
protected int[] pos;
protected int[][] neighbours;
protected Grid grid;
/**
* Constructor for abstract species class
* @param row row position of this instance of a creature of either species
* @param col columns position of this instance of a creature of either species
* @param g grid world in which this creature lives
*/
Species(int row, int col, Grid g) {
this.pos = new int[2];
this.pos[0] = row;
this.pos[1] = col;
this.grid = g;
this.neighbours = g.validateNeighbours(g.getNeighbours(this.pos));
}
public String getDisp(){
return disp;
}
public int getLife(){
return life;
}
public int[] getPos(){
return pos;
}
public int[][] getSpNeighb() {
return neighbours;
}
public double getFitness() {
return fitness;
}
/**
* Method for running thread.
* First sleep, then attempt to reproduce.
*
* Afterwards, set own position to null and kill thread.
* If interrupted (i.e. killed), set itself to null
*/
public void run() {
try {
// System.out.println("sleep: " + (this.getLife()*1000));
Thread.sleep(this.getLife()*1000);
reproduce();
}
catch (InterruptedException e) {
grid.setCreature(pos, null);
}
finally {
grid.setCreature(pos, null);
Thread.interrupted();
}
}
/**
* Method for spreading species to neighbouring cells
*
* Only spread to valid neighbouring positions - these are validated
* in constructor.
*
* The method then checks what "lives" in each of the neighbouring position.
* Its fitness is then checked against a random number between 0-1
* (and the fitness of a competing creature, if applicable),
* to emulate the probability of reproducing.
*
* If it successfully reproduces on a position with an existing creature,
* it will interrupt its thread.
*
*/
public synchronized void reproduce() {
for (int i = 0; i < neighbours.length; i++) {
Species currSp = grid.getSpecies(neighbours[i]);
if (currSp == null || currSp.isAlive() || currSp == this) {
if ((this.getFitness() - Math.random()) > 0) {
// System.out.println("fit:" + (this.getFitness() - Math.random()) );
grid.setCreature(neighbours[i], this.disp);
}
}
else {
if ((this.getFitness() - currSp.getFitness() - Math.random()) > 0) {
currSp.interrupt();
grid.setCreature(neighbours[i], this.disp);
}
}
}
}
}