// Place the ship onto the board. // Typicall call would be placeShip(board, 5, "C") for a five spot carrier ship. function placeShip(&$board, $shipSize, $shipMarker) { $shipPlacement = findPlaceOnBoard($board, $shipSize); while (!checkForSafePlacement($board, $shipSize, $shipPlacement["start_x"], $shipPlacement["start_y"], $shipPlacement["orientation"])) { $shipPlacement = findPlaceOnBoard($board, $shipSize); } $orientation = $shipPlacement["orientation"]; $startY = $shipPlacement["start_y"]; $startX = $shipPlacement["start_x"]; if ($orientation == 0) { for ($i = 0; $i < $shipSize; $i++) { $board[$startY][$startX + $i] = $shipMarker; } } else { for ($i = 0; $i < $shipSize; $i++) { $board[$startY + $i][$startX] = $shipMarker; } } } // Look at the board and find a random place to place a ship. // Return the starting X,Y and orientation for the ship in an array. function findPlaceOnBoard(&$board, $shipSize) { $orientation = rand(0,1); $maxStartCoord = (count($board[0]) - $shipSize); if ($orientation == 0) { // Horizontal $startX = rand(0,$maxStartCoord); $startY = rand(0,count($board) - 1); } else { // Vertical $startX = rand(0,count($board[0]) - 1); $startY = rand(0,$maxStartCoord); } return array("start_x" => $startX, "start_y" => $startY, "orientation" => $orientation); } // Check to see if it is safe to place the ship at starting X,Y with given orientation // Here "W" is a marker for open water. Use whatever marker determines open water. // Returns true if it is safe to place the ship at the specified location with given orientation. function checkForSafePlacement(&$board, $shipSize, $startX, $startY, $orientation) { if ($orientation == 0) { for ($i = 0; $i < $shipSize; $i++) { if ($board[$startY][$startX + $i] != "W") { return false; } } } else { for ($i = 0; $i < $shipSize; $i++) { if ($board[$startY + $i][$startX] != "W") { return false; } } } return true; }
Posted: March 18, 2023
Return to the snippets listing