Example #1
0
 /**
  * @param BattleshipInterface $battleship
  * @param PointInterface $start
  * @param PointInterface $end
  */
 public function __construct(BattleshipInterface $battleship, PointInterface $start, PointInterface $end)
 {
     /*
      * placer should allow ony
      * ---->
      * OR
      * | 
      * |
      * \/
      * 
      * But not <-----
      * Instead of throw error, $start and $end could be exchanged.
      */
     if ($start->getX() > $end->getX() || $start->getY() > $end->getY()) {
         throw new Exception\Exception("Points missmatch");
     }
     $this->battleship = $battleship;
     $this->startPoint = $start;
     $this->endPoint = $end;
     if ($this->getPoints()->count() !== $battleship->getSize()) {
         throw new Exception\Exception('Can\'t fit battleship in placer');
     }
 }
Example #2
0
 /**
  * Get available placers for battleship
  * @param BattleshipInterface $battleship
  * @return Placer[]
  */
 public function getValidPlaces(BattleshipInterface $battleship)
 {
     $potentialPlacements = [];
     $battleshipSize = $battleship->getSize();
     for ($yIndex = 0; $yIndex < $this->fieldHeight; $yIndex++) {
         for ($xIndex = 0; $xIndex < $this->fieldWidth; $xIndex++) {
             $horizontalValidation = true;
             $verticalValidation = true;
             for ($i = 0; $i < $battleshipSize; $i++) {
                 if ($horizontalValidation) {
                     $pointToCheck = new Point($xIndex + $i, $yIndex);
                     if (!$this->isPointFree($pointToCheck)) {
                         $horizontalValidation = false;
                     }
                 }
                 if ($verticalValidation) {
                     $pointToCheck = new Point($xIndex, $yIndex + $i);
                     if (!$this->isPointFree($pointToCheck)) {
                         $verticalValidation = false;
                     }
                 }
                 if (!$horizontalValidation && !$verticalValidation) {
                     break;
                 }
             }
             if ($verticalValidation) {
                 $potentialPlacements[] = new Placer($battleship, new Point($xIndex, $yIndex), new Point($xIndex, $yIndex + $battleshipSize - 1));
             }
             if ($horizontalValidation) {
                 $potentialPlacements[] = new Placer($battleship, new Point($xIndex, $yIndex), new Point($xIndex + $battleshipSize - 1, $yIndex));
             }
         }
     }
     return $potentialPlacements;
 }