Home > Web Front-end > JS Tutorial > Make puzzle games with jQuery_jquery

Make puzzle games with jQuery_jquery

WBOY
Release: 2016-05-16 16:20:53
Original
1482 people have browsed it

Source code idea analysis:

【1】How to generate a picture grid, I think of two methods:

(1) Cut this large picture into 16 small pictures, and then use the src of the img tag

(2) There is only one large image, and then the background image of each element is cut and positioned using the background-position of CSS, which requires 16 arrays [0,0], [-150,0], [-300 ,0]..........(I adopt this)

【2】Picture background positioning array and layout positioning array

After choosing to use CSS to position and cut the image, you need to generate data.

The required css background positioning array is: [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]

The values ​​​​in [0,-150,-300,-450] are used among them (that is, I define the height and width of the image as multiples of 150), so I use this value to automatically generate it through for(){} Array

Copy code The code is as follows:

//this.nCol here is 4 --- because my puzzle is 4*4
// this.nArea is 150, which is the width and height of each picture (600px/4) - the large picture is 600*600
          var l = [],
                  p = [];
for(var n=0;n l.push(n*(this.nArea 1)); //Generate [0,151,302,453] grid layout positioning array, because my effect requires a border (green border in the picture), so it is different from the css background positioning array
                  p.push(-n*this.nArea);             }
for(var i=0;i       var t = parseInt(i/this.nCol),
                                k = i - this.nCol*t,
                     aP = [],
aL = [];
aP.push(p[k],p[t],i); //Here I added an additional i to the css background positioning array, which is used for judgment in step 3. It does not need to be used to set css attributes. I Set it as the attribute of the tag [bg-i]
aL.push(l[k],l[t]);
This.aBgp[i] = aP;
This.aLayout[i] = aL;
            }

[3] Determine whether it is completed

The second element (div) applies css background positioning this.aBgp[1] (value is [-150,0,1]), and the randomly assigned layout positioning is this.aLayout[3] (here 3 is randomly generated) (the value is [453,0]), then left:453px,top:0;

By moving this element, what changes is its letf and top values, not the order of its own structure. Get the left and top values ​​of this element (if it is moved to left:151px, top:0), and then use Judging from the value [151,0] of this.aLayout[1] (the 1 index is the [bg-i]=1 of the own label attribute and the index of this.aBgp[1]), equality means that the element has moved The rear position is correct.

Detailed code:

Copy code The code is as follows:

/*
Version:2.0
*/
Function GyPuzzleGame(option){
This.target = $(option.target);
This.data = option.data; //Image data
This.opt = option;
This.nLen = option.count; //How many puzzle pieces
This.aColLayout = option.aColLayout || [0,151,302,453];//Layout horizontal array
This.aRowLayout = option.aRowLayout || [0,151];//Layout vertical array
This.aColBgp = option.aColBgp || [0,-150,-300,-450];//Layout horizontal array
This.aRowBgp = option.aRowBgp || [0,-150];//Layout vertical array
This.nCol = this.aColLayout.length;
This.nRow = this.aRowLayout.length;
This.aLayout = []; //Layout array
This.aBgp = []; //css background positioning array
This.init();
}
GyPuzzleGame.prototype = {
        getRand:function(a,r){
            var arry = a.slice(0),
newArry = [];
for(var n=0;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 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 var t = parseInt(n/this.nCol),
l = n - this.nCol*t;
var html = $('
').
                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("");
                    }
                }
            });
        },
        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('
恭喜过关
');
        }
    });
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template