想用 jQuery 做一個能玩的拼圖小遊戲嗎?本文把設計思路和完整源碼一次公開,帶你從零理解這類小遊戲背後的原理。感興趣的朋友不妨跟著動手做一遍。
一、如何切出圖片網格
要把一張大圖變成拼圖塊,我想到兩種做法:
(1)把大圖切成 16 張小圖,各自用 img 標籤的 src 引入;
(2)只保留一張大圖,讓每個格子的背景圖透過 CSS 的 background-position 來定位切割,這樣只需準備 16 組坐標值,例如 [0,0]、[-150,0]、[-300,0]……(本文採用這種做法)。
二、背景定位數組與布局定位數組
既然選了 CSS 定位切圖,就得先生成數據。所需的 CSS 背景定位數組為:
[0,0],[-150,0],[-300,0],[-450,0],
[0,-150],[-150,-150],[-300,-150],[-450,-150],
[0,-300],[-150,-300],[-300,-300],[-450,-300],
[0,-450],[-150,-450],[-300,-450],[-450,-450]
可以發現,這些值都由 [0,-150,-300,-450] 組合而成(也就是我定義的圖片寬高 150 的倍數),因此用 for{} 迴圈自動生成即可:
代碼如下:
//this.nCol在這裡是4 --- 因為我的拼圖是4*4
// this.nArea是150,是每張圖片的寬,高(600px/4)--大圖是600*600
var l = [],
p = [];
for(var n=0;n<this.nCol;n++){
l.push(n*(this.nArea+1)); //生成[0,151,302,453] 網格的布局定位數組,因為我的效果需要邊框(圖中的綠色邊框),所以與css背景定位數組就不一樣了
p.push(-n*this.nArea); // 生成了[0,-150,-300,-450]就是上面說的,CSS背景定位值
}
for(var i=0;i<this.nLen;i++){ // this.nLen 是為 16
var t = parseInt(i/this.nCol),
k = i - this.nCol*t,
aP = [],
aL = [];
aP.push(p[k],p[t],i); //這裡我給css背景定位數組額外加了i,是為第3步判斷用的,不需要拿來設置css屬性的,我把它設置為標簽的屬性裡[bg-i]
aL.push(l[k],l[t]);
this.aBgp[i] = aP;
this.aLayout[i] = aL;
}
三、如何判斷是否完成
關鍵在於每個格子都記著自己「正確位置」的索引。移動拼圖時,改變的其實是元素的 left、top,而非結構順序。只要把移動後的坐標和該元素應有的布局坐標一比對,全部相符就代表通關。
完整源碼
代碼如下:
/*
version:2.0
*/
function GyPuzzleGame(option){
this.target = $(option.target);
this.data = option.data; //圖片數據
this.opt = option;
this.nLen = option.count; //多少張拼圖
this.aColLayout = option.aColLayout || [0,151,302,453];//布局橫向數組
this.aRowLayout = option.aRowLayout || [0,151];//布局豎向數組
this.aColBgp = option.aColBgp || [0,-150,-300,-450];//布局橫向數組
this.aRowBgp = option.aRowBgp || [0,-150];//布局豎向數組
this.nCol = this.aColLayout.length;
this.nRow = this.aRowLayout.length;
this.aLayout = []; //布局數組
this.aBgp = []; //css背景定位數組
this.init();
}
GyPuzzleGame.prototype = {
getRand:function(a,r){
var arry = a.slice(0),
newArry = [];
for(var n=0;n<r;n++){
var nR = parseInt(Math.random()*arry.length);
newArry.push(arry[nR]);
arry.splice(nR,1);
}
return newArry;
},
setPos:function(){
for(var i=0;i<this.nLen;i++){
var t = parseInt(i/this.nCol),
l = i - this.nCol*t,
aP = [],
aL = [];
aP.push(this.aColBgp[l],this.aRowBgp[t],i);
aL.push(this.aColLayout[l],this.aRowLayout[t]);
this.aBgp[i] = aP;
this.aLayout[i] = aL;
}
},
isPass:function(item){
var _that = this,
is = 0;
item.each(function(){
var l = parseInt($(this).css('left')),
t = parseInt($(this).css('top')),
i = parseInt($(this).attr('data-bgi'));
if(l==_that.aLayout[i][0]&&t==_that.aLayout[i][1]){
is ++;
}
});
return is;
},
createDom:function(){
var layout = this.getRand(this.aLayout,this.nLen);
for(var n=0;n<this.nLen;n++){
var t = parseInt(n/this.nCol),
l = n - this.nCol*t;
var html = $('<div data-bgi="'+this.aBgp[n][2]+'" class="puzzle_list"></div>').
css({'left':layout[n][0]+'px',
'top':layout[n][1]+'px',
'background-image':'url('+this.data+')',
'background-position':this.aBgp[n][0]+'px'+' '+this.aBgp[n][1]+'px'
});
this.target.append(html);
}
},
move:function(){
var $div = this.target.find('.puzzle_list'),
_that = this;
var hasElem = function(){
var t = false;
$div.each(function(){
if($(this).hasClass("on")){
t = true;
}
});
return t;
};
// click
$div.click(function(){
var $this = $(this);
if(hasElem()&&!$this.hasClass("on")){
var index = $('.on').index();
if($div.eq(index).is(':animated')||$this.is(':animated')){
return false;
}
var l = $div.eq(index).position().left,
t = $div.eq(index).position().top,
myl = $this.position().left,
myt = $this.position().top;
$(this).animate({'left':l,'top':t});
$div.eq(index).css({'z-index':'1'}).animate({'left':myl,'top':myt},function(){
$(this).removeClass("on");
$(this).find('span').remove();
$(this).css({'z-index':'0'});
if(_that.isPass($div) == _that.nLen){
if(typeof _that.opt.success == 'function'){
_that.opt.success({target:_that.target});
}
}
});
}
else {
if($this.hasClass("on")){
$this.removeClass("on");
$this.find('span').remove();
}
else {
$this.addClass("on").append("<span></span>");
}
}
});
},
init:function(){
// 設置CSS背景定位與元素布局數組
this.setPos();
// 創建元素
this.createDom();
// 挪動圖片
this.move();
}
}
//實例調用
new GyPuzzleGame({
'data':'images/03.jpg',
'target':'#pA',
'count':8,
'success':function(opt){
opt.target.append('<div class="puzzle_mask"></div><div class="puzzle_pass">恭喜過關</div>');
}
});