html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
div{border:1px solid #FFFFCC;margin: 0 auto;margin-top: 40px;}
span{float:left;width:30px;height:30px;margin:2px;border:1px solid #FFAA24;background:#fff}
span:hover{cursor:pointer}
.guan{background-color: #ddd;}
.kai{background-color: #006DBB;}
</style>
<body>
<p>开关灯游戏,点击某一个灯周围的灯会根据点击的反选,当所有的灯都开了就算获胜</p>
选择难度<select id="level" οnchange="start()">
<option value="8">3级</option>
<option value="9">4级</option>
<option value="10">5级</option>
<option value="11">6级</option>
<option value="12">7级</option>
<option value="13">8级</option>
<option value="14">9级</option>
<option value="15">10级</option>
<option value="16">11级</option>
<option value="17">12级</option>
<option value="18">13级</option>
</select>
<input type="button" οnclick="window.location.reload();" value="重玩">
<div id="cont">
</div>
</body>
</html>
<script src="js/j.js"></script>
<script src="index.js"></script>
js代码
var rclass = /[\t\r\n\f]/g;
function Od(id){
this.id = id;
}
Od.prototype.gd = function(idString){
return document.getElementById(String(idString));
}
Od.prototype.hasClass = function(selector){//来自jquery
var className = " " + selector + " ",
i = 0,
l = this.length;
for (; i < l; i++) {
if (this[i].nodeType === 1 &&
(" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) {
return true;
}
}
return false;
}
var od = new Od();
var start = function(){
var cont = od.gd('cont');
var sl = parseInt(od.gd('level').value);
var slen = sl*sl;
var str = '';
var sq = Math.sqrt(slen);
var dj = [0,sq-1,slen-sq,slen-1];
cont.style.height = String((sq-2)*36)+'px';
cont.style.width = String((sq-2)*36)+'px';
for(var i=0;i<slen;i++){
if(i>dj[0] && i<dj[1]){
str += '<span name="'+String(i)+'" class="guan" style="display:none">'+'</span>';
}else if(i>dj[2] && i<dj[3]){
str += '<span name="'+String(i)+'" class="guan" style="display:none">'+'</span>';
}else if(i%sq==0 || (i+1)%sq == 0){
str += '<span name="'+String(i)+'" class="guan" style="display:none">'+'</span>';
}else{
str += '<span name="'+String(i)+'" class="guan">'+'</span>';
}
}
cont.innerHTML = str;
var sl = document.getElementsByTagName('span');
for(var i=0;i<slen;i++){
sl[i].addEventListener('click',function(e){
var dn = parseInt(this.getAttribute('name'));
var pn = [dn,dn-1,dn+1,dn+sq,dn-sq];
for(var j=0;j<pn.length;j++){
if(sl[pn[j]].className == 'guan'){
sl[pn[j]].setAttribute('class','kai');
}else{
sl[pn[j]].setAttribute('class','guan');
}
}
})
}
}
start();
代码的github地址如下:
https://github.com/chenwg/js-fly