MATLAB: Create Minesweeper Like Game

arrayfor loopgameif statement

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?

Best Answer

Just use conv2() to count the bombs:
gameBoard = [...
'0' '0' '0' '0' '0'
'1' '1' '1' '0' '0'
'1' 'k' '2' '1' '1'
'1' '1' '2' 'k' '1'
'0' '0' '1' '1' '1']
% Find the bombs.
bombLocations = gameBoard == 'k'
% Sum up the bombs in a surrounding 3x3 window around each pixel.
nearbyBombs = conv2(double(bombLocations), ones(3), 'same')
% Create a new board that is characters and instead of numbers.
newBoard = num2str(nearbyBombs, '%1d')
% Replace the bomb locations with the letter k.
newBoard(bombLocations) = 'k'
You'll see:
gameBoard =
00000
11100
1k211
112k1
00111
bombLocations =
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 1 0
0 0 0 0 0
nearbyBombs =
0 0 0 0 0
1 1 1 0 0
1 1 2 1 1
1 1 2 1 1
0 0 1 1 1
newBoard =
00000
11100
11211
11211
00111
newBoard =
00000
11100
1k211
112k1
00111