コード例 #1
0
 /**
  * @param int $width
  * @param int $height
  * @param array $shipSizes
  * @return Fields
  */
 public static function generate($width, $height, array $shipSizes)
 {
     Assertion::integer($width);
     Assertion::integer($height);
     Assertion::allInteger($shipSizes);
     $elements = [];
     for ($y = 0; $y < $height; $y++) {
         for ($x = 0; $x < $width; $x++) {
             $elements[] = Field::generate($x, $y);
         }
     }
     $fields = Fields::create($elements);
     foreach ($shipSizes as $shipSize) {
         $attempts = 0;
         while (true) {
             if ($attempts == static::MAX_ATTEMPTS) {
                 throw new CannotPlaceShipOnGridException();
             }
             $direction = mt_rand(0, 1) == 0 ? 'right' : 'below';
             $spot = Coords::create(mt_rand(0, $width - 1), mt_rand(0, $height - 1));
             $endPoint = static::validEndpoint($fields, $spot, $shipSize, $direction);
             if ($endPoint === null) {
                 $attempts++;
                 continue;
             }
             // If we end up here the ship can fit at the determined spot
             $fields->place(Ship::create($spot, $endPoint));
             break;
         }
     }
     return $fields;
 }
コード例 #2
0
ファイル: Fields.php プロジェクト: WeCamp/flyingliquourice
 /**
  * @param array $data
  *
  * @return static
  */
 public static function fromArray(array $data)
 {
     $ships = [];
     foreach ($data['ships'] as $ship) {
         $ships[] = Ship::fromArray($ship);
     }
     $elements = [];
     foreach ($data['fields'] as $field) {
         $field = Field::fromArray($field);
         /** @var Ship $ship */
         foreach ($ships as $ship) {
             if ($ship->on($field->coords())) {
                 $field->place($ship);
             }
         }
         $elements[] = $field;
     }
     return new static($elements, $ships);
 }