Code covered by the BSD License  

Highlights from
BattleShip (R)

image thumbnail

BattleShip (R)

by

 

23 Oct 2008 (Updated )

Learn and have fun with an old classic.

atboard
function obj = atboard
%  	Author: Isaac Noh
%   Copyright 2008-2009 The MathWorks, Inc.
%   Version: 1.1


% Create the Attack Board
[grid, ghandles] = creategrid;
obj.grid = grid;
obj.ghandles = ghandles;
obj.bhandle = createbutton;
set(obj.bhandle,'Callback',@fire_cbfcn);


% Callback function for PUSHBUTTON
    function fire_cbfcn(hObject,eventdata)
        % Check the values of the attack points
        gh = logical(cell2mat(get(obj.ghandles,'Value')));
        if sum(gh) ~= 1
            str = 'You must choose one target.';
            warndlg(sprintf(str));
        else

            u1 = guidata(gcbo);
            target = obj.grid(gh);
            fprintf(u1,target.getlocation());
            set(hObject,'Enable','off');

        end
    end

% Create the grid
    function [grid, handle] = creategrid

        vert = 0.935;
        hor = 0.1;

        obj.axhandle = axes('XGrid','on',...
            'YGrid','on',...
            'GridLineStyle','-',...
            'XLimMode','manual',...
            'YLimMode','manual',...
            'XTick',[0:.1:1],...
            'YTick',[0:.1:1],...
            'XTickLabel','',...
            'YTickLabel','',...
            'Units','normalized',...
            'Position',[0.14 0.535 0.6 0.4],...
            'Color',[0 0 .7]);
        
        % Pre-allocate memory
        grid(10,10) = atgridpt;
        handle = zeros(10);
        
        for i = 1:10
            col = num2str(i);
            for j = 1:10
                row = char(j+64);
                grid(i,j) = atgridpt([hor+(0.06*i) vert+(0.01-0.04*j) 0.03 0.02],row,col);
                grid(i,j).setlocation([char(j+64) num2str(i)]);
                handle(i,j) = grid(i,j).handle;
                uicontrol('Style','text',...
                    'Units','normalized',...
                    'Position',[hor vert+(0.0075-0.04*j) 0.03 0.02],...
                    'String',row,...
                    'BackgroundColor',[0.8 0.8 0.8])
            end
            uicontrol('Style','text',...
                'Units','normalized',...
                'Position',[hor-0.005+(0.06*i) vert+0.0075 0.03 0.02],...
                'String',col,...
                'BackgroundColor',[0.8 0.8 0.8])
        end
    end

% Create the PUSHBUTTON
    function fire = createbutton
        fire = uicontrol('Style','pushbutton',...
            'Units','normalized',...
            'Position',[0.8 0.925 0.1 0.025],...
            'String','Fire',...
            'Enable','off');
    end
end

Contact us