<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>球球大作战</title>
<style>
section {
width: 150px;
height: 30px;
font-size: 24px;
color: red;
background-color: rgba(0, 0, 0, 0.479);
position: relative;
left: 50%;
margin-left: -75px;
letter-spacing: 5px;
text-align: center;
line-height: 30px;
display: none;
margin-bottom: 10px;
z-index: 999;
}
span {
font-size: 20px;
color: red;
}
p {
position: relative;
z-index: 999;
}
</style>
</head>
<body>
<p>连续击破<span class="num">0</span>个小球</p>
<p>累计获得球内积分:<span class="score">0</span></p>
<section>开始游戏</section>
<section>游戏结束</section>
<section>重新开始</section>
</body>
</html>
<script>
var oStart = document.querySelectorAll("section");//开始游戏
oStart[0].style.display = "block";
oStart[0].onclick = function () {
var timer = setInterval(fun, 1000);
oStart[0].style.display = "none";
function fun() {
var x = Math.ceil(Math.random() * 1200)//随机宽度
var y = Math.ceil(Math.random() * 600)//随机高度
var f = Math.ceil(Math.random() * 100)//随机分数
var size = Math.ceil(Math.random() * (200 - 50) + 50);//随机大小
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
var str = '#';
for (var i = 0; i < 6; i++) {
var index = Math.floor(Math.random() * 16);
str += arr[index];
}
// console.log(str);
// console.log(w, h);
// console.log(x, y, size);
//创建随机小球
var Div = document.createElement('div')
Div.innerText = `${f}`;
Div.classList = "box"//添加类名
Div.style.cssText = `width: ${size}px; height: ${size}px; background-color: royalblue; position: absolute;border-radius: 50%;left: ${x}px; top: ${y}px;background-color:${str}; text-align: center;line-height:${size}px;`
document.body.appendChild(Div);
var oNum = document.querySelector(".num")//个数
var oScore = document.querySelector(".score")//得分
var oBox = document.getElementsByClassName("box");//获取当前页面小球的个数
var num = 0;
var score = 0;
//点击小球消失
Div.onclick = function () {
this.remove();
// console.log(123);
num++;
// console.log(num);
//计算个数
oNum.innerText = oNum.innerText / 1 + num;
// console.log(typeof oNum.innerText)
//计算得分
oScore.innerText = oScore.innerText / 1 + Div.innerText / 1;
}
// console.log(oBox.length);
//判读游戏结束
if (oBox.length >= 5) {
clearInterval(timer)
for (var i = 0; i < oBox.length; i++) {
oBox[i].onclick = null;//游戏结束关闭点击小球事件
}
oStart[1].style.display = "block";
oStart[2].style.display = "block";
};
//重新开始,页面数据清零
oStart[2].onclick = function () {
for (var i = oBox.length - 1; i >= 0; i--) {
oBox[i].parentNode.removeChild(oBox[i])//清空所有小球
}
oNum.innerText = 0;
oScore.innerText = 0;
oStart[1].style.display = "none";
oStart[2].style.display = "none";
timer = setInterval(fun, 800)
};
}
}
</script>
<style>
body {
background-color: pink;
}
</style>