sliding.html!doctypehtmlhtmlheadmetahttp-equiv=content-typecontent=text/html;charset=utf-8/metaname=viewportcontent=width=device-width,initial-scale=1.0,user-scalable=yes/metaname=HandheldFriendlycontent=true/linkrel=stylesheethref=jquery.mobile-1.4.3.min.css/scriptsrc=jquery-2.1.1.min.js/scriptscriptsrc=jquery.mobile-1.4.3.min.js/scriptscripttype=text/javascript/scripttitle拼图游戏/titlestyle.picture{border:1pxsolidblack;}/style/headbodydivid=titleh2拼图游戏/h2/divdivid=sliderformlabel简单/labelinputtype=rangeid=scalevalue=4min=3max=5step=1label困难/labeldivdata-role=controlgroupadata-ajax=falsehref=menu.htmldata-role=button返回菜单/a/div/formbr/divdivid=mainclass=maincanvasid=puzzlewidth=480pxheight=480px/canvas/divscriptsrc=sliding.js/script/body/htmlSliding.jsvarcontext=document.getElementById('puzzle').getContext('2d');varimg=newImage();img.src='fizz2.jpg';img.addEventListener('load',drawTiles,false);varboardSize=document.getElementById('puzzle').width;vartileCount=document.getElementById('scale').value;vartileSize=boardSize/tileCount;varclickLoc=newObject;clickLoc.x=0;clickLoc.y=0;varemptyLoc=newObject;emptyLoc.x=0;emptyLoc.y=0;varsolved=false;varboardParts=newObject;setBoard();document.getElementById('scale').onchange=function(){tileCount=this.value;tileSize=boardSize/tileCount;setBoard();drawTiles();};document.getElementById('puzzle').onmousemove=function(e){clickLoc.x=Math.floor((e.pageX-this.offsetLeft)/tileSize);clickLoc.y=Math.floor((e.pageY-this.offsetTop)/tileSize);};document.getElementById('puzzle').onclick=function(){if(distance(clickLoc.x,clickLoc.y,emptyLoc.x,emptyLoc.y)==1){slideTile(emptyLoc,clickLoc);drawTiles();}if(solved){setTimeout(function(){alert(Yousolvedit!);},500);}};functionsetBoard(){boardParts=newArray(tileCount);for(vari=0;itileCount;++i){boardParts[i]=newArray(tileCount);for(varj=0;jtileCount;++j){boardParts[i][j]=newObject;boardParts[i][j].x=(tileCount-1)-i;boardParts[i][j].y=(tileCount-1)-j;}}emptyLoc.x=boardParts[tileCount-1][tileCount-1].x;emptyLoc.y=boardParts[tileCount-1][tileCount-1].y;solved=false;}functiondrawTiles(){context.clearRect(0,0,boardSize,boardSize);for(vari=0;itileCount;++i){for(varj=0;jtileCount;++j){varx=boardParts[i][j].x;vary=boardParts[i][j].y;if(i!=emptyLoc.x||j!=emptyLoc.y||solved==true){context.drawImage(img,x*tileSize,y*tileSize,tileSize,tileSize,i*tileSize,j*tileSize,tileSize,tileSize);}}}}functiondistance(x1,y1,x2,y2){returnMath.abs(x1-x2)+Math.abs(y1-y2);}functionslideTile(toLoc,fromLoc){if(!solved){boardParts[toLoc.x][toLoc.y].x=boardParts[fromLoc.x][fromLoc.y].x;boardParts[toLoc.x][toLoc.y].y=boardParts[fromLoc.x][fromLoc.y].y;boardParts[fromLoc.x][fromLoc.y].x=tileCount-1;boardParts[fromLoc.x][fromLoc.y].y=tileCount-1;toLoc.x=fromLoc.x;toLoc.y=fromLoc.y;checkSolved();}}functioncheckSolved(){varflag=true;for(vari=0;itileCount;++i){for(varj=0;jtileCount;++j){if(boardParts[i][j].x!=i||boardParts[i][j].y!=j){flag=false;}}}solved=flag;}