Search code examples
matlabmatlab-figure

how can I edit grids on a battleship board to represent ships in Matlab


I am using subplot() and pcolor(zeros(7,7)); to produce the following figure for a battleship game (please see link below). Im trying to change the color of specific grids to represent ships, but I can't figure it out, so can I please get help with this, I need to for example change grids 22 and 23 in "your board" to red and have the existing figure updated, not get a new figure.


Solution

  • It's easiest if you set up a function to create/colour a specific square, then this is trivial, and can be recycled throughout your game. Below I've made the local function drawSquare(bs,N,player,color) which accepts a board size (bs), square number (N), a player ('top' or 'bottom'), and a colour, which can be any valid MATLAB colorspec.

    Then I've made another function setup(bs) which calls this a bunch of times to create the "board" for each player.

    Then you can see it's as simple as calling drawSquare( bs, 3, 'top', 'r' ); to turn the top player's square number 3 red.

    Equally it's easy to call drawSquare( bs, 4, 'top', [0.6,0.5,0.5] ); to colour square 4 for that player a grey-ish tone to show something like a "hit" square in the battleships game.

    board

    figure(100);
    bs = 6; % board size
    % Initialise the board
    setup( bs );
    % Example usage colouring in specific squares
    drawSquare( bs, 3, 'top', 'r' )
    drawSquare( bs, 4, 'top', [0.6,0.5,0.5] );
    
    function setup( bs )
        clf; % clear the board
        for ii = 1:(bs^2)
            % Loop over all squares, make the base boards
            drawSquare( bs, ii, 'top', 'w' );
            drawSquare( bs, ii, 'bottom', 'w' );
        end
        % Format the plots without ticks and with titles
        subplot( 2, 1, 1 );
        set( gca, 'XTickLabel', '', 'YTickLabel', '', 'BoxStyle', 'full' );
        title( 'Computer Board' );
        subplot( 2, 1, 2 );
        set( gca, 'XTickLabel', '', 'YTickLabel', '', 'BoxStyle', 'full' );
        title( 'Your Board' );
    end
    
    function drawSquare( bs, N, player, color )
        % sq = square size, N = square number, player = 'top' or 'bottom'
        % color = valid plot colour for different square types
        x = mod(N-1,bs);        % x axis in grid
        y = floor( (N-1)/bs );  % y axis in grid
        if strcmpi( player, 'top' )
            subplot( 2, 1, 1 ); % top player is subplot 1
            x = bs - x;         % top player square 1 is bottom-right
        else
            subplot( 2, 1, 2 ); % bottom player is subplot 2
            y = bs - y;         % bottom player square 1 is top-left
        end
        xp = [x, x+1, x+1, x];  % x coordinates of grid square
        yp = [y, y, y+1, y+1];  % y coordinates of grid square
        patch( xp, yp, color ); % use patch to make coloured square
        text( x+(1/2), y+(1/2), num2str(N), 'HorizontalAlignment', 'center' );
    end