Create Minesweeper Like Game
이전 댓글 표시
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
Walter Roberson
2015년 12월 1일
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
2015년 12월 1일
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.
채택된 답변
추가 답변 (1개)
Guillaume
2015년 12월 1일
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
Krish Desai
2015년 12월 1일
Guillaume
2015년 12월 1일
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;
카테고리
도움말 센터 및 File Exchange에서 Strategy & Logic에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!