以下是一个用MATLAB实现的简单打地鼠游戏的代码:
% 游戏参数设置
num_holes = 9; % 地洞数量
num_rounds = 5; % 游戏回合数
% 初始化游戏状态
score = 0; % 分数
holes = zeros(1, num_holes); % 地洞状态:0代表没出现地鼠,1代表出现地鼠
game_over = false; % 游戏结束标志
% 游戏主循环
for round = 1:num_rounds
% 显示当前分数和地洞状态
disp(['Round ', num2str(round)]);
disp(['Score: ', num2str(score)]);
disp(holes);
disp('----------------------------');
% 生成地鼠出现的地洞
index = randi(num_holes);
holes(index) = 1;
% 玩家选择地洞
choice = input('Choose a hole: ');
% 检查玩家选择的地洞是否有地鼠
if holes(choice) == 1
score = score + 1;
disp('You hit the mole!');
else
disp('You missed!');
end
% 清空地洞状态
holes = zeros(1, num_holes);
% 判断游戏是否结束
if score >= num_holes
disp('Game over!');
game_over = true;
break;
end
end
% 如果游戏没有在规定回合内结束,则显示最终得分
if ~game_over
disp(['Final score: ', num2str(score)]);
end
使用以上代码,玩家可以在每个回合中选择一个地洞进行打击,并根据是否击中地鼠获得分数。游戏在达到指定的回合数或者玩家获得足够分数时结束,并显示最终得分。