How can you handle ships that are larger than a single grid cell in a Battleship game implemented in PHP?
In order to handle ships that are larger than a single grid cell in a Battleship game implemented in PHP, you can create a multi-dimensional array to represent the game board where each cell can hold information about a ship segment. This way, you can track the position and orientation of each ship on the board.
// Define the game board as a multi-dimensional array
$board = array_fill(0, 10, array_fill(0, 10, 0));
// Define a function to place a ship on the board
function placeShip($board, $shipSize, $row, $col, $orientation) {
for ($i = 0; $i < $shipSize; $i++) {
if ($orientation == 'horizontal') {
$board[$row][$col + $i] = 1; // Mark ship segment on the board
} else {
$board[$row + $i][$col] = 1; // Mark ship segment on the board
}
}
return $board;
}
// Example of placing a ship of size 3 at row 2, column 3 horizontally
$board = placeShip($board, 3, 2, 3, 'horizontal');