这篇文章主要介绍了js面向对象之如何实现拼图游戏,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
一、html代码
拼图小游戏
二、js代码
function PinTuGame(id){
var that = this;
this.oBtn = document.getElementById(id);
this.oTable = document.createElement('table');
this.oTbody = document.createElement('tbody');
this.aTd = null;
this.aTdMsg = []; //用于存储每个图片的信息
this.num = 0; //用于判断拼图是否完成
this.oTable.cellSpacing = '0';
this.createElem(); //初始化游戏界面
this.oBtn.onclick = function(){
for(var i = 0; i 100) {clearInterval(timer) };
},15);
that.beginGame();
}
}
PinTuGame.prototype = { //初始化游戏界面
createElem: function(){
for(var i =0; i<4; i++){
var oTr = document.createElement('tr');
for(var j =0; j<4; j++){
var oTd = document.createElement('td');
this.num ++;
var tdMsg = {
seq: this.num,
bgPosition: -100*j+'px '+ -100*i+'px'
};
this.aTdMsg.push(tdMsg);
oTr.appendChild(oTd);
}
this.oTbody.appendChild(oTr);
}
this.oTable.appendChild(this.oTbody);
document.body.appendChild(this.oTable);
this.aTd = this.oTbody.getElementsByTagName('td');
for(var i = 0; i3 || arr[i][1]>3)continue;
if( rows[arr[i][0]].cells[ arr[i][1] ].style.opacity == '0' ){
rows[arr[i][0]].cells[ arr[i][1] ].style.opacity = 1;
this.style.opacity=0;
//与隐藏的td交换json对象
var thisJson = this.json;
this.json = rows[arr[i][0]].cells[ arr[i][1]].json;
rows[arr[i][0]].cells[arr[i][1]].json = thisJson;
//与隐藏的td交换bakcground-position
this.style.backgroundPosition=this.json.bgPosition;
rows[arr[i][0]].cells[arr[i][1]].style.backgroundPosition=rows[arr[i][0]].cells[arr[i][1]].json.bgPosition;
}
}
that.checkWin();
};
}
}
},
checkWin: function(){ //检测游戏是否完成
var aJson = [];
for(var i = 0; iaJson[i+1])return;
}
for(var i = 0; i二、游戏图片素材












