刚睡觉起来,有个童鞋问我原生写地鼠游戏难不难?
回答:“你理清打地鼠游戏的逻辑关系,就不难,半个钟都要不了。
然后不信。。。于是就。。。现场写了个给他
ps: 我觉得,写东西,重点在于逻辑。
打地鼠常见功能有:
- 1.背景图与老鼠随机显示与隐藏;
- 2.点击时累计积分或者信息提示;
- 3.在规定时间内,自动结束游戏;
- 4.停止、退出、重玩游戏。
*** 基本就这样子?***
现在就简单了,写样式,根据功能需求写逻辑代码;
结构与样式
<style>
* {
padding: 0;
}
html,
body {
width: 90%;
height: 80%;
background-color: grey;
}
h1 {
text-align: center;
}
#box {
width: 90%;
height: 93%;
}
.contbox {
width: 100%;
height: 100%;
margin: auto;
margin-top: 6%;
border: 1px solid greenyellow;
display: flex;
flex-wrap: wrap;
position: relative;
}
.minbox {
width: 32%;
height: 32%;
border: 1px solid hotpink;
margin-left: 1%;
}
.minbox img {
width: 100%;
height: 100%;
}
.textbox {
position: absolute;
top: 55px;
font-size: 26px;
color: #f4f4f4;
}
</style>
<body>
<h1>打地鼠游戏V01版</h1>
<div id="box">
<div class="contbox"></div>
<div class="textbox">
<span class="stops">停止游戏</span>||
<span>信息提示处:</span>
<span class="textboxs"></span>
</div>
</div>
</body>
效果如下:
js行为
var contBox = document.querySelector('.contbox');
var textBoxs = document.querySelector('.textboxs');
var stops = document.querySelector('.stops');
let mouseArr = [];
let jsNum1 = 0, jsNum2 = 0;//计数器
mouseArr.length = 9;//定义盒子个数
for (let i = 0; i < mouseArr.length; i++) {
contBox.innerHTML += `<div class="minbox"><img src='./img/greenbelt.jpg'alt></div>`
}
// 获取img标签
var minBox = document.querySelectorAll('img');
// 封装老鼠随机出现
function showMouse() {
var num = Math.floor((Math.random() * minBox.length));
minBox[num].src = './img/mouse.gif';
setTimeout(`minBox[${num}].src = './img/greenbelt.jpg'`, 900);
}
// 启动游戏
var mouseStart = setInterval(showMouse, 1500);
// 敲打老鼠
for (let i = 0; i < mouseArr.length; i++) {
minBox[i].onclick = function () {
let str = 'mouse';
if (minBox[i].src.indexOf(str) < 0) {
jsNum1++;
textBoxs.innerText = '菜鸡,你第' + jsNum1 + '次没打到他了';
} else {
jsNum2++;
textBoxs.innerText = '秀儿,你第' + jsNum2 + '次打到他了';
}
}
}
// 停止游戏
stops.onclick = function () {
clearInterval(mouseStart);
alert('游戏已经停止');
}
本文地址:https://blog.csdn.net/m0_46442996/article/details/107593413
如对本文有疑问, 点击进行留言回复!!
2016年信息安全工程师综合知识第11-15题解析【建群网培信息安全工程师】
网友评论