the following web app for board game testing has a couple features implemented wrong way: the generated feature "+1" gets added to a player's items as a "1" when his marker is put on a field with "+1" and the "+1" disappears. This is wrong, it should work exactly as "+2" or "-1" feature as they're different that ITEM-features. And all the "+1", "+2" and "-1" features should affect the Count action used on the field they're on (by adding or subtracting the number from the count), even then they should remain on the field. Please also add a new action button: "Make another move" - it should simply make the turn phase 1 again, (which will continue to phase 2 as normal after making a new marker placement.) CODE: <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Interactive Game Board</title>
    <style>
        /* Root CSS Variables for Responsiveness */
        :root {
            --wall-fr: 1fr; /* Fractional unit for walls */
            --cell-fr: 4fr; /* Fractional unit for cells */
            --fog-color: rgba(0, 0, 0, 0.5); /* Semi-transparent fog */
            --max-board-size: 90vmin; /* Max size for the board */
            --fog-transition-time: 0.3s;
        }

        /* Game board container */
        #game-container {
            display: grid;
            /* Define alternating wall and cell sizes using fractional units */
            grid-template-columns: var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr);
            grid-template-rows: var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr) var(--cell-fr) var(--wall-fr);
            gap: 0;
            position: relative;
            width: var(--max-board-size);
            height: var(--max-board-size);
            margin: 20px auto;
            border: var(--wall-fr) solid #333;
            background-color: #fff;
            box-sizing: border-box;
            overflow: hidden; /* Prevent overflow */
        }

        /* Cells */
        .cell {
            background-color: white;
            border: none; /* Borders are handled by grid walls */
            position: relative;
            cursor: pointer;
            overflow: hidden;
        }

        /* Marker container */
        .marker-container {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-weight: bold;
            font-size: 1.5em;
            pointer-events: none; /* Allows clicks to pass through to the cell */
        }

        /* Number container */
        .number-container {
            position: absolute;
            top: 5%;
            left: 5%;
            font-size: 0.8em;
            pointer-events: none; /* Allows clicks to pass through to the cell */
        }

        /* Feature container */
        .feature-container {
            position: absolute;
            bottom: 5%;
            right: 5%;
            font-size: 1em;
            pointer-events: none; /* Allows clicks to pass through to the cell */
        }

        /* Corners */
        .corner {
            width: 100%;
            height: 100%;
            background-color: #666;
            cursor: pointer;
            box-sizing: border-box;
        }

        /* Horizontal walls */
        .h-wall {
            width: 100%;
            height: 100%;
            background-color: transparent; /* Initially no wall */
            cursor: pointer;
            box-sizing: border-box;
        }

        /* Vertical walls */
        .v-wall {
            width: 100%;
            height: 100%;
            background-color: transparent; /* Initially no wall */
            cursor: pointer;
            box-sizing: border-box;
        }

        /* Hover effect */
        .cell:hover,
        .corner:hover,
        .h-wall:hover,
        .v-wall:hover {
            background-color: #ffd700;
        }

        /* Controls */
        #controls {
            text-align: center;
            margin: 10px;
        }

        #controls button {
            padding: 0.5em 1em;
            margin: 0.3em;
            font-size: 1em;
            cursor: pointer;
        }

        /* Status display */
        #status-container {
            text-align: center;
            font-size: 1.2em;
            margin-bottom: 0.5em;
        }

        .status-item {
            margin: 0.3em;
        }

        .wall-counter {
            margin-top: 0.5em;
            font-size: 1em;
            color: #333;
        }

        /* Message display */
        #message {
            text-align: center;
            font-size: 1em;
            margin-bottom: 0.5em;
            color: green;
        }

        /* Filled area */
        .filled {
            background-color: rgba(0, 0, 255, 0.2);
        }

        .filled-red {
            background-color: rgba(255, 0, 0, 0.2);
        }

        /* Disabled walls (black walls) */
        .disabled-wall {
            background-color: black !important;
            cursor: not-allowed !important;
        }

        /* Fog of War */
        .fog {
            position: absolute;
            background-color: var(--fog-color);
            z-index: 10;
            cursor: pointer;
            border: 2px solid #444;
            box-sizing: border-box;
            transition: opacity var(--fog-transition-time);
            width: 100%;
            height: 100%;
        }

        /* Feature Styles */
        .item-feature {
            width: 15px;
            height: 15px;
            background-color: orange;
            border-radius: 50%;
            position: relative;
            top: 50%;
            left: 0%;
            transform: translate (-50%, -50%);
        }

        /* Responsive adjustments */
        @media (max-width: 600px) {
            :root {
                --max-board-size: 95vmin;
            }

            .marker-container {
                font-size: 1.2em;
            }

            .number-container {
                font-size: 0.7em;
            }

            #controls button {
                padding: 0.4em 0.8em;
                font-size: 0.9em;
            }

            #status-container {
                font-size: 1em;
            }

            #message {
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div id="status-container">
        <div class="status-item">Current Player: <span id="current-player" style="color: blue;">Blue (O)</span></div>
        <div class="wall-counter">
            Blue Walls Used: <span id="blue-walls-used">0</span> |
            Red Walls Used: <span id="red-walls-used">0</span>
        </div>
        <!-- Added Item Display for Players -->
        <div class="status-item">Blue Items: <span id="blue-items">-</span></div>
        <div class="status-item">Red Items: <span id="red-items">-</span></div>
    </div>
    <div id="message"></div>
    <div id="game-container"></div>
    <div id="controls">
        <button id="flood-button" disabled>Flood</button>
        <button id="count-button" disabled>Count</button>
        <button id="pass-button" disabled>Pass Turn</button>
        <button id="reset-button">Reset Game</button>
    </div>
    <script>
        const N = 9; // Grid size
        const gameContainer = document.getElementById('game-container');
        const statusDisplay = document.getElementById('current-player');
        const messageDisplay = document.getElementById('message');
        const floodButton = document.getElementById('flood-button');
        const countButton = document.getElementById('count-button');
        const passButton = document.getElementById('pass-button');
        const resetButton = document.getElementById('reset-button');
        const blueWallsUsedDisplay = document.getElementById('blue-walls-used');
        const redWallsUsedDisplay = document.getElementById('red-walls-used');
        const blueItemsDisplay = document.getElementById('blue-items'); // New
        const redItemsDisplay = document.getElementById('red-items');   // New

        let currentPlayer = 'blue'; // 'blue' or 'red'
        let turnPhase = 1; // 1: Place marker, 2: Choose action
        let actionMode = null; // 'flood' or 'count'
        let wallMode = false; // Indicates if in wall drawing mode
        let firstCorner = null; // Stores first corner selected for wall
        let countNumber = {
            blue: 1,
            red: 1
        };
        let optionalWallDrawn = false; // Tracks optional wall during flood

        // Initialize variables for Fog of War
        const fogSize = 3; // Each fog patch covers 3x3 cells
        const totalPatches = 9; // 3x3 grid of fog patches
        let patchesCleared = 0; // Tracks number of cleared patches
        const maxInitialClearings = 2; // First two clearings do not generate terrain

        const players = {
            blue: {
                name: 'Blue',
                color: 'blue',
                marker: 'O',
                markerPosition: null,
                usedWalls: 0,
                items: '' // New: Collected items
            },
            red: {
                name: 'Red',
                color: 'red',
                marker: 'X',
                markerPosition: null,
                usedWalls: 0,
                items: '' // New: Collected items
            }
        };

        // Initialize game board elements
        function initGameBoard() {
            gameContainer.innerHTML = '';
            // Create cells
            for (let i = 0; i < N; i++) {
                for (let j = 0; j < N; j++) {
                    const cell = document.createElement('div');
                    cell.classList.add('cell');
                    cell.dataset.row = i;
                    cell.dataset.col = j;
                    // Calculate grid positions (1-based indexing)
                    cell.style.gridRowStart = 2 + i * 2; // Cells start at grid-row=2,4,...18
                    cell.style.gridColumnStart = 2 + j * 2;

                    // Create marker, number, and feature containers
                    const markerContainer = document.createElement('div');
                    markerContainer.classList.add('marker-container');
                    markerContainer.id = `marker-${i}-${j}`;

                    const numberContainer = document.createElement('div');
                    numberContainer.classList.add('number-container');
                    numberContainer.id = `number-${i}-${j}`;

                    const featureContainer = document.createElement('div');
                    featureContainer.classList.add('feature-container');
                    featureContainer.id = `feature-${i}-${j}`;

                    cell.appendChild(markerContainer);
                    cell.appendChild(numberContainer);
                    cell.appendChild(featureContainer); // Added feature container

                    cell.addEventListener('click', onCellClick);
                    gameContainer.appendChild(cell);
                }
            }

            // Create corners
            for (let i = 0; i <= N; i++) {
                for (let j = 0; j <= N; j++) {
                    const corner = document.createElement('div');
                    corner.classList.add('corner');
                    corner.dataset.row = i;
                    corner.dataset.col = j;
                    // Corners are at grid rows and columns:1,3,...19
                    corner.style.gridRowStart = 1 + i * 2;
                    corner.style.gridColumnStart = 1 + j * 2;
                    corner.addEventListener('click', onCornerClick);
                    gameContainer.appendChild(corner);
                }
            }

            // Create horizontal walls
            for (let i = 0; i <= N; i++) {
                for (let j = 0; j < N; j++) {
                    const hWall = document.createElement('div');
                    hWall.classList.add('h-wall');
                    hWall.dataset.row = i;
                    hWall.dataset.col = j;
                    // Horizontal walls are between rows
                    hWall.style.gridRowStart = 1 + i * 2;
                    hWall.style.gridColumnStart = 2 + j * 2;
                    hWall.addEventListener('click', onWallClick);
                    gameContainer.appendChild(hWall);
                }
            }

            // Create vertical walls
            for (let i = 0; i < N; i++) {
                for (let j = 0; j <= N; j++) {
                    const vWall = document.createElement('div');
                    vWall.classList.add('v-wall');
                    vWall.dataset.row = i;
                    vWall.dataset.col = j;
                    // Vertical walls are between columns
                    vWall.style.gridRowStart = 2 + i * 2;
                    vWall.style.gridColumnStart = 1 + j * 2;
                    vWall.addEventListener('click', onWallClick);
                    gameContainer.appendChild(vWall);
                }
            }

            // Initialize Fog of War
            initFogOfWar();
        }

        // Initialize Fog of War by creating nine fog patches
        function initFogOfWar() {
            for (let p = 0; p < totalPatches; p++) {
                const patch = document.createElement('div');
                patch.classList.add('fog');

                // Calculate patch position based on patch index
                const patchRow = Math.floor(p / 3);
                const patchCol = p % 3;

                // Each patch covers 3x3 cells
                // Calculate grid row and column starts
                const gridRowStart = 2 + patchRow * 6; // Each patch spans 3 cells (3*2) + 0 walls
                const gridRowEnd = gridRowStart + 5; // Exclusive, spans rows 2 to 7 for patchRow=0
                const gridColStart = 2 + patchCol * 6; // Similarly for columns
                const gridColEnd = gridColStart + 5; // Exclusive

                // Position the fog patch in the grid
                patch.style.gridRowStart = gridRowStart;
                patch.style.gridRowEnd = gridRowEnd;
                patch.style.gridColumnStart = gridColStart;
                patch.style.gridColumnEnd = gridColEnd;

                // Add click handler to remove fog
                patch.addEventListener('click', () => {
                    removeFogPatch(patch);
                });

                gameContainer.appendChild(patch);
            }
        }

        // Remove fog patch and generate terrain if applicable
        function removeFogPatch(patch) {
            patch.style.opacity = '0';
            setTimeout(() => {
                patch.remove();
            }, 300); // Match with CSS transition

            patchesCleared++;

            if (patchesCleared > maxInitialClearings) {
                // Generate terrain features for this patch
                generateTerrainFeatures(patch);
            } else {
                setMessage(`Fog cleared. No terrain generated for the first ${maxInitialClearings} clearings.`, 'blue');
            }
        }
        
    // Corrected generateTerrainFeatures function
    function generateTerrainFeatures(patch) {
        // Determine the patch's grid position
        const gridRowStart = parseInt(patch.style.gridRowStart);
        const gridRowEnd = parseInt(patch.style.gridRowEnd);
        const gridColStart = parseInt(patch.style.gridColumnStart);
        const gridColEnd = parseInt(patch.style.gridColumnEnd);

        // Collect all 12 inner walls within the 3x3 cell area
        const innerWalls = [];

            // Horizontal Inner Walls
            // There are 2 rows of horizontal inner walls within a 3x3 cell area
            for (let rowOffset = 1; rowOffset < 3; rowOffset++) { // Rows 1 and 2 within the patch
                const currentRow = gridRowStart + (rowOffset * 2) - 1; // e.g., 3 and 5
                for (let colOffset = 1; colOffset <= 3; colOffset++) { // 3 horizontal walls per inner row
                    const currentCol = gridColStart + (colOffset * 2) - 2; // e.g., 2, 4, 6
                    const hWallRow = (currentRow - 1) / 2; // Convert to data-row (e.g., 3 -> 1)
                    const hWallCol = (currentCol - 2) / 2; // Convert to data-col (e.g., 2 -> 0)
                    const hWall = document.querySelector(`.h-wall[data-row="${hWallRow}"][data-col="${hWallCol}"]`);
                    if (hWall && !hWall.classList.contains('disabled-wall')) {
                        innerWalls.push(hWall);
                    }
                }
            }
            // Vertical Inner Walls
            // There are 2 columns of vertical inner walls within a 3x3 cell area
            for (let colOffset = 1; colOffset < 3; colOffset++) { // Columns 1 and 2 within the patch
                const currentCol = gridColStart + (colOffset * 2) - 1; // e.g., 3 and 5
                for (let rowOffset = 1; rowOffset <= 3; rowOffset++) { // 3 vertical walls per inner column
                    const currentRow = gridRowStart + (rowOffset * 2) - 2; // e.g., 2, 4, 6
                    const vWallRow = (currentRow - 2) / 2; // MANUAL OFFSET Convert to data-row (e.g., 2 -> 1)
                    const vWallCol = (currentCol - 1) / 2; // Convert to data-col (e.g., 3 -> 1)
                    const vWall = document.querySelector(`.v-wall[data-row="${vWallRow}"][data-col="${vWallCol}"]`);
                    if (vWall && !vWall.classList.contains('disabled-wall')) {
                        innerWalls.push(vWall);
                    }
                }
            }

        // Apply 20% probability to disable each inner wall (turn it into a black wall)
        innerWalls.forEach(wall => {
            if (!isWallPresent(wall) && !wall.classList.contains('disabled-wall')) {
                if (Math.random() < 0.2) { // 20% chance
                    wall.classList.add('disabled-wall');
                    wall.removeEventListener('click', onWallClick); // Disable further clicks
                }
            }
        });

        // Generate terrain features on cells
        generateCellFeatures(gridRowStart, gridColStart, fogSize);

        setMessage('Terrain features generated for the cleared area.', 'green');
        }

        // Generate features for each cell within the fog patch
        function generateCellFeatures(gridRowStart, gridColStart, size) {
            for (let i = 0; i < size; i++) { // Rows within the fog patch
                for (let j = 0; j < size; j++) { // Columns within the fog patch
                    const cellRow = (gridRowStart - 2) / 2 + i; // Adjusted to match cell indices
                    const cellCol = (gridColStart - 2) / 2 + j;
                    const featureContainer = document.getElementById(`feature-${cellRow}-${cellCol}`);
                    
                    // Clear any existing features
                    featureContainer.innerHTML = '';

                    // Generate a random number between 0-99
                    const rand = Math.floor(Math.random() * 100);
                    let feature = null;

                    if (rand < 9) { // 0-8: 9% ITEM
                        feature = generateRandomItem();
                        // Create visual representation of ITEM
                        const itemElement = document.createElement('div');
                        itemElement.classList.add('item-feature');
                        featureContainer.appendChild(itemElement);
                    } else if (rand < 20) { // 9-19: 11% +1
                        feature = +1;
                        featureContainer.textContent = '+1';
                        featureContainer.style.color = 'green';
                    } else if (rand < 22) { // 20-21: 2% +2
                        feature = +2;
                        featureContainer.textContent = '+2';
                        featureContainer.style.color = 'green';
                    } else if (rand < 25) { // 22-24: 3% -1
                        feature = -1;
                        featureContainer.textContent = '-1';
                        featureContainer.style.color = 'red';
                    } else { // 25-99: 75% Empty
                        feature = null;
                    }

                    // Store the feature in the cell's dataset
                    const cell = document.querySelector(`.cell[data-row="${cellRow}"][data-col="${cellCol}"]`);
                    if (cell) {
                        cell.dataset.feature = feature !== null ? feature : '';
                    }
                }
            }
        }

        // Generate a random item (M, W, 1) with equal probability
        function generateRandomItem() {
            const items = ['M', 'W', '1'];
            const index = Math.floor(Math.random() * items.length);
            return items[index];
        }

        // Reset Game
        function resetGame() {
            currentPlayer = 'blue';
            turnPhase = 1;
            actionMode = null;
            wallMode = false;
            firstCorner = null;
            countNumber = {
                blue: 1,
                red: 1
            };
            optionalWallDrawn = false;
            patchesCleared = 0;
            players.blue.markerPosition = null;
            players.red.markerPosition = null;
            players.blue.usedWalls = 0;
            players.red.usedWalls = 0;
            players.blue.items = '';
            players.red.items = '';
            updateStatus();
            updateWallCounters();
            updateItemsDisplay(); // New
            setMessage('');
            disableButtons();
            initGameBoard();
        }

        // Update status display
        function updateStatus() {
            statusDisplay.textContent = `${players[currentPlayer].name} (${players[currentPlayer].marker})`;
            statusDisplay.style.color = players[currentPlayer].color;
        }

        // Update wall counters display
        function updateWallCounters() {
            blueWallsUsedDisplay.textContent = players.blue.usedWalls;
            redWallsUsedDisplay.textContent = players.red.usedWalls;
        }

        // Update items display
        function updateItemsDisplay() { // New
            blueItemsDisplay.textContent = players.blue.items || '-';
            blueItemsDisplay.style.color = players.blue.color;
            redItemsDisplay.textContent = players.red.items || '-';
            redItemsDisplay.style.color = players.red.color;
        }

        // Set message display
        function setMessage(msg, color = 'green') {
            messageDisplay.textContent = msg;
            messageDisplay.style.color = color;
        }

        // Disable action buttons
        function disableButtons() {
            floodButton.disabled = true;
            countButton.disabled = true;
            passButton.disabled = true;
        }

        // Enable action buttons
        function enableButtons() {
            floodButton.disabled = false;
            countButton.disabled = false;
            passButton.disabled = false;
        }

        // Cell click handler
        function onCellClick(e) {
            const cell = e.currentTarget;
            const row = parseInt(cell.dataset.row);
            const col = parseInt(cell.dataset.col);

            if (turnPhase === 1) {
                // Place marker

                // Remove existing marker if any
                if (players[currentPlayer].markerPosition) {
                    const prevPos = players[currentPlayer].markerPosition;
                    const prevMarkerContainer = document.getElementById(`marker-${prevPos.row}-${prevPos.col}`);
                    if (prevMarkerContainer) {
                        const existingMarker = prevMarkerContainer.querySelector(`span[data-player="${currentPlayer}"]`);
                        if (existingMarker) {
                            prevMarkerContainer.removeChild(existingMarker);
                        }
                    }
                }

                // Update marker container without affecting numbers
                const markerContainer = document.getElementById(`marker-${row}-${col}`);
                // Add the marker for the current player
                const existingMarker = markerContainer.querySelector(`span[data-player="${currentPlayer}"]`);
                if (!existingMarker) {
                    const marker = document.createElement('span');
                    marker.textContent = players[currentPlayer].marker;
                    marker.style.color = players[currentPlayer].color;
                    marker.dataset.player = currentPlayer;
                    markerContainer.appendChild(marker);
                }

                // Update marker position for the player
                players[currentPlayer].markerPosition = { row, col };

                // Collect ITEM if present
                collectItemIfPresent(cell, row, col);

                // Enable action buttons
                enableButtons();

                // Move to next turn phase
                turnPhase = 2;
                setMessage('Marker placed. Choose an action.');
            } else if (turnPhase === 2) {
                if (actionMode === 'flood') {
                    const success = performFloodFill(row, col);
                    if (success) {
                        actionMode = null;
                        endTurn();
                    } else {
                        // Do not end turn, allow player to retry
                        setMessage('Flood Fill failed. The area is not fully enclosed. Please try again or choose to pass the turn.', 'red');
                    }
                } else if (actionMode === 'count') {
                    placeCount(cell);
                }
            }
        }

        // Collect ITEM if present when a marker is placed
        function collectItemIfPresent(cell, row, col) { // New
            const feature = cell.dataset.feature;
            if (typeof feature === 'string' && feature.length === 1 && ['M', 'W', '1'].includes(feature)) {
                // It's an ITEM
                players[currentPlayer].items += feature;
                updateItemsDisplay();
                setMessage(`Collected item: ${feature}`, players[currentPlayer].color);
                // Remove the feature from the cell
                const featureContainer = document.getElementById(`feature-${row}-${col}`);
                featureContainer.innerHTML = '';
                cell.dataset.feature = '';
            }
        }

        // Corner click handler
        function onCornerClick(e) {
            if (turnPhase !== 2) {
                return;
            }
            const corner = e.currentTarget;
            const row = parseInt(corner.dataset.row);
            const col = parseInt(corner.dataset.col);

            if (wallMode) {
                // Second corner click
                const dist = Math.abs(firstCorner.row - row) + Math.abs(firstCorner.col - col);
                if ((firstCorner.row === row || firstCorner.col === col) && (dist === 1 || dist === 2)) {
                    const success = drawWallBetweenCorners(firstCorner, { row, col }, currentPlayer);
                    if (success) {
                        setMessage('Wall drawn successfully.', 'green');
                        players[currentPlayer].usedWalls += 1;
                        updateWallCounters();
                        if (actionMode === 'flood') {
                            // During flood, allow drawing only one optional wall
                            optionalWallDrawn = true;
                            // Remain in action mode 'flood' to allow flood fill
                        } else {
                            // Normally, end the turn after drawing a wall
                            endTurn();
                        }
                    } else {
                        setMessage('Failed to draw wall. It might already exist.', 'red');
                    }
                    // Reset wall drawing state
                    wallMode = false;
                    firstCorner.element.style.backgroundColor = '#666';
                    firstCorner = null;
                } else {
                    setMessage('Second corner must be adjacent horizontally or vertically.', 'red');
                }
            } else {
                // First corner click
                if (actionMode === 'flood' && optionalWallDrawn) {
                    // Already drew optional wall during flood
                    setMessage('Optional wall already drawn for this flood action.', 'red');
                    return;
                }

                // Check if corner is adjacent to the current player's marker position
                const markerPos = players[currentPlayer].markerPosition;
                if (markerPos && isCornerAdjacentToCell(row, col, markerPos.row, markerPos.col)) {
                    wallMode = true;
                    firstCorner = { row, col, element: corner };
                    corner.style.backgroundColor = players[currentPlayer].color;
                    if (actionMode === 'flood') {
                        setMessage('Select the second corner to draw the optional wall.', 'blue');
                    } else {
                        setMessage('Select the second corner to draw the wall.', 'blue');
                    }
                } else {
                    setMessage('Select a corner adjacent to your marker cell.', 'red');
                }
            }
        }

        // Wall click handler (to prevent walls from being clickable)
        function onWallClick(e) {
            // Currently, walls are drawn via corner clicks. Clicking walls themselves does nothing.
            // If additional functionalities are desired (e.g., removing walls), implement here.
        }

        // Check if corner is adjacent to cell
        function isCornerAdjacentToCell(cornerRow, cornerCol, cellRow, cellCol) {
            const cellCorners = getCellCorners(cellRow, cellCol);
            return cellCorners.some(c => c.row === cornerRow && c.col === cornerCol);
        }

        // Get corners of a cell
        function getCellCorners(cellRow, cellCol) {
            const topLeft = { row: cellRow, col: cellCol };
            const topRight = { row: cellRow, col: cellCol + 1 };
            const bottomLeft = { row: cellRow + 1, col: cellCol };
            const bottomRight = { row: cellRow + 1, col: cellCol + 1 };
            return [topLeft, topRight, bottomLeft, bottomRight];
        }

        // Draw wall between two corners
        // Returns true if wall was successfully drawn, false otherwise
        function drawWallBetweenCorners(corner1, corner2, player) {
            let wallsDrawn = [];

            if (corner1.row === corner2.row) {
                // Horizontal wall(s)
                const minCol = Math.min(corner1.col, corner2.col);
                const maxCol = Math.max(corner1.col, corner2.col);
                for (let col = minCol; col < maxCol; col++) {
                    const hWall = document.querySelector(`.h-wall[data-row="${corner1.row}"][data-col="${col}"]`);
                    if (hWall) {
                        if (isWallPresent(hWall)) {
                            // Wall already exists
                            return false;
                        }
                        hWall.style.backgroundColor = players[player].color;
                        wallsDrawn.push(hWall);
                    }
                }
            } else if (corner1.col === corner2.col) {
                // Vertical wall(s)
                const minRow = Math.min(corner1.row, corner2.row);
                const maxRow = Math.max(corner1.row, corner2.row);
                for (let row = minRow; row < maxRow; row++) {
                    const vWall = document.querySelector(`.v-wall[data-row="${row}"][data-col="${corner1.col}"]`);
                    if (vWall) {
                        if (isWallPresent(vWall)) {
                            // Wall already exists
                            return false;
                        }
                        vWall.style.backgroundColor = players[player].color;
                        wallsDrawn.push(vWall);
                    }
                }
            } else {
                // Diagonal walls are not allowed
                return false;
            }

            // If all walls drawn successfully, update counts
            if (wallsDrawn.length > 0) {
                return true;
            } else {
                return false;
            }
        }

        // Flood button handler
        floodButton.addEventListener('click', () => {
            if (actionMode !== null) return;
            actionMode = 'flood';
            optionalWallDrawn = false;
            setMessage('Flood mode activated. Optionally draw one wall adjacent to your marker, then click on a cell to perform flood fill.', 'blue');
            // Enable wall drawing; Flood mode manages walls differently
        });

        // Count button handler
        countButton.addEventListener('click', () => {
            if (actionMode !== null) return;
            actionMode = 'count';
            setMessage('Count mode activated. Click on cells to place counts. Click Pass Turn when done.', 'blue');
        });

        // Pass button handler
        passButton.addEventListener('click', () => {
            endTurn();
        });

        // Reset button handler
        resetButton.addEventListener('click', () => {
            resetGame();
        });

        // Perform Flood Fill
        function performFloodFill(startRow, startCol) {
            const visited = new Set();
            const fillColor = currentPlayer === 'blue' ? 'filled' : 'filled-red';
            const queue = [{ row: startRow, col: startCol }];
            let isEnclosed = true;

            while (queue.length > 0) {
                const { row, col } = queue.shift();
                const key = `${row},${col}`;
                if (visited.has(key)) continue;
                visited.add(key);

                // Check if cell is on boundary WITHOUT a wall blocking the flood
                if (
                    (row === 0 && (!isWallPresent(getCellWalls(row, col).top))) ||
                    (row === N - 1 && (!isWallPresent(getCellWalls(row, col).bottom))) ||
                    (col === 0 && (!isWallPresent(getCellWalls(row, col).left))) ||
                    (col === N - 1 && (!isWallPresent(getCellWalls(row, col).right)))
                ) {
                    isEnclosed = false;
                }

                // Check all four directions
                const walls = getCellWalls(row, col);

                // Top
                if (!walls.top || !isWallPresent(walls.top)) {
                    if (row > 0) {
                        queue.push({ row: row - 1, col });
                    }
                }

                // Bottom
                if (!walls.bottom || !isWallPresent(walls.bottom)) {
                    if (row < N - 1) {
                        queue.push({ row: row + 1, col });
                    }
                }

                // Left
                if (!walls.left || !isWallPresent(walls.left)) {
                    if (col > 0) {
                        queue.push({ row, col: col - 1 });
                    }
                }

                // Right
                if (!walls.right || !isWallPresent(walls.right)) {
                    if (col < N - 1) {
                        queue.push({ row, col: col + 1 });
                    }
                }
            }

            if (isEnclosed) {
                // Fill the area
                visited.forEach(key => {
                    const [row, col] = key.split(',').map(Number);
                    const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
                    if (cell) {
                        cell.classList.add(fillColor);
                    }
                });
                setMessage('Area is enclosed. Flood Fill completed!', 'green');
                return true;
            } else {
                setMessage('Area is not fully enclosed. Flood Fill failed.', 'red');
                return false;
            }
        }

        // Get walls around a cell
        function getCellWalls(row, col) {
            const walls = {};

            // Top wall
            walls.top = document.querySelector(`.h-wall[data-row="${row}"][data-col="${col}"]`);

            // Bottom wall
            walls.bottom = document.querySelector(`.h-wall[data-row="${row + 1}"][data-col="${col}"]`);

            // Left wall
            walls.left = document.querySelector(`.v-wall[data-row="${row}"][data-col="${col}"]`);

            // Right wall
            walls.right = document.querySelector(`.v-wall[data-row="${row}"][data-col="${col + 1}"]`);

            return walls;
        }

        // Check if wall is present (colored)
        function isWallPresent(wall) {
            if (!wall) return false;
            const bgColor = window.getComputedStyle(wall).backgroundColor;
            // Transparent walls have RGBA(0, 0, 0, 0) or 'transparent'
            return bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent';
        }

        // Place count on cell
        function placeCount(cell) {
            const row = parseInt(cell.dataset.row);
            const col = parseInt(cell.dataset.col);
            const numberContainer = document.getElementById(`number-${row}-${col}`);

            if (numberContainer.textContent) {
                setMessage('Cell already has a number.', 'red');
                return;
            }

            const number = countNumber[currentPlayer]++;
            numberContainer.textContent = number;
            numberContainer.style.color = players[currentPlayer].color;
            setMessage('Count placed.', 'green');
        }

        // End turn
        function endTurn() {
            // Reset variables
            turnPhase = 1;
            actionMode = null;
            wallMode = false;
            firstCorner = null;
            optionalWallDrawn = false;

            // Disable action buttons
            disableButtons();

            // Swap player
            currentPlayer = currentPlayer === 'blue' ? 'red' : 'blue';
            updateStatus();
            setMessage('Turn passed to the next player.', 'blue');
        }

        // Initialize the game
        resetGame();
    </script>
</body>
</html>