7.29关灯游戏,用script实现
<!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>关灯js版</title>
</head>
<body>
<script>
let rowCount = 10;
let colCount = 10;
let onColor = 'yellow';
let offColor = 'black';
let lightCount = 0;
let level = 1;
let lightWidth = 50;
let lightHeight = lightWidth;
let lightList = [];
//游戏初始化
function init(){
let wap = document.createElement('div');
wap.style.width = lightWidth * colCount + 'px';
wap.style.height = lightWidth * rowCount +'px';
wap.style.border = '1px solid gray';
wap.style.margin = 'auto';
wap.classList.add('clear');
let clearStyle = document.createElement('style');
clearStyle.innerText = '.clear:after {content :""; display: block; clear: both;}'
for(i = 0 ; i < 100 ; i++){
let light = document.createElement('div');
light.style.width = lightWidth + 'px';
light.style.height = lightHeight +'px';
light.style.border ='1px solid lightgray';
light.style.boxSizing = 'border-box';
light.style.backgroundColor = offColor;
light.style.float = 'left';
light.id = i;
light.onclick = myClick;
//push 从数组后面添加元素
lightList.push(light);
wap.appendChild(light);
}
document.body.appendChild(clearStyle);
document.body.appendChild(wap);
}
//游戏逻辑
function myClick(){
findLights(this);
}
function findLights(light){
turnLight(light);
//获取灯的下标
let index = parseInt(light.id);
let row = parseInt(index / colCount);
let upIndex = index - colCount;
if(upIndex >= 0){
turnLight(lightList[upIndex]);
}
let downIndex = index + colCount;
if(downIndex < lightList.length){
turnLight(lightList[downIndex]);
}
let leftIndex = index - 1;
let leftRow = parseInt(leftIndex / colCount);
if(leftIndex >= 0 && leftRow == row){
turnLight(lightList[leftIndex]);
}
let rightIndex = index + 1;
let rightRow = parseInt(rightIndex / colCount);
if(rightRow == row){
turnLight(lightList[rightIndex]);
}
//获胜判断
if(lightCount == 0){
alert('u win');
run();
}
}
function turnLight(light){
if(light.style.backgroundColor == onColor){
light.style.backgroundColor = offColor;
lightCount--;
}else{
light.style.backgroundColor = onColor;
lightCount++;
}
}
function next(level){
for(let i = 0 ; i < level; i++){
let randomIndex = parseInt(Math.random() * lightList.length);
findLights(lightList[randomIndex]);
}
}
function run(){
next(level++);
}
init();
run();
</script>
</body>
</html>