DIV CSS 佈局教程網

用jQuery打造拼圖小遊戲的完整思路與源碼
編輯:JQuery特效代碼     

本文詳細記錄了用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;               
            }

三、判斷是否完成

舉例來說,第二個元素(div)應用了 CSS 背景定位 this.aBgp[1](值為 [-150,0,1]),而隨機分配給它的布局定位假如是 this.aLayout[3](值為 [453,0]),那麼它的 left:453px、top:0。

當我們挪動這個元素時,改變的是它的 left、top 值,而非它在結構中的順序。因此只要讀取該元素當前的 left、top(例如挪到了 left:151px、top:0),再與 this.aLayout[1] 的值 [151,0] 進行比對——這裡的索引1正是標簽屬性 [bg-i]=1,也是 this.aBgp[1] 的索引——若相等,就說明這個元素的位置正確了。

完整代碼

代碼如下:
/*
    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);
            // console.log(layout);
            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>');
        }
    });

整個遊戲通過 CSS 背景定位切割單張大圖,隨機打亂布局位置後讓用戶點擊兩塊進行交換,每次移動後比對當前坐標與目標坐標,全部歸位即觸發過關回調。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved