Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5

Thread: picture shuffle

  1. #1
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts

    picture shuffle

    yet another pic puzzle script :| i din't even think of it...came up upon it from http://www.codingforums.com/showthread.php?t=136924...i'm even using the same images and some of the same code (i'm sorry dj89)...well, heres one way of solving it

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title>Sliding Puzzle Game </title>
      <base href="http://dan.jex.googlepages.com/" />
    <script type="text/javascript">
    //Global Varriables
    var COL_SIZE = 4;
    var ROW_SIZE = 4;
    var puzzle = 15;
    var moves = 0;
    var tile = "0.jpg";
    complete = false;
    var pieces = new Array(puzzle);
    
    if ( !Array.prototype.filter ) {
    	Array.prototype.filter = function(cb) {
    		var ar = [];
    		for ( var i = 0, l = this.length; i < l; i++ ) {
    			if ( cb.call(this, this[i], i, this) ) {
    				ar.push(this[i]);
    			}
    		}
    		return ar;
    	}
    }
    function startpuzzle()
    {
        complete = false; //set complete to false useful is people play the puzzle more than once. this stoping the complete message at the end of the puzzle reapearing evertime the person moves a peice after completeing it more than once.
        moves = 0; //reset moves back to zero (again useful if someone has a second go after completeing the puzzle)
        pieces = Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0); //Array of 16 counting from 0. allocated space for each image in puzzle.
    }
    
    function getNeighbours(which) {
    	var tiles = [];
    	var col = which &#37; COL_SIZE;
    	var row = parseInt(which / ROW_SIZE);
    	var tiles = [];
    	if ( row > 0 ) {
    		// top
    		tiles.push( (COL_SIZE * (row-1)) + col );
    	}
    	if ( row < (ROW_SIZE-1) ) {
    		// bottom
    		tiles.push( (COL_SIZE * (row+1)) + col);
    	}
    	if ( col > 0 ) {
    		// left
    		tiles.push( (COL_SIZE * row) + (col - 1));
    	}
    	if ( col < (COL_SIZE-1) ) {
    		// right
    		tiles.push( (COL_SIZE * row) + (col + 1));
    	}
    	return tiles;
    }
    
    function tryMove(click) {
    	if ( pieces[click] == 0 ) {
    		// do nothing
    		return;
    	}
    	var tiles = getNeighbours(click);
    	var blank = tiles.filter(function(v) {
    		return 0 == pieces[v];
    	});
    	if ( blank.length > 0 ) {
    		// have a blank nearby
    		swop(click, blank[0]); // can only have one :)
    		check();
    	}
    }
    
    function shuffle() {
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	var blankPos = 15;
    	var count = Math.floor(1000 * Math.random());
    	while ( count-- > 0) {
    		var tiles = getNeighbours(blankPos);
    		var rnd   = parseInt( Math.random() * 1000, 10) % tiles.length;
    		var t = pieces[blankPos];
    		pieces[blankPos] = pieces[tiles[rnd]];
    		pieces[tiles[rnd]] = t;
    		//swop(blankPos, tiles[rnd]);
    		blankPos = tiles[rnd];
    	}
    	for ( var i = 0; i < pieces.length; i++ ) {
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function reset() {
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	for ( var i = 0; i < pieces.length; i++ ) {
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function swop(a, b) {
        /*
    	var temp = document.getElementById(a).src;
        document.getElementById(a).src = document.getElementById(b).src;
        document.getElementById(b).src = temp;
    	*/
    	var da = document.getElementById(a);
    	var db = document.getElementById(b);
    	var dap = da.parentNode;
    	var dbp = db.parentNode;
    	da = dap.removeChild(da);
    	db = dbp.removeChild(db);
    	var tid = da.id;
    	da.id = db.id;
    	db.id = tid;
    	dap.appendChild(db);
    	dbp.appendChild(da);
    
        var tttt = pieces[a]; pieces[a]=pieces[b]; pieces[b]=tttt;
    }
    
    function check () {
        var count = 0;
        /*if (!complete) {
            moves++;
            return;
        }*/
        for (var i=0; i < 15; i++) {
            if (pieces[i] == (i + 1)) count++;
        }
        if (count < 15) {  //alert(count + " number(s) are correct");
        }
        else {
            alert(" Hooray!! You are the Winner! \nThe final piece to the puzzle is your prize.");
            cflag = false;
            //document.images[15].src = romek;
        }
    } // fun check()
    </script>
     </head>
    
    <body onload="startpuzzle();">
    
    
    <table border=0 cellspacing=0 cellpadding=0><tr><td bgcolor="#0080ff">
    <button onClick="shuffle(); return false">Randomise</button><button onClick="reset(); return false">Reset</button></td></tr></table>
    <br>
    <br>
    <table border=3 cellspacing=0 cellpadding=5><tr><td bgcolor="#FFFFFF">
    <table cellspacing="0" cellpadding="0" border="0">
    <tr>
      <td><a href="#" onclick="tryMove( 0); return false;"><img id="0"  src="1.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 1); return false;"><img id="1"  src="2.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 2); return false;"><img id="2"  src="3.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 3); return false;"><img id="3"  src="4.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 4); return false;"><img id="4"  src="5.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 5); return false;"><img id="5"  src="6.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 6); return false;"><img id="6"  src="7.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 7); return false;"><img id="7"  src="8.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 8); return false;"><img id="8"  src="9.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 9); return false;"><img id="9"  src="10.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(10); return false;"><img id="10" src="11.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(11); return false;"><img id="11" src="12.jpg" border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove(12); return false;"><img id="12" src="13.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(13); return false;"><img id="13" src="14.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(14); return false;"><img id="14" src="15.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(15); return false;"><img id="15" src="0.jpg"  border="0"/></a></td>
    </tr>
    </table>
    </td></tr></table>
    </center>
    </td></tr></table>
     </body>
    </html>
    You never have to change anything you got up in the middle of the night to write. -- Saul Bellow

  • #2
    New Coder
    Join Date
    Mar 2008
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Another picture puzzle script
    Code:
    <!-- FOUR STEPS TO INSTALL PICTURE PUZZLE:
    
      1.  Copy the coding into the HEAD of your HTML document
      2.  Add the onLoad event handler into the BODY tag
      3.  Put the last coding into the BODY of your HTML document
      4.  Put this final code right before your </div></BODY> code  -->
    
    <!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->
    
    <HEAD>
    
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Original:  Davey Erwin (daverwin@hotmail.com) -->
    <!-- Web Site:  http://daverwin.homepage.com -->
    
    <!-- This script and many more are available free online at -->
    <!-- The JavaScript Source!! http://javascript.internet.com -->
    
    <!-- Begin
    // Uses Dan Steinman's Dynapi code
    // http://www.dansteinman.com/dynapi/
    
    function Puzzle(q,v,n,W,H,c,g) {
    this.mixem=null
    this.x=new Array()
    this.y=new Array()
    this.n=new Array()
    this.name=n
    this.f=false
    this.ma=false
    this.g=0
    this.w=W/3
    this.h=H/3
    s=css(n+"kDiv",q,v,W+20,H+60,c)
    s+=css(n+"mDiv",10,50,W,H,c)
    d='<DIV ID="'+n+'kDiv"><center><font color=blue size=5>'
    d+='<a href="javascript:'+n+'.scramble()">Scramble</a> or '
    d+='<a href="javascript:'+n+'.solve()">Solve</a></font></center>\n'
    d+='<DIV ID="'+n+'mDiv">\n'
    for(i=0;i<8;i++){
    m=n+i
    cn1=i
    cn2=0
    if(cn1>5)cn1-=6,cn2=2
    if(cn1>2)cn1-=3,cn2=1
    x=this.w*cn1
    y=this.h*cn2
    s+=css(m+"aDiv",x,y,this.w,this.h,c)
    s+=css(m+"bDiv",0-x,0-y,W,H)
    d+='<DIV ID="'+m+'aDiv" onclick="javascript:'+n+'.mov('+i+')">'
    d+='<DIV ID="'+m+'bDiv"><img src='+g+' height='+H+' width='+W+'>'
    d+='</div></div>\n'
    this.x[i]=cn1
    this.y[i]=cn2
    this.n[i]=m + "a"
    }
    d+='</div></div>\n'
    this.x[8]=2
    this.y[8]=2
    this.s=s
    this.d=d
    this.getCss  =PuzzleGetCss
    this.getDiv  =PuzzleGetDiv
    this.move    =PuzzleMove
    this.mov     =PuzzleMov  
    this.scramble=PuzzleSc  
    this.solve   =PuzzleSolve
    this.mixemup =PuzzleSC 
    this.stop    =PuzzleStop
    }
    function PuzzleMov(i){if(this.ma)return
    eval(this.name+'.move(i)')
    }
    function PuzzleStop(){
    eval('clearInterval('+this.mixem+')')
    this.ma=false
    }
    function PuzzleSc(){if(this.ma)return
    this.ma=true
    eval('setTimeout("'+this.name+'.stop()",15500)')
    eval('this.mixem=setInterval("'+this.name+'.mixemup()",300)')
    } 
    function PuzzleSC(){
    this.f=false
    while(!this.f){
    eval(this.name+'.move('+this.g+++')')
    if(this.g==8)this.g=-1}
    }
    function PuzzleSolve(){if(this.ma)return
    for(i=0;i<3;i++){for(j=0;j<3;j++){
    if(i*3+j<8)eval(this.n[i*3+j]+'.slideTo(this.w * j,this.h * i)')
    this.y[i*3+j]=i
    this.x[i*3+j]=j}}
    }     
    function PuzzleMove(n){
    x = this.x[n]
    y = this.y[n]
    w = this.x[8]
    z = this.y[8]
    if(((x==w)|(y==z))&(((x-1)==w)|((x+1)==w)|((y-1)==z)|((y+1)==z))){
    this.f=true
    eval(this.n[n]+'.slideTo(this.w*w,this.h*z)')
    this.x[n] = w
    this.y[n] = z
    this.x[8] = x
    this.y[8] = y}
    }
    function PuzzleGetCss(){return this.s}
    function PuzzleGetDiv(){return this.d}
    function init(){DynLayerInit()}
    // Dynamic Layer Object
    // sophisticated layer/element targeting and animation object which provides the core functionality needed in most DHTML applications
    // 19990604
    
    // Copyright (C) 1999 Dan Steinman
    // Distributed under the terms of the GNU Library General Public License
    // Available at http://www.dansteinman.com/dynapi/
    
    function DynLayer(id,nestref,frame) {
    if (!is.ns5 && !DynLayer.set && !frame) DynLayerInit()
    this.frame = frame || self
    if (is.ns) {
    if (is.ns4) {
    if (!frame) {
    if (!nestref) var nestref = DynLayer.nestRefArray[id]
    if (!DynLayerTest(id,nestref)) return
    this.css = (nestref)? eval("document."+nestref+".document."+id) : document.layers[id]
    }
    else this.css = (nestref)? eval("frame.document."+nestref+".document."+id) : frame.document.layers[id]
    this.elm = this.event = this.css
    this.doc = this.css.document
    }
    else if (is.ns5) {
    this.elm = document.getElementById(id)
    this.css = this.elm.style
    this.doc = document
    }
    this.x = this.css.left
    this.y = this.css.top
    this.w = this.css.clip.width
    this.h = this.css.clip.height
    }
    else if (is.ie) {
    this.elm = this.event = this.frame.document.all[id]
    this.css = this.frame.document.all[id].style
    this.doc = document
    this.x = this.elm.offsetLeft
    this.y = this.elm.offsetTop
    this.w = (is.ie4)? this.css.pixelWidth : this.elm.offsetWidth
    this.h = (is.ie4)? this.css.pixelHeight : this.elm.offsetHeight
    }
    this.id = id
    this.nestref = nestref
    this.obj = id + "DynLayer"
    eval(this.obj + "=this")
    }
    function DynLayerMoveTo(x,y) {
    if (x!=null) {
    this.x = x
    if (is.ns) this.css.left = this.x
    else this.css.pixelLeft = this.x
    }
    if (y!=null) {
    this.y = y
    if (is.ns) this.css.top = this.y
    else this.css.pixelTop = this.y
    }
    }
    function DynLayerMoveBy(x,y) {
    this.moveTo(this.x+x,this.y+y)
    }
    function DynLayerShow() {
    this.css.visibility = (is.ns4)? "show" : "visible"
    }
    function DynLayerHide() {
    this.css.visibility = (is.ns4)? "hide" : "hidden"
    }
    DynLayer.prototype.moveTo = DynLayerMoveTo
    DynLayer.prototype.moveBy = DynLayerMoveBy
    DynLayer.prototype.show = DynLayerShow
    DynLayer.prototype.hide = DynLayerHide
    DynLayerTest = new Function('return true')
    
    // DynLayerInit Function
    function DynLayerInit(nestref) {
    if (!DynLayer.set) DynLayer.set = true
    if (is.ns) {
    if (nestref) ref = eval('document.'+nestref+'.document')
    else {nestref = ''; ref = document;}
    for (var i=0; i<ref.layers.length; i++) {
    var divname = ref.layers[i].name
    DynLayer.nestRefArray[divname] = nestref
    var index = divname.indexOf("Div")
    if (index > 0) {
    eval(divname.substr(0,index)+' = new DynLayer("'+divname+'","'+nestref+'")')
    }
    if (ref.layers[i].document.layers.length > 0) {
    DynLayer.refArray[DynLayer.refArray.length] = (nestref=='')? ref.layers[i].name : nestref+'.document.'+ref.layers[i].name
    }
    }
    if (DynLayer.refArray.i < DynLayer.refArray.length) {
    DynLayerInit(DynLayer.refArray[DynLayer.refArray.i++])
    }
    }
    else if (is.ie) {
    for (var i=0; i<document.all.tags("DIV").length; i++) {
    var divname = document.all.tags("DIV")[i].id
    var index = divname.indexOf("Div")
    if (index > 0) {
    eval(divname.substr(0,index)+' = new DynLayer("'+divname+'")')
    }
    }
    }
    return true
    }
    DynLayer.nestRefArray = new Array()
    DynLayer.refArray = new Array()
    DynLayer.refArray.i = 0
    DynLayer.set = false
    
    // Slide Methods
    function DynLayerSlideTo(endx,endy,inc,speed,fn) {
    if (endx==null) endx = this.x
    if (endy==null) endy = this.y
    var distx = endx-this.x
    var disty = endy-this.y
    this.slideStart(endx,endy,distx,disty,inc,speed,fn)
    }
    function DynLayerSlideBy(distx,disty,inc,speed,fn) {
    var endx = this.x + distx
    var endy = this.y + disty
    this.slideStart(endx,endy,distx,disty,inc,speed,fn)
    }
    function DynLayerSlideStart(endx,endy,distx,disty,inc,speed,fn) {
    if (this.slideActive) return
    if (!inc) inc = 20
    if (!speed) speed = 20
    var num = Math.sqrt(Math.pow(distx,2) + Math.pow(disty,2))/inc
    if (num==0) return
    var dx = distx/num
    var dy = disty/num
    if (!fn) fn = null
    this.slideActive = true
    this.slide(dx,dy,endx,endy,num,1,speed,fn)
    }
    function DynLayerSlide(dx,dy,endx,endy,num,i,speed,fn) {
    if (!this.slideActive) return
    if (i++ < num) {
    this.moveBy(dx,dy)
    this.onSlide()
    if (this.slideActive) setTimeout(this.obj+".slide("+dx+","+dy+","+endx+","+endy+","+num+","+i+","+speed+",\""+fn+"\")",speed)
    else this.onSlideEnd()
    }
    else {
    this.slideActive = false
    this.moveTo(endx,endy)
    this.onSlide()
    this.onSlideEnd()
    eval(fn)
    }
    }
    function DynLayerSlideInit() {}
    DynLayer.prototype.slideInit = DynLayerSlideInit
    DynLayer.prototype.slideTo = DynLayerSlideTo
    DynLayer.prototype.slideBy = DynLayerSlideBy
    DynLayer.prototype.slideStart = DynLayerSlideStart
    DynLayer.prototype.slide = DynLayerSlide
    DynLayer.prototype.onSlide = new Function()
    DynLayer.prototype.onSlideEnd = new Function()
    
    // Clip Methods
    function DynLayerClipInit(clipTop,clipRight,clipBottom,clipLeft) {
    if (is.ie) {
    if (arguments.length==4) this.clipTo(clipTop,clipRight,clipBottom,clipLeft)
    else if (is.ie4) this.clipTo(0,this.css.pixelWidth,this.css.pixelHeight,0)
    }
    }
    function DynLayerClipTo(t,r,b,l) {
    if (t==null) t = this.clipValues('t')
    if (r==null) r = this.clipValues('r')
    if (b==null) b = this.clipValues('b')
    if (l==null) l = this.clipValues('l')
    if (is.ns) {
    this.css.clip.top = t
    this.css.clip.right = r
    this.css.clip.bottom = b
    this.css.clip.left = l
    }
    else if (is.ie) this.css.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)"
    }
    function DynLayerClipBy(t,r,b,l) {
    this.clipTo(this.clipValues('t')+t,this.clipValues('r')+r,this.clipValues('b')+b,this.clipValues('l')+l)
    }
    function DynLayerClipValues(which) {
    if (is.ie) var clipv = this.css.clip.split("rect(")[1].split(")")[0].split("px")
    if (which=="t") return (is.ns)? this.css.clip.top : Number(clipv[0])
    if (which=="r") return (is.ns)? this.css.clip.right : Number(clipv[1])
    if (which=="b") return (is.ns)? this.css.clip.bottom : Number(clipv[2])
    if (which=="l") return (is.ns)? this.css.clip.left : Number(clipv[3])
    }
    DynLayer.prototype.clipInit = DynLayerClipInit
    DynLayer.prototype.clipTo = DynLayerClipTo
    DynLayer.prototype.clipBy = DynLayerClipBy
    DynLayer.prototype.clipValues = DynLayerClipValues
    
    // Write Method
    function DynLayerWrite(html) {
    if (is.ns) {
    this.doc.open()
    this.doc.write(html)
    this.doc.close()
    }
    else if (is.ie) {
    this.event.innerHTML = html
    }
    }
    DynLayer.prototype.write = DynLayerWrite
    
    // BrowserCheck Object
    function BrowserCheck() {
    var b = navigator.appName
    if (b=="Netscape") this.b = "ns"
    else if (b=="Microsoft Internet Explorer") this.b = "ie"
    else this.b = b
    this.version = navigator.appVersion
    this.v = parseInt(this.version)
    this.ns = (this.b=="ns" && this.v>=4)
    this.ns4 = (this.b=="ns" && this.v==4)
    this.ns5 = (this.b=="ns" && this.v==5)
    this.ie = (this.b=="ie" && this.v>=4)
    this.ie4 = (this.version.indexOf('MSIE 4')>0)
    this.ie5 = (this.version.indexOf('MSIE 5')>0)
    this.min = (this.ns||this.ie)
    }
    is = new BrowserCheck()
    
    // CSS Function
    function css(id,left,top,width,height,color,vis,z,other) {
    if (id=="START") return '<STYLE TYPE="text/css">\n'
    else if (id=="END") return '</STYLE>'
    var str = (left!=null && top!=null)? '#'+id+' {position:absolute; left:'+left+'px; top:'+top+'px;' : '#'+id+' {position:relative;'
    if (arguments.length>=4 && width!=null) str += ' width:'+width+'px;'
    if (arguments.length>=5 && height!=null) {
    str += ' height:'+height+'px;'
    if (arguments.length<9 || other.indexOf('clip')==-1) str += ' clip:rect(0px '+width+'px '+height+'px 0px);'
    }
    if (arguments.length>=6 && color!=null) str += (is.ns)? ' layer-background-color:'+color+';' : ' background-color:'+color+';'
    if (arguments.length>=7 && vis!=null) str += ' visibility:'+vis+';'
    if (arguments.length>=8 && z!=null) str += ' z-index:'+z+';'
    if (arguments.length==9 && other!=null) str += ' '+other
    str += '}\n'
    return str
    }
    function writeCSS(str,showAlert) {
    str = css('START')+str+css('END')
    document.write(str)
    if (showAlert) alert(str)
    }
    //  End -->
    </script>
    </HEAD>
    
    <!-- STEP TWO: Insert the onLoad event handler into your BODY tag  -->
    
    <BODY OnLoad="init()">
    
    <!-- STEP THREE: Copy this code into the BODY of your HTML document  -->
    
    <script language="JavaScript" src="slider-puzzle.js"></script>
    
    <SCRIPT LANGUAGE="JavaScript">
    
    <!-- This script and many more are available free online at -->
    <!-- The JavaScript Source!! http://javascript.internet.com -->
    
    <!-- Begin
    puz = new Puzzle(100, 120, 'puz', 201, 201, '#ffcc00', 'puzzle1.gif');
    
    // Name = new Puzzle(Xpos, Ypos, 'Name', width, height, 'Color', 'GifPath');
    // Name must be the same in both places GifPath may be relative or absolute
    
    writeCSS( puz.getCss() );
    //  End -->
    </script>
    
    <!-- STEP FOUR: Put this final code right before your </div></BODY> code  -->
    
    <script>
    document.write( puz.getDiv() ); // change 'puz' to the name you gave your puzzle above
    </script>
    
    </BODY>
    
    <p><center>
    <font face="arial, helvetica" size="-2">Free JavaScripts provided<br>
    by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
    </center><p>
    
    <!-- Script Size:  11.50 KB -->
    Thanks and regards
    http://www.outsource-website-development.com/ http://www.outsource-website-design.com/
    Last edited by Basscyst; 04-09-2008 at 09:03 PM.

  • #3
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,533
    Thanks
    3
    Thanked 512 Times in 499 Posts
    similar to above but cross browser

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <script language="JavaScript" type="text/javascript">
    /*<![CDATA[*/
    // Basic Element Animator (13-March-2008) DRAFT
    // by Vic Phillips http://www.vicsjavascripts.org.uk
    
    // To progressively change the Left, Top, Width, Height or Opacity of an element over a specified period of time.
    
    // **** Application Notes
    
    // **** The HTML Code
    //
    // when moving an element the inline or class rule style position of the element should be assigned as
    // 'position:relative;' or 'position:absolute;'
    //
    // The element would normally be assigned a unique ID name.
    //
    
    // **** Executing the Effect(Script)
    //
    // The effect is executed by an event call to function 'zxcBAnimator('left','tst1',20,260,2000);'
    // where:
    // parameter 0 = the mode(see Note 1).                                                                     (string)
    // parameter 1 = the unique ID name or element object.                                                     (string or element object)
    // parameter 2 = the start position of the effect.                                                         (digits, for opacity minimum 0, maximum 100)
    // parameter 3 = the finish position of the effect.                                                        (digits, for opacity minimum 0, maximum 100)
    // parameter 4 = (optional) period of time between the start and finish of the effect in milliseconds.     (digits or defaults to 2000 milliSeconds)
    //
    //  Note 1:  The default units(excepting opacity) are 'px'.
    //  Note 2:  Examples modes: 'left', 'top', 'width', 'height', 'opacity.
    //           For hyphenated modes, the first character after the hyphen must be upper case, all others lower case.
    //  Note 3:  To 'toggle' the effect include '#' in parameter 0.
    //           The first call will set the toggle parameters.
    //           Subsequent calls with '#' in parameter 0 and the same start and finish parameters will 'toggle' the effect.
    //  Note 4:  The function may be re-executed with a different set of parameters (start/finish time or period)
    //           whenever required, say from an onclick/mouseover/out event.
    //           The period parameter will be retained unless re-specified.
    //
    // **** Advanced Applications
    //
    //  It may be required to access the current value of the effect.
    //  The element effect is accessible from the element property
    //  element effect = elementobject[mode.replace(/[-#]/g,'')+'oop'];
    //  where mode is parameter 0 of the initial call.
    //  An array storing the current, start and finish values of the element effect may be accessed
    //  from the element effect.data as fields 0, 1 and 2 respectively
    //
    
    // **** General
    //
    // All variable, function etc. names are prefixed with 'zxc' to minimise conflicts with other JavaScripts.
    // These characters may be changed to characters of choice using global find and replace.
    //
    // The Functional Code(about 2K) is best as an External JavaScript.
    //
    // Tested with IE7 and Mozilla FireFox on a PC.
    //
    
    
    
    // **** Functional Code - NO NEED to Change
    
    
    function zxcBAnimator(zxcmde,zxcobj,zxcsrt,zxcfin,zxctime){
     if (typeof(zxcobj)=='string'){ zxcobj=document.getElementById(zxcobj); }
     if (!zxcobj||(!zxcsrt&&!zxcfin)) return;
     var zxcoop=zxcobj[zxcmde.replace(/[-#]/g,'')+'oop'];
     if (zxcoop){
      clearTimeout(zxcoop.to);
      if (zxcoop.srtfin[0]==zxcsrt&&zxcoop.srtfin[1]==zxcfin&&zxcmde.match('#')) zxcoop.update([zxcoop.data[0],(zxcoop.srtfin[0]==zxcoop.data[2])?zxcfin:zxcsrt],zxctime);
      else zxcoop.update([zxcsrt,zxcfin],zxctime);
     }
     else zxcobj[zxcmde.replace(/[-#]/g,'')+'oop']=new zxcBAnimatorOOP(zxcmde,zxcobj,zxcsrt,zxcfin,zxctime);
    }
    
    function zxcBAnimatorOOP(zxcmde,zxcobj,zxcsrt,zxcfin,zxctime){
     this.srtfin=[zxcsrt,zxcfin];
     this.to=null;
     this.obj=zxcobj;
     this.mde=zxcmde.replace(/[-#]/g,'');
     this.update([zxcsrt,zxcfin],zxctime);
    }
    
    zxcBAnimatorOOP.prototype.update=function(zxcsrtfin,zxctime){
     this.time=zxctime||this.time||2000;
     if (zxcsrtfin[0]==zxcsrtfin[1]) return;
     this.data=[zxcsrtfin[0],zxcsrtfin[0],zxcsrtfin[1]];
     this.srttime=new Date().getTime();
     this.cng();
    }
    
    zxcBAnimatorOOP.prototype.cng=function(){
     var zxcms=new Date().getTime()-this.srttime;
     this.data[0]=(this.data[2]-this.data[1])/this.time*zxcms+this.data[1];
     if (this.mde!='left'&&this.mde!='top'&&this.data[0]<0) this.data[0]=0;
     if (this.mde!='opacity') this.obj.style[this.mde]=this.data[0]+'px';
     else  this.opacity(this.data[0]);
     if (zxcms<this.time) this.to=setTimeout(function(zxcoop){return function(){zxcoop.cng();}}(this), 10);
     else {
      this.data[0]=this.data[2];
      if (this.mde!='opacity') this.obj.style[this.mde]=this.data[0]+'px';
      else  this.opacity(this.data[0]);
     }
    }
    
    zxcBAnimatorOOP.prototype.opacity=function(zxcopc){
     if (zxcopc<0||zxcopc>100){ return; }
     this.obj.style.filter='alpha(opacity='+zxcopc+')';
     this.obj.style.opacity=this.obj.style.MozOpacity=this.obj.style.KhtmlOpacity=zxcopc/100-.001;
    }
    
    
    /*]]>*/
    </script>
    <script language="JavaScript" type="text/javascript">
    /*<![CDATA[*/
    // Picture Puzzle (09-April-2008) DRAFT
    // by Vic Phillips http://www.vicsjavascripts.org.uk
    
    function zxcInitPuzzle(zxcid,zxcrows,zxccols,zxccol,zxcmip,zxccip){
     var zxcp=document.getElementById(zxcid);
     zxcp.mip=document.getElementById(zxcmip);
     zxcp.cip=document.getElementById(zxccip);
     var zxcmimg=zxcp.getElementsByTagName('IMG')[0];
     var zxcw=Math.floor(zxcmimg.width/zxccols);
     var zxch=Math.floor(zxcmimg.height/zxcrows);
     zxcp.grid=[zxcrows,zxccols,zxcw,zxch]
     zxcp.ary=[];
     for (var zxc0=0;zxc0<zxcrows*zxccols;zxc0++){
      zxcp.ary[zxc0]=zxcES('DIV',{position:'absolute',overflow:'hidden',width:zxcw+'px',height:zxch+'px',backgroundColor:zxccol||'#000000'},zxcp);
      zxcp.ary[zxc0].pos=[zxcw*(zxc0%3),zxch*Math.floor(zxc0/zxccols)];
      zxcES(zxcmimg.cloneNode(false),{position:'absolute',left:-zxcw*(zxc0%3)+'px',top:-zxch*Math.floor(zxc0/zxccols)+'px'},zxcp.ary[zxc0]);
      zxcp.ary[zxc0].onclick=function(){ zxcSwap(this); }
     }
     zxcp.to=null;
     zxcp.removeChild(zxcmimg);
     zxcReset(zxcid);
     zxcp.mcnt=-1;
     zxcMveCnt(zxcp);
     zxcCheck(zxcp);
    }
    
    function zxcReset(zxcid){
     var zxcp=document.getElementById(zxcid);
     for (var zxc0=0;zxc0<zxcp.ary.length;zxc0++){
      zxcp.ary[zxc0].pos=[zxcp.grid[2]*(zxc0%zxcp.grid[1]),zxcp.grid[3]*Math.floor(zxc0/zxcp.grid[1])];
      zxcES(zxcp.ary[zxc0],{left:zxcp.ary[zxc0].pos[0]+'px',top:zxcp.ary[zxc0].pos[1]+'px'});
     }
     zxcp.blank=zxcp.ary[zxc0-1];
     zxcES(zxcp.ary[zxc0-1].firstChild,{visibility:'hidden'});
     zxcp.mcnt=-1;
     zxcMveCnt(zxcp);
     zxcCheck(zxcp);
    }
    
    function zxcShuffle(zxcid){
     var zxcp=document.getElementById(zxcid);
     var zxcdivs=zxcp.ary.randomise();
     for (var zxc0=0;zxc0<zxcdivs.length;zxc0++){
      zxcBAnimator('left',zxcdivs[zxc0],zxcdivs[zxc0].offsetLeft,zxcp.grid[2]*(zxc0%zxcp.grid[1]),500);
      zxcBAnimator('top',zxcdivs[zxc0],zxcdivs[zxc0].offsetTop,zxcp.grid[3]*Math.floor(zxc0/zxcp.grid[1]),500);
     }
     zxcES(zxcp.ary[zxc0-1].firstChild,{visibility:'hidden'});
     zxcp.mcnt=-1;
     zxcMveCnt(zxcp);
     setTimeout(function(){ zxcCheck(zxcp); },550);
    }
    
    function zxcSwap(zxcobj){
     var zxcp=zxcobj.parentNode;
     var zxcobjpos=[zxcobj.offsetLeft,zxcobj.offsetTop];
     var zxcblankpos=[zxcp.blank.offsetLeft,zxcp.blank.offsetTop];
     if ((Math.abs(zxcblankpos[0]-zxcobjpos[0])<=zxcp.grid[2]&&zxcblankpos[1]==zxcobjpos[1])||(Math.abs(zxcblankpos[1]-zxcobjpos[1])<=zxcp.grid[3]&&zxcblankpos[0]==zxcobjpos[0])){
      zxcBAnimator('left',zxcp.blank,zxcblankpos[0],zxcobjpos[0],1000);
      zxcBAnimator('top',zxcp.blank,zxcblankpos[1],zxcobjpos[1],1000);
      zxcBAnimator('left',zxcobj,zxcobjpos[0],zxcblankpos[0],1000);
      zxcBAnimator('top',zxcobj,zxcobjpos[1],zxcblankpos[1],1000);
      setTimeout(function(){ zxcCheck(zxcp,true); },1050);
     }
     zxcMveCnt(zxcp);
    }
    
    function zxcMveCnt(zxcp){
     zxcp.mcnt++;
     if (zxcp.mip) zxcp.mip[zxcp.mip.nodeName=='INPUT'?'value':'innerHTML']=zxcp.mcnt+' Moves';
    }
    
    function zxcCheck(zxcp,zxcck){
     var zxcnu=0;
     for (var zxc0=0;zxc0<zxcp.ary.length;zxc0++){
      if (zxcp.ary[zxc0].pos[0]==zxcp.ary[zxc0].offsetLeft&&zxcp.ary[zxc0].pos[1]==zxcp.ary[zxc0].offsetTop) zxcnu++;
     }
     if (zxcp.cip) zxcp.cip[zxcp.cip.nodeName=='INPUT'?'value':'innerHTML']=zxcnu+' Correct';
     if (zxcck&&zxcnu==zxcp.ary.length){
      alert('Well Done');
      zxcES(zxcp.ary[zxc0-1].firstChild,{visibility:'visible'});
     }
    }
    
    Array.prototype.randomise=function(){
     var zxccnt=0,zxcta=[];
     while (zxccnt<this.length){
      var zxctmp=Math.floor(Math.random()*this.length-1)+1;
      if (!zxcta[zxctmp]){zxcta[zxctmp]=this[zxccnt]; zxccnt++; }
     }
     return zxcta;
    }
    
    function zxcES(zxcele,zxcstyle,zxcp,zxctxt){
     if (typeof(zxcele)=='string') zxcele=document.createElement(zxcele);
     for (key in zxcstyle) zxcele.style[key]=zxcstyle[key];
     if (zxcp) zxcp.appendChild(zxcele);
     if (zxctxt) zxcele.appendChild(document.createTextNode(zxctxt));
     return zxcele;
    }
    
    
    
    
    /*]]>*/
    </script></head>
    
    <body onload="zxcInitPuzzle('tst',4,3,'#FFCC66','Moves','Correct');">
    <input type="button" name="" value="Shuffle" onclick="zxcShuffle('tst');"/>
    <input type="button" name="" value="Reset" onclick="zxcReset('tst');"/>
    <div id="tst" style="position:relative;width:351px;height:263px;" >
    <img src="http://www.vicsjavascripts.org.uk/StdImages/WinterPalace.jpg" width="351" height="263" />
    </div>
    <div id="Correct" size="10" ></div>
    <input id="Moves" size="10" />
    
    </body>
    
    </html>
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #4
    New to the CF scene
    Join Date
    May 2008
    Location
    london bridge is falling down
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by shyam View Post
    yet another pic puzzle script :| i din't even think of it...came up upon it from http://www.codingforums.com/showthread.php?t=136924...i'm even using the same images and some of the same code (i'm sorry dj89)...well, heres one way of solving it

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title>Sliding Puzzle Game </title>
      <base href="http://dan.jex.googlepages.com/" />
    <script type="text/javascript">
    //Global Varriables
    var COL_SIZE = 4;
    var ROW_SIZE = 4;
    var puzzle = 15;
    var moves = 0;
    var tile = "0.jpg";
    complete = false;
    var pieces = new Array(puzzle);
    
    if ( !Array.prototype.filter ) {
    	Array.prototype.filter = function(cb) {
    		var ar = [];
    		for ( var i = 0, l = this.length; i < l; i++ ) {
    			if ( cb.call(this, this[i], i, this) ) {
    				ar.push(this[i]);
    			}
    		}
    		return ar;
    	}
    }
    function startpuzzle()
    {
        complete = false; //set complete to false useful is people play the puzzle more than once. this stoping the complete message at the end of the puzzle reapearing evertime the person moves a peice after completeing it more than once.
        moves = 0; //reset moves back to zero (again useful if someone has a second go after completeing the puzzle)
        pieces = Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0); //Array of 16 counting from 0. allocated space for each image in puzzle.
    }
    
    function getNeighbours(which) {
    	var tiles = [];
    	var col = which % COL_SIZE;
    	var row = parseInt(which / ROW_SIZE);
    	var tiles = [];
    	if ( row > 0 ) {
    		// top
    		tiles.push( (COL_SIZE * (row-1)) + col );
    	}
    	if ( row < (ROW_SIZE-1) ) {
    		// bottom
    		tiles.push( (COL_SIZE * (row+1)) + col);
    	}
    	if ( col > 0 ) {
    		// left
    		tiles.push( (COL_SIZE * row) + (col - 1));
    	}
    	if ( col < (COL_SIZE-1) ) {
    		// right
    		tiles.push( (COL_SIZE * row) + (col + 1));
    	}
    	return tiles;
    }
    
    function tryMove(click) {
    	if ( pieces[click] == 0 ) {
    		// do nothing
    		return;
    	}
    	var tiles = getNeighbours(click);
    	var blank = tiles.filter(function(v) {
    		return 0 == pieces[v];
    	});
    	if ( blank.length > 0 ) {
    		// have a blank nearby
    		swop(click, blank[0]); // can only have one :)
    		check();
    	}
    }
    
    function shuffle() {
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	var blankPos = 15;
    	var count = Math.floor(1000 * Math.random());
    	while ( count-- > 0) {
    		var tiles = getNeighbours(blankPos);
    		var rnd   = parseInt( Math.random() * 1000, 10) % tiles.length;
    		var t = pieces[blankPos];
    		pieces[blankPos] = pieces[tiles[rnd]];
    		pieces[tiles[rnd]] = t;
    		//swop(blankPos, tiles[rnd]);
    		blankPos = tiles[rnd];
    	}
    	for ( var i = 0; i < pieces.length; i++ ) {
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function reset() {
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	for ( var i = 0; i < pieces.length; i++ ) {
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function swop(a, b) {
        /*
    	var temp = document.getElementById(a).src;
        document.getElementById(a).src = document.getElementById(b).src;
        document.getElementById(b).src = temp;
    	*/
    	var da = document.getElementById(a);
    	var db = document.getElementById(b);
    	var dap = da.parentNode;
    	var dbp = db.parentNode;
    	da = dap.removeChild(da);
    	db = dbp.removeChild(db);
    	var tid = da.id;
    	da.id = db.id;
    	db.id = tid;
    	dap.appendChild(db);
    	dbp.appendChild(da);
    
        var tttt = pieces[a]; pieces[a]=pieces[b]; pieces[b]=tttt;
    }
    
    function check () {
        var count = 0;
        /*if (!complete) {
            moves++;
            return;
        }*/
        for (var i=0; i < 15; i++) {
            if (pieces[i] == (i + 1)) count++;
        }
        if (count < 15) {  //alert(count + " number(s) are correct");
        }
        else {
            alert(" Hooray!! You are the Winner! \nThe final piece to the puzzle is your prize.");
            cflag = false;
            //document.images[15].src = romek;
        }
    } // fun check()
    </script>
     </head>
    
    <body onload="startpuzzle();">
    
    
    <table border=0 cellspacing=0 cellpadding=0><tr><td bgcolor="#0080ff">
    <button onClick="shuffle(); return false">Randomise</button><button onClick="reset(); return false">Reset</button></td></tr></table>
    <br>
    <br>
    <table border=3 cellspacing=0 cellpadding=5><tr><td bgcolor="#FFFFFF">
    <table cellspacing="0" cellpadding="0" border="0">
    <tr>
      <td><a href="#" onclick="tryMove( 0); return false;"><img id="0"  src="1.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 1); return false;"><img id="1"  src="2.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 2); return false;"><img id="2"  src="3.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 3); return false;"><img id="3"  src="4.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 4); return false;"><img id="4"  src="5.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 5); return false;"><img id="5"  src="6.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 6); return false;"><img id="6"  src="7.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 7); return false;"><img id="7"  src="8.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 8); return false;"><img id="8"  src="9.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 9); return false;"><img id="9"  src="10.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(10); return false;"><img id="10" src="11.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(11); return false;"><img id="11" src="12.jpg" border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove(12); return false;"><img id="12" src="13.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(13); return false;"><img id="13" src="14.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(14); return false;"><img id="14" src="15.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(15); return false;"><img id="15" src="0.jpg"  border="0"/></a></td>
    </tr>
    </table>
    </td></tr></table>
    </center>
    </td></tr></table>
     </body>
    </html>
    hi folk's i really need your help for this pieces of code of javascript for sliding puzzle could u please tell me what every peices of code does about this code

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title>Sliding Puzzle Game </title>
      <base href="http://dan.jex.googlepages.com/" />
    <script type="text/javascript">
    //Global Varriables
    var COL_SIZE = 4; ----------tell me what this for????-----------
    var ROW_SIZE = 4;----------tell me what this for????-----------
    var puzzle = 15;----------tell me what this for????-----------
    var moves = 0;----------tell me what this for????-----------
    var tile = "0.jpg";----------tell me what this for????-----------
    complete = false;----------tell me what this for????-----------
    var pieces = new Array(puzzle);----------tell me what this for????-----------
    
    if ( !Array.prototype.filter ) {----------tell me what this for????-----------
    	Array.prototype.filter = function(cb) {-------tell me what this for????-------
    		var ar = [];----------tell me what this for????-----------
    		for ( var i = 0, l = this.length; i < l; i++ ) {----------tell me what this for?
    			if ( cb.call(this, this[i], i, this) ) {
    				ar.push(this[i]);
    			}
    		}
    		return ar;----------tell me what this for????-----------
    	}
    }
    function startpuzzle()--------tell me what this for????-----------
    {
        complete = false; //set complete to false useful is people play the puzzle more than once. this stoping the complete message at the end of the puzzle reapearing evertime the person moves a peice after completeing it more than once.
        moves = 0; //reset moves back to zero (again useful if someone has a second go after completeing the puzzle)
        pieces = Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0); //Array of 16 counting from 0. allocated space for each image in puzzle.
    }
    
    function getNeighbours(which) { ----------tell me what this for????-----------
    	var tiles = [];  ----------tell me what this for????-----------
    	var col = which % COL_SIZE;----------tell me what this for????-----------
    	var row = parseInt(which / ROW_SIZE);---tell me what this for????--------
    	var tiles = [];----------tell me what this for????-----------
    	if ( row > 0 ) {------tell me what this for????-----------
    		// top
    		tiles.push( (COL_SIZE * (row-1)) + col );
    	}
    	if ( row < (ROW_SIZE-1) ) {
    		// bottom
    		tiles.push( (COL_SIZE * (row+1)) + col);
    	}
    	if ( col > 0 ) {
    		// left
    		tiles.push( (COL_SIZE * row) + (col - 1));
    	}
    	if ( col < (COL_SIZE-1) ) {
    		// right
    		tiles.push( (COL_SIZE * row) + (col + 1));
    	}
    	return tiles;
    }
    
    function tryMove(click) {
    	if ( pieces[click] == 0 ) { ----------tell me what this for????-----------
    		// do nothing
    		return;
    	}
    	var tiles = getNeighbours(click); ----------tell me what this for????-----------
    	var blank = tiles.filter(function(v) {
    		return 0 == pieces[v];
    	});
    	if ( blank.length > 0 ) {
    		// have a blank nearby
    		swop(click, blank[0]); // can only have one :)
    		check();
    	}
    }
    
    function shuffle() {----------tell me what this for????-----------
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	var blankPos = 15; ----------tell me what this for????-----------
    	var count = Math.floor(1000 * Math.random())------tell me what this for????-----
    	while ( count-- > 0) { ----------tell me what this for????-----------
    		var tiles = getNeighbours(blankPos); ----------tell me what this for????-
    		var rnd   = parseInt( Math.random() * 1000, 10) % tiles.length; ----tell me what this for???
    
     pieces[blankPos];----------tell me what this for????-----------
    		pieces[blankPos] = pieces[tiles[rnd]];
    		pieces[tiles[rnd]] = t;
    		//swop(blankPos, tiles[rnd]);
    		blankPos = tiles[rnd];
    	}
    	for ( var i = 0; i < pieces.length; i++ ) {----------tell me what this for?
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function reset() {----------tell me what this for????-----------
    	pieces = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
    	for ( var i = 0; i < pieces.length; i++ ) {
    		document.getElementById(i).src = pieces[i] + '.jpg';
    	}
    }
    function swop(a, b) {----------tell me what this for????-----------
        /*
    	var temp = document.getElementById(a).src; ----------tell me what this for all
        document.getElementById(a).src = document.getElementById(b).src;
        document.getElementById(b).src = temp;
    	*/
    	var da = document.getElementById(a); ----------tell me what this for????-
    	var db = document.getElementById(b);----------tell me what this for???
    	var dap = da.parentNode; ----------tell me what this for????-----------
    	var dbp = db.parentNode;----------tell me what this for????-----------
    	da = dap.removeChild(da);----------tell me what this for????-----------
    	db = dbp.removeChild(db);----------tell me what this for????-----------
    	var tid = da.id;----------tell me what this for????-----------
    	da.id = db.id;----------tell me what this for????-----------
    	db.id = tid;----------tell me what this for????-----------
    	dap.appendChild(db);----------tell me what this for????-----------
    	dbp.appendChild(da);----------tell me what this for????-----------
    
        var tttt = pieces[a]; pieces[a]=pieces[b]; pieces[b]=tttt;
    }
    
    function check () {----------tell me what this for????-----------
        var count = 0;
        /*if (!complete) {
            moves++;
            return;
        }*/
        for (var i=0; i < 15; i++) {
            if (pieces[i] == (i + 1)) count++;
        }
        if (count < 15) {  //alert(count + " number(s) are correct");
        }
        else {
            alert(" Hooray!! You are the Winner! \nThe final piece to the puzzle is your prize.");
            cflag = false;
            //document.images[15].src = romek;
        }
    } // fun check()
    </script>
     </head>
    
    <body onload="startpuzzle();">
    
    
    <table border=0 cellspacing=0 cellpadding=0><tr><td bgcolor="#0080ff">
    <button onClick="shuffle(); return false">Randomise</button><button onClick="reset(); return false">Reset</button></td></tr></table>
    <br>
    <br>
    <table border=3 cellspacing=0 cellpadding=5><tr><td bgcolor="#FFFFFF">
    <table cellspacing="0" cellpadding="0" border="0">
    <tr>
      <td><a href="#" onclick="tryMove( 0); return false;"><img id="0"  src="1.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 1); return false;"><img id="1"  src="2.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 2); return false;"><img id="2"  src="3.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 3); return false;"><img id="3"  src="4.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 4); return false;"><img id="4"  src="5.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 5); return false;"><img id="5"  src="6.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 6); return false;"><img id="6"  src="7.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 7); return false;"><img id="7"  src="8.jpg"  border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove( 8); return false;"><img id="8"  src="9.jpg"  border="0"/></a></td>
      <td><a href="#" onclick="tryMove( 9); return false;"><img id="9"  src="10.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(10); return false;"><img id="10" src="11.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(11); return false;"><img id="11" src="12.jpg" border="0"/></a></td>
    </tr><tr>
      <td><a href="#" onclick="tryMove(12); return false;"><img id="12" src="13.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(13); return false;"><img id="13" src="14.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(14); return false;"><img id="14" src="15.jpg" border="0"/></a></td>
      <td><a href="#" onclick="tryMove(15); return false;"><img id="15" src="0.jpg"  border="0"/></a></td>
    </tr>
    </table>
    </td></tr></table>
    </center>
    </td></tr></table>
     </body>
    </html>
    Last edited by Trinithis; 05-02-2008 at 10:37 PM.

  • #5
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    shibu: Your code doesn't work in either my FF or IE

    vwphillips: FYI, when I increased the grid size, some of the subimages repeated, and when I decreased it, more than one 'hole' appeared. If I'm not mistaken, your shuffle doesn't guarantee that the puzzle can be solved. But that's just a guess.

    ace007: Sorry, but you need to learn javascript before you can understand the code.

    Here's something I batched up for kicks. You might have to refresh the page once because the image has to be cached or something, and I don't feel like fixing that with a preloader.

    pictureShuffler.html
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
    <html>
    <head>
    <title>Picture Shuffler</title>
    </head>
    <body><div>
    
    <div id="pane"></div>
    
    <script type="text/javascript" src="pictureShuffler.js"></script>
    </div></body>
    </html>
    pictureShuffler.js
    Code:
    var shufflePuzzle = (function() { // returns shuffle
    
      //-----------------------------------------------------------------------------------//
      // The variables are avaliable to change
    
      var pane = document.getElementById("pane");
      var imgSrc = "http://img.photobucket.com/albums/v251/Trinithis/grouchotrust.jpg";
      var rows = 3;
      var cols = 7;
      var onsolve = function() {
        alert("You win!");
        shuffle();
      };
    
      //-----------------------------------------------------------------------------------//
      // Don't change from here down
    
      var img = document.createElement("img");
      img.src = imgSrc;
      img.style.position = "relative";
      var width = Math.floor(img.width / cols);
      var height = Math.floor(img.height / rows);
    
      //-----------------------------------------------------------------------------------//
      // Constructors
    
      var Pos = function(row, col) {
        this.row = row;
        this.col = col;
      }
      Pos.prototype.equals = function(rhs) {
        return this.row === rhs.row && this.col === rhs.col;
      };
    
      //-----------------------------------------------------------------------------------//
      // Functions
    
      var adjToHole = function(p) {
        var adjs = getAdjacents(p);
        for(var i = adjs.length - 1; i >= 0; --i)
          if(adjs[i].pos.equals(hole.pos))
            return true;
        return false;
      };
    
      var getAdjacents = function(p) {
        var adjs = [];
        for(var i = p.adjPositions.length - 1, adj, adjPos; i >= 0; --i) {
          adjPos = p.adjPositions[i];
          adj = pieces[adjPos.row] && pieces[adjPos.row][adjPos.col];
          if(adj)
            adjs.push(adj);
        }
        return adjs;
      };
    
      var getRow = function(el) {
        return Math.floor(parseInt(el.style.left) / width);
      };
    
      var getCol = function(el) {
        return Math.floor(parseInt(el.style.top) / height);
      };
    
      var isSolved = function() {
        for(var i = 0, p; i < cols; ++i)
          for(var j = 0; j < rows; ++j) {
            p = pieces[i][j];
            if(!p.pos.equals(p.origPos))
              return false;
          }
        return true;
      };
    
      var movePiece = function(e) {
        e = e || window.event;
        var idiv = (e.target || e.srcElement).parentNode;
        var p = pieces[getRow(idiv)][getCol(idiv)];
        if(!adjToHole(p))
          return;
        swap(p, hole);
        if(isSolved())
          onsolve();
      };
    
      var shuffle = function() {
        // this shuffle guarantees that the puzzle can be solved
        for(var i = Math.pow(rows * cols, 2); i > 0; --i) {
          var adjs = getAdjacents(hole);
          var adj = adjs[Math.floor(Math.random() * adjs.length)];
          swap(adj, hole);
        }
      };
    
      var swap = function(p1, p2) {
        var s1 = p1.idiv.firstChild.style;
        var s2 = p2.idiv.firstChild.style;
        var temp = arguments.callee.temp;
        temp.left = s1.left;
        temp.top = s1.top;
        temp.origPos = p1.origPos;
        temp.vis = p1.idiv.style.visibility;
        s1.left =   s2.left;
        s2.left = temp.left;
        s1.top =   s2.top;
        s2.top = temp.top;
        p1.origPos =   p2.origPos;
        p2.origPos = temp.origPos;
        p1.idiv.style.visibility = p2.idiv.style.visibility;
        p2.idiv.style.visibility = temp.vis;
        if(hole === p1)
          hole = p2;
        else if(hole === p2)
          hole = p1;
      };
      swap.temp = {};
    
      //-----------------------------------------------------------------------------------//
      // Data
    
      var pieces = (function() {  // to prevent closure over the DOM elements
        var idiv = document.createElement("div");
        idiv.style.overflow = "hidden";
        idiv.style.display = "block";
        idiv.style.width = width + "px";
        idiv.style.height = height + "px";
        idiv.style.border = "solid black 1px";
        idiv.style.position = "absolute";
        idiv.appendChild(img);
        var pieces = [];
        for(var i = 0, p; i < cols; ++i) {
          pieces[i] = [];
          for(var j = 0; j < rows; ++j) {
            p = pieces[i][j] = {};
            p.origPos = new Pos(i, j);
            p.pos = new Pos(i, j);
            p.adjPositions = [new Pos(i-1, j), new Pos(i+1, j), new Pos(i, j+1), new Pos(i, j-1)];
            p.idiv = idiv.cloneNode(true);
            p.idiv.style.left = i * width + "px";
            p.idiv.style.top = j * height + "px";
            p.idiv.firstChild.style.left = -i * width + "px";
            p.idiv.firstChild.style.top = -j * height + "px";
            pane.appendChild(p.idiv);
          }
        }
        return pieces;
      })();
      
      var hole = pieces[pieces.length-1];
      hole = hole[hole.length-1];
      hole.idiv.style.visibility = "hidden";
    
      //-----------------------------------------------------------------------------------//
      // Initialization
    
      for(var i = 0; i < cols; ++i)
        for(var j = 0; j < rows; ++j)
          pieces[i][j].idiv.onclick = movePiece;
    
      img = pane = null;
      return shuffle;
    })();
    Last edited by Trinithis; 05-03-2008 at 09:39 AM.
    Trinithis


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •