예제 #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
 /**
  * @test
  */
 public function it_should_not_allow_to_fire_in_a_locked_game()
 {
     $game = Game::create();
     $game->surrender();
     $this->setExpectedException(GameIsLockedException::class);
     $game->fire(Coords::create(1, 1));
 }
예제 #3
0
 /**
  * @param int $x
  * @param int $y
  * @return static
  */
 public static function generate($x, $y)
 {
     return new static(Coords::create($x, $y));
 }
예제 #4
0
 /**
  * fire on $location
  * @param string $location
  * @return string
  */
 private function fire($location)
 {
     $identifier = GameIdentifier::fromString($this->id());
     $game = $this->repository()->get($identifier);
     $coordElements = explode('.', $location);
     $coords = Coords::create((int) $coordElements[0], (int) $coordElements[1]);
     $result = $game->fire($coords);
     $this->repository()->save($game);
     echo 'Firing on ' . $location . ' in game: ' . $game->id() . PHP_EOL;
     echo (string) $game;
     return $result;
 }
예제 #5
0
 /**
  * Retrieve the coords a specified distance below these coords.
  *
  * @param int $distance
  *
  * @return Coords
  */
 public function below($distance)
 {
     return Coords::create($this->x(), $this->y() + $distance);
 }
예제 #6
0
<?php

require __DIR__ . '/vendor/autoload.php';
$game = Wecamp\FlyingLiquorice\Domain\Game::create(10, 10);
echo $game;
while (true) {
    try {
        $game->fire(\Wecamp\FlyingLiquorice\Domain\Game\Coords::create(mt_rand(0, 9), mt_rand(0, 9)));
    } catch (Wecamp\FlyingLiquorice\Domain\Game\FieldAlreadyBeenShotException $e) {
        // Ignore
    } catch (Wecamp\FlyingLiquorice\Domain\Game\GameIsLockedException $e) {
        // Won the game
        break;
    }
}
echo $game;