用MATLAB写个扫雷游戏
clc;clear;close all;
%% 初始化游戏参数
% 设置地雷数量以及地图大小(长宽)
bombNum = 20; % 地雷数量
mapSize = 8; % 地图大小,长宽均为8格
map = zeros(mapSize); % 生成一个全0的地图
%% 随机放置地雷
% 随机生成 bombNum 个在 mapSize 范围内的坐标
randPos = randi([1, mapSize], [bombNum, 2]);
for ii=1:length(randPos)
map(randPos(ii, 1), randPos(ii, 2)) = -1; % 根据随机坐标赋值 -1 表示该位置是雷
end
%% 根据雷的位置,赋予周围八个方向的数字
for ii=2:mapSize-1 % 去掉边界处理
for jj=2:mapSize-1
if map(ii, jj) == -1 % 该位置是雷,则跳过
continue;
else % 该位置不是雷
aroundBombNum = 0 ; % 统计该位置周围八个方向上的地雷数量
for kk=-1:1 % 遍历该位置周围八个方向
for ll=-1:1 if map(ii+kk, jj+ll) == -1 aroundBombNum = aroundBombNum + 1 ; end end end if aroundBombNum ~= 0 map(ii,jj) = aroundBombNum ; end end end end %% 显示扫雷界面 figure('Name','扫雷','NumberTitle','off'); imagesc (map); colormap (flipud (gray)); axis equal off ; title('扫 雷') ;
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!