How do I create a counter on a GUI?

3 views (last 30 days)
Mohd Iramul Hoque
Mohd Iramul Hoque on 13 Apr 2015
Answered: Jan on 13 Apr 2015
So basically, we're trying to create battleship on matlab and we have a functioning source code which makes the use of a matrix of zeros and ones and assigns each index to one of the push buttons. The player is given 10 tries to hit 6 ships on a 4x4 grid. The problem we are having is that everytime we press one of the push buttons, the counter is reset to 0 instead of being updated each and every time the push button is pressed.
Here's some of the code:
% --- Executes just before M5_BoatWars_easy_17 is made visible.
function M5_BoatWars_easy_17_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to M5_BoatWars_easy_17 (see VARARGIN)
% Choose default command line output for M5_BoatWars_easy_17
handles.output = hObject;
handles.bombs=0;
while 1
handles.x=round((1-0).*rand(4,4)) %matrix of zeros and ones
if (length(find(handles.x))==6)
break;
end
end
disp(handles.x)
handles.y=length(find(handles.x)); %number of ships
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes M5_BoatWars_easy_17 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = M5_BoatWars_easy_17_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pb_1.
function pb_1_Callback(hObject, eventdata, handles)
% hObject handle to pb_1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(hObject,'value',handles.x(1,1));
a=get(hObject,'value');
handles.bombs=handles.bombs+1;
if a==1
set(hObject,'string','Hit');
set(hObject,'Backgroundcolor','r');
else
set(hObject,'string','Miss');
set(hObject,'Backgroundcolor','b');
end
guidata(hObject, handles);
[EDITED, Jan, Please apply a proper code formatting - thanks]

Answers (1)

Jan
Jan on 13 Apr 2015
Insert this line on the top of each callback to get the current value of the handles struct, and not the one from the definition of the callbacks during the creation of the GUI:
handles = guidata(hObject);

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!