Total Complexity | 10 |
Total Lines | 100 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | <?php |
||
9 | class Life |
||
10 | { |
||
11 | /** |
||
12 | * World object acts as an info card. |
||
13 | * |
||
14 | * @var World |
||
15 | */ |
||
16 | private $world; |
||
17 | |||
18 | /** |
||
19 | * DAO of organisms |
||
20 | * |
||
21 | * @var Organisms |
||
22 | */ |
||
23 | private $organisms; |
||
24 | |||
25 | /** |
||
26 | * Keeps the number of current generation. |
||
27 | * |
||
28 | * @var int |
||
29 | */ |
||
30 | private $generations = 0; |
||
31 | |||
32 | /** |
||
33 | * Life constructor. |
||
34 | * @param World $world |
||
35 | * @param Organisms $organisms |
||
36 | */ |
||
37 | public function __construct(World $world, Organisms $organisms) |
||
38 | { |
||
39 | $this->world = $world; |
||
40 | $this->organisms = $organisms; |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * Initializes the game |
||
45 | * |
||
46 | * @param bool $verbose |
||
47 | */ |
||
48 | public function start($verbose = true) |
||
49 | { |
||
50 | if ($this->generations == 0) { |
||
51 | while ($this->generations < $this->world->getIterations()) { |
||
52 | $this->organisms->iterate(); |
||
53 | if ($verbose) { |
||
54 | self::printMatrixCli($this->organisms->getCells()); |
||
55 | } |
||
56 | $this->generations++; |
||
57 | } |
||
58 | } |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * Shows if the game reached max iteration |
||
63 | * |
||
64 | * @return bool |
||
65 | */ |
||
66 | public function isEnded() |
||
67 | { |
||
68 | return $this->generations == $this->world->getIterations(); |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * Helper method to print organisms to CLI. |
||
73 | * |
||
74 | * @param $matrix |
||
75 | */ |
||
76 | private static function printMatrixCli($matrix) |
||
109 | } |
||
110 | |||
111 | } |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: