I am creating a simple minesweeper game for an assignment, but I am having trouble making the program determine whether the player has won or not. I am trying to find a function that determines whether any of the elements of A are equal to -2 and then use that in a while loop.

I have a simplified test code that I have been using to try to do this, but I can't find any functions that do what I want to do.

With everything I've tried so far, it either just keeps asking for more input even when it should say that the game is over, or it skips the while loop entirely. The last thing probably happens because all the elements of the start array are equal.

I have looked at xor, unique, setdiff, intersect, ismember isempty, and probably a couple more that I can't remember.

As this is not the complete code, I have just answered yes to the flag question every time in order to change all the elements from -2 to -3.

I also know that this wouldn't be the best way to determine whether the player has won or not, as it doesn't take into consideration if all the flags are placed correctly, but I wanna sort this part out first before I get on to that:)


for r=1:2
    for c=1:2

while % any of the elements in A are equal to -2
    while selected~=-1 
        selectRow=input('Which row is the cell you would like to access on? ');
        selectCol=input('Which column is the cell you would like to access on? ');
        selectFlag=input('Would you like to put a flag in this cell? ','s');
        if selectRow<=2 && selectRow>=1 && selectCol<=2 && selectCol>=1
            while strcmp(selectFlag, 'yes') || strcmp(selectFlag, 'no')
                if strcmp(selectFlag, 'yes')
                elseif strcmp(selectFlag, 'no')
fprintf('You have hit a mine. Please restart.\n');

fprintf('Congrats! You have won!');

1 Answers

SecretAgentMan On

There are multiple ways to know if an entry of A is equal to -2 and how to interact with the location of all those entries.

The any function
As suggested by @etmuse and @Wolfie in the comments, the any function may be best here. Notice in the documentation that more advanced options are available for versions R2018b and later.

% MATLAB R2017a
rng(8675309)                % For reproducibility (ensure some -2 appear)
A = randi([-4 0],4)         % Generate example matrix
any(A == -2,1)              % Test columns of A
any(A == -2,2)              % Test rows of A

Logical Index

% Use a logical index
idx = (A == -2)

It is a bit trickier to use the indices.

% Use the indices directly.
ind = find(A==-2) 

Notice this gives you the indices if the array A were converted to vector form.

A(:)                            % Force column vector
reshape(A(:),4,4)'              % Reshape into matrix

Disclosure: If @etmuse or @Wolfie post answer with any function, will remove that from my answer or make this community wiki. It was their idea.