How can PHP sessions be utilized to store game state information in a Battleship game?

To store game state information in a Battleship game using PHP sessions, you can save the game board and player's moves in session variables. This allows the game state to persist across multiple page loads or game sessions. By storing this information in sessions, players can resume their game where they left off without losing progress.

<?php
session_start();

// Initialize game board and player's moves
if (!isset($_SESSION['game_board'])) {
    $_SESSION['game_board'] = initializeGameBoard();
}
if (!isset($_SESSION['player_moves'])) {
    $_SESSION['player_moves'] = [];
}

// Function to initialize game board
function initializeGameBoard() {
    $game_board = array(
        array('O', 'O', 'O', 'O', 'O'),
        array('O', 'O', 'O', 'O', 'O'),
        array('O', 'O', 'O', 'O', 'O'),
        array('O', 'O', 'O', 'O', 'O'),
        array('O', 'O', 'O', 'O', 'O')
    );
    return $game_board;
}

// Function to update game board with player's move
function updateGameBoard($row, $col) {
    $_SESSION['game_board'][$row][$col] = 'X';
}

// Example of updating game board with player's move
$row = 2;
$col = 3;
updateGameBoard($row, $col);

// Display game board
foreach ($_SESSION['game_board'] as $row) {
    echo implode(' ', $row) . "<br>";
}
?>