View Javadoc
1   package org.woehlke.simulation.evolution.model;
2   
3   
4   import java.util.ArrayList;
5   import java.util.Date;
6   import java.util.List;
7   import java.util.Random;
8   
9   /**
10   * (C) 2006 - 2008 Thomas Woehlke.
11   * http://thomas-woehlke.de/p/simulated-evolution/
12   * @author Thomas Woehlke
13   * User: thomas
14   * Date: 04.02.2006
15   * Time: 19:06:20
16   */
17  public class World {
18  
19      private List<Cell> cells;
20      private int INITIAL_POPULATION = 20;
21      private Random random;
22      private Point worldDimensions;
23      private WorldMapFood worldMapFood;
24  
25      public World(Point worldDimensions) {
26          long seed = new Date().getTime();
27          random = new Random(seed);
28          this.worldDimensions = worldDimensions;
29          worldMapFood = new WorldMapFood(this.worldDimensions,random);
30          createPopulation();
31      }
32  
33      private void createPopulation() {
34          cells = new ArrayList<Cell>();
35          for (int i = 0; i < INITIAL_POPULATION; i++) {
36              int x = random.nextInt(worldDimensions.getX());
37              int y = random.nextInt(worldDimensions.getY());
38              if (x < 0) {
39                  x *= -1;
40              }
41              if (y < 0) {
42                  y *= -1;
43              }
44              Point pos = new Point(x, y);
45              Cell cell = new Cell(worldDimensions, pos, random);
46              cells.add(cell);
47          }
48      }
49  
50      public void letLivePopulation() {
51          worldMapFood.letFoodGrow();
52          Point pos;
53          List<Cell> children = new ArrayList<Cell>();
54          List<Cell> died = new ArrayList<Cell>();
55          for (Cell cell:cells) {
56              cell.move();
57              if(cell.died()){
58                  died.add(cell);
59              } else {
60                  pos = cell.getPosition();
61                  int food = worldMapFood.eat(pos);
62                  cell.eat(food);
63                  if (cell.isPregnant()) {
64                      Cell child = cell.cellDivisionFactory();
65                      children.add(child);
66                  }
67              }
68          }
69          for(Cell dead:died){
70              cells.remove(dead);
71          }
72          cells.addAll(children);
73  
74      }
75  
76      public List<Cell> getAllCells(){
77          return cells;
78      }
79  
80      public boolean hasFood(int x, int y) {
81          return worldMapFood.hasFood(x,y);
82      }
83  }