Create Minesweeper Like Game
Show older comments
I create this board with my code:
1 2 3 4 5
1x x x x x
2x x x x x
3x k x x x
4x x x k x
5x x x x x
I want to replace the board above with the board below, that is all the 'k'='*' and any values surrounding k have a counter.
1 2 3 4 5
10 0 0 0 0
21 1 1 0 0
31 k 2 1 1
41 1 2 k 1
50 0 1 1 1
How would I go about doing this?
2 Comments
Walter Roberson
on 1 Dec 2015
I do not understand about 'k'='*', and it is not clear why the x became 0 in places that are not surrounding k.
Image Analyst
on 1 Dec 2015
k is where a bomb resides. The other numbers are the number of 8-connected bombs that are next to that location. For example, row 3, column 3 is next to 2 bombs, so it's a 2. Row 3, column 4 is next to only one k, so it has a value of 1. Same as in the minesweeper game.
Accepted Answer
More Answers (1)
Guillaume
on 1 Dec 2015
Please, use valid matlab syntax in your question, so we don't have to guess if the input is a cell array, a char array, or something else, and whether the spaces and headers are embedded in the matrix or not
Possibly:
in = ['xxxxx';
'xxxxx';
'xkxxx';
'xxxkx';
'xxxxx'];
%step 1: convert the input matrix into an array of 0 and 1, 1 where k is present
%if your input matrix is a different format, you'll have to figure how to do it on your own
inaslogical = in == 'k';
%step2: convolve the array of 0 and 1 with an array of 1:
out = conv2(double(inaslogical), ones(3), 'same')
2 Comments
Krish Desai
on 1 Dec 2015
Guillaume
on 1 Dec 2015
Note: don't use the name size for a variable as you won't be able to use the extremely useful size function.
A more efficient way to generate your board:
function board = makeboard(boardsize)
symbols = 'xk';
playarea = num2cell(symbols(1 + (rand(boardsize) < 1/5)));
header = num2cell(1:boardsize);
board = [{[]}, header; header', playarea];
end
The gist of my answer (and IA's answer) still stands. You need to convert your play area into a logical array, where 1 stands for a mine. Then convolve with a square of 1 to get the number of neighbours.
With the given format:
ismine = cell2mat(board(2:end, 2:end)) == 'k';
neighbourcount = conv2(double(ismine), ones(3), 'same');
neighbourcount = num2cell(neighbourcount);
neighbourcount(ismine) = {'k'};
newboard = board;
newboard(2:end, 2:end) = neighbourcount;
Categories
Find more on Board games 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!