Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Game of Developer Life... Deconstructed

Game of Developer Life... Deconstructed

Mariusz Gil

April 03, 2017
Tweet

More Decks by Mariusz Gil

Other Decks in Programming

Transcript

  1. private function calculateNewCellState($cell, $cellPosition) { $aliveCount = 0; $currentNeighbour =

    0; $isFirstColumn = $cellPosition % $this->columns === 0; $isLastColumn = $cellPosition % $this->columns === $this->columns - 1; for ($i = 0; $i < 8; $i++) { $currentNeighbour = $cellPosition + $this->neighbourCoordinates[$i]; if ($currentNeighbour > 0 && ($currentNeighbour < $this->boardLength) && $this->currentGeneration[$currentNeighbour]->getState()) { if (($isFirstColumn && !in_array($i, [0, 3, 5])) || ($isLastColumn && !in_array($i, [2, 4, 7])) || !($isFirstColumn || $isLastColumn)) { $aliveCount++; } } } if ($cell->getState() && ($aliveCount < 2 || $aliveCount > 3)) { return false; } else if (!$cell->getState() && $aliveCount === 3) { return true; } else { return $cell->getState(); } }
  2. protected function setCellDead(int $posN, int $posM) { $this->grid ->getCell($posN, $posM)

    ->setDead(); } private function onePlay() { $cellsToUpdate = []; for ($n = 0; $n < $this->grid->getSizeN(); $n++) { for ($m = 0; $m < $this->grid->getSizeM(); $m++) { $neighboursCount = $this->grid->getCellNeighboursCount($n, $m); $cellsToUpdate[] = ['n' => $n, 'm' => $m, 'neighbours' => $neighboursCount]; } } foreach ($cellsToUpdate as $cellStruct) { $this->rules->applyForCell($this->grid->getCell($cellStruct['n'], $cellStruct['m']), $cellStruct['neighbours']); } }
  3. public function compute() { $computedGrid = []; foreach ($this->matrix as

    $row => $cellArr) { foreach ($cellArr as $col => $cell) { $ns = $this->checkLifeNeighbours($row, $col); $newCell = ($cell === null) ? $this->checkIfAwake($ns) : $this->setCellStatus($cell, $ns); $computedGrid[$row][$col] = $newCell; } } $this->matrix = $computedGrid; } private function setCellStatus(Cell $cell, int $lifeNeighbours) { $newCell = clone($cell); if ($cell->getIsAlive() && ($lifeNeighbours < 2 || $lifeNeighbours > 3)) { $newCell->setIsAlive(false); } elseif (!$cell->getIsAlive() && 3 == $lifeNeighbours) { $newCell->setIsAlive(true); } return $newCell; }
  4. 2 3

  5. 4 6

  6. private function checkIfAwake($lifeNeighbours) { return (3 == $lifeNeighbours) ? new

    Cell(true) : null; } private function checkLifeNeighbours(int $row, int $col) { $life = 0; for ($rowMatrix = $row-1; $rowMatrix <= $row+1; $rowMatrix++) { for ($colMatrix = $col-1; $colMatrix <= $col+1; $colMatrix++) { if ($colMatrix == $col && $rowMatrix == $row) continue; if (isset($this->matrix[$rowMatrix][$colMatrix]) && $this->matrix[$rowMatrix][$colMatrix]->getIsAlive()) { $life++; } } } return $life; }
  7. Cancer cell cell Universe Game Rule Populator cli Renderer 2D

    Coordinates stronger cell Always alive cell 3D Coordinates Svg Renderer