public function nextGrid(AnimatedLightingGrid $grid) { $verticalSize = $grid->verticalSize(); $horizontalSize = $grid->horizontalSize(); $lights = []; $existingLights = $grid->getLights(); $brokenLights = $grid instanceof BrokenAnimatedLightingGrid ? $grid->getBrokenLights() : []; //loop through grid checking each light for its status + neighbours for ($y = 1; $y <= $verticalSize; $y++) { for ($x = 1; $x <= $horizontalSize; $x++) { if (in_array($x . "-" . $y, $brokenLights)) { $lights[] = $x . "-" . $y; continue; } //find out how many neighbour lights are switched on $onNeighbours = 0; foreach ($grid->neighbours($x, $y) as $neighbour) { if (in_array($neighbour[0] . "-" . $neighbour[1], $existingLights)) { $onNeighbours++; } } //work out state for this light for next step $currentlyOn = in_array("{$x}-{$y}", $existingLights); if ($currentlyOn && ($onNeighbours == 2 || $onNeighbours == 3)) { $lights[] = "{$x}-{$y}"; } elseif (!$currentlyOn && $onNeighbours == 3) { $lights[] = "{$x}-{$y}"; } } } $grid->lights($lights); return $grid; }
public function lights(array $lights) { parent::lights(array_merge($lights, $this->getBrokenLights())); }