<script type="text/javascript">
//初始化地图
function initMap(){
var rowNum = 10; //行数
var colNum = 10; //列数
for(let row = 0; row < rowNum; row++){
for(let col = 0; col < colNum; col++){
let button = document.createElement("button"); //动态创建button元素
button.style.width = "30px"; //定义宽度
button.style.height = "30px"; //定义高度
button.style.backgroundColor = "rgb(211,211,211)"; //定义背景色
//当点击按钮时
button.onclick = function(){
//获取当前点击的按钮的位置
let x = this.getAttribute("x");
let y = this.getAttribute("y");
//发现地雷
if(x == 4 && y == 4){
alert('Game Over!');
return;
}
//未发现地雷
else{
this.style.backgroundColor = "white"; //解锁按钮
}
};
//定义每个按钮的x,y坐标属性
button.setAttribute("x",row);
button.setAttribute("y",col);
//在页面中显示按钮
document.body.appendChild(button);
}
//换行
let lineBreak = document.createElement("br");
document.body.appendChild(lineBreak);
}
}
//启动游戏
initMap();
</script>
————————————————————————————————————————————关注小世学长不迷路,带你看更多小程序(小游戏)!!!
该代码段展示了一个使用JavaScript编写的简单地雷游戏。通过循环创建10x10的按钮网格,每个按钮有x和y坐标属性。当点击特定位置(如x=4,y=4)的按钮时,触发GameOver警告,否则改变按钮背景色表示已被检查。

249

被折叠的 条评论
为什么被折叠?



