1 package org.woehlke.computer.kurzweil.simulated.evolution.model;
2
3
4 import lombok.EqualsAndHashCode;
5 import lombok.Getter;
6 import lombok.ToString;
7 import lombok.extern.log4j.Log4j2;
8 import org.woehlke.computer.kurzweil.simulated.evolution.model.cell.Cell;
9 import org.woehlke.computer.kurzweil.simulated.evolution.model.world.SimulatedEvolutionParameter;
10 import org.woehlke.computer.kurzweil.simulated.evolution.model.lattice.SimulatedEvolutionWorldLattice;
11 import org.woehlke.computer.kurzweil.simulated.evolution.model.world.WorldPoint;
12
13 import java.io.Serializable;
14 import java.util.ArrayList;
15 import java.util.Date;
16 import java.util.List;
17 import java.util.Random;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 @Log4j2
38 @ToString(exclude = {"random"})
39 @EqualsAndHashCode(exclude = {"random"})
40 public class SimulatedEvolutionModel implements Serializable {
41
42 static final long serialVersionUID = 242L;
43
44
45
46
47 private List<Cell> cells;
48
49
50
51
52 private final int INITIAL_POPULATION = 20;
53
54
55
56
57 private Random random;
58
59
60
61
62 private WorldPoint worldDimensions;
63
64
65
66
67 private SimulatedEvolutionWorldLattice simulatedEvolutionWorldLattice;
68
69
70
71
72 @Getter
73 private SimulatedEvolutionParameter simulatedEvolutionParameter;
74
75 public SimulatedEvolutionModel(WorldPoint worldDimensions) {
76 long seed = new Date().getTime();
77 random = new Random(seed);
78 this.worldDimensions = worldDimensions;
79 simulatedEvolutionWorldLattice = new SimulatedEvolutionWorldLattice(this.worldDimensions,random);
80 createPopulation();
81 simulatedEvolutionParameter = new SimulatedEvolutionParameter();
82
83 }
84
85
86
87
88 private void createPopulation() {
89 cells = new ArrayList<Cell>();
90 for (int i = 0; i < INITIAL_POPULATION; i++) {
91 int x = random.nextInt(worldDimensions.getX());
92 int y = random.nextInt(worldDimensions.getY());
93 if (x < 0) {
94 x *= -1;
95 }
96 if (y < 0) {
97 y *= -1;
98 }
99 WorldPoint pos = new WorldPoint(x, y);
100 Cell cell = new Cell(worldDimensions, pos, random);
101 cells.add(cell);
102 }
103 }
104
105
106
107
108
109 public void letLivePopulation() {
110 simulatedEvolutionWorldLattice.letFoodGrow();
111 WorldPoint pos;
112 List<Cell> children = new ArrayList<Cell>();
113 List<Cell> died = new ArrayList<Cell>();
114 for (Cell cell:cells) {
115 cell.move();
116 if(cell.died()){
117 died.add(cell);
118 } else {
119 pos = cell.getPosition();
120 int food = simulatedEvolutionWorldLattice.eat(pos);
121 cell.eat(food);
122 if (cell.isPregnant()) {
123 Cell child = cell.performReproductionByCellDivision();
124 children.add(child);
125 }
126 }
127 }
128 for(Cell dead:died){
129 cells.remove(dead);
130 }
131 cells.addAll(children);
132 }
133
134 public List<Cell> getAllCells(){
135 return cells;
136 }
137
138 public boolean hasFood(int x, int y) {
139 return simulatedEvolutionWorldLattice.hasFood(x,y);
140 }
141 }