<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
background: black;
}
.box{
width: 400px;
height: 600px;
background: white;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.start{
position: absolute;
top:0;
left: 0;
width: 400px;
height: 70px;
background: white;
color: #000;
font-size: 50px;
font-weight: bolder;
text-align: center;
line-height: 70px;
border-bottom: 1px solid #222;
z-index: 99;
}
.gameStatus{
width: 400px;
height: 50px;
margin: 0 auto;
background: white;
border-top: 1px solid #222;
color: #000;
font-size: 20px;
font-weight: bolder;
text-align: center;
line-height: 50px;
}
.main{
width: 400px;
height: 600px;
position: relative;
top:-150px;
}
.row{
width: 400px;
height: 150px;
}
.col{
width: 99px;
height: 150px;
float: left;
border: 1px solid #333;
border-top: 0;
border-right: 0;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="start" id="start"></div>
<div class="main" id="main"></div>
</div>
<div class="gameStatus" id="gameStatus"></div>
<script>
window.onload = function () {
var box = document.getElementById("box");
var start = document.getElementById("start");
var main = document.getElementById("main");
var gameStatus = document.getElementById("gameStatus");
var timer = null;
var speed = 5;
var score = 0;//计数的
start.innerHTML = "开始游戏";
start.onclick = function () {
if(main.children.length){
main.innerHTML = "";
}
start.style.display = "none";
gameStatus.innerHTML ="游戏开始";
cDiv();
timer =setInterval(function () {
main.style.top = main.offsetTop + speed + "px";
if(main.offsetTop === 0){
main.style.top = -150 + "px";
cDiv();
}
if(main.children.length === 6){
for(var i = 0; i < 4;i++){
if(main.children[main.children.length-1].children[i].key === "i"){
clearInterval(timer);
start.style.display = "block";
gameStatus.innerHTML = "游戏结束";
start.innerHTML = "重新开始";
score = 0;
}
}
main.removeChild(main.children[main.children.length - 1]);
}
},30);
};
function cDiv() {
var rowDiv = document.createElement("div");
rowDiv.className = "row";
//控制生成的div中哪一个被设置了颜色
var index = parseInt(Math.random() * 4);
for(var i = 0 ; i < 4 ; i++){
var colDiv = document.createElement("div");
colDiv.className = "col";
if(i === index){
colDiv.style.background = "black";
colDiv.key = "i";
}
colDiv.onclick = function () {
if(this.key === "i"){
this.style.backgroundColor = "#666";
this.key = "";
score++;
}else {
//游戏结束
clearInterval(timer);
start.style.display = "block";
gameStatus.innerHTML = "游戏结束,分数"+score;
start.innerHTML = "重新开始";
score = 0;
}
};
rowDiv.appendChild(colDiv);
}
//第一行
if(main.children.length === 0){
main.appendChild(rowDiv);
}else{//之后的每一行
main.insertBefore(rowDiv,main.children[0]);
}
}
}
</script>
</body>
</html>