Random play function implementation

Im looking for some tips on how to start the random play function, so I have 6 atm images in the div box and I want a function that allows them to move around, how should I start? Should I put images in a separate div? any help or sample code appreciated, thanks

+4
source share
3 answers

The following is a jQuery solution. You can achieve the same results using vanilla JavaScript, but this will require a few extra lines of code.

<div id="deck"> <div><img src="" /></div> <div><img src="" /></div> . . . </div> 
 // Fisherโ€“Yates Shuffle (Knuth variant) // To shuffle an array a of n elements (indices 0..n-1): // for i from n - 1 downto 1 do // j <- random integer with 0 <= j <= i // exchange a[j] and a[i] // jQuery specific: // 1) remove elements from DOM and convert them into a native JavaScript array // 2) apply algorithm // 3) inject the array back to DOM var a = $("#deck > div").remove().toArray(); for (var i = a.length - 1; i >= 1; i--) { var j = Math.floor(Math.random() * (i + 1)); var bi = a[i]; var bj = a[j]; a[i] = bj; a[j] = bi; } $("#deck").append(a); 

Demo here

+3
source

I implemented something similar for a card game , so you can probably get some tips from this. Just do a resource lookup for "shuffle" in my .js files, and you should understand how I did it. From memory, I initially placed all my images in a div, and then moved them using the shuffle function. I think I later started dragging an array of URLs and then generated image elements later.

I used the jQuery plugin from Ca-Phun Ung 'Shuffle' (although I think I rewrote my own version to better understand its inner workings). You can also find useful information. See jQuery Shuffle

0
source

Ok, I got it!

 var divs = $('selector to get all divs'); // This could be $('img'); function shuffle(divs, iterations) { var size = divs.size(); for(var i = iterations; i > 0; i--) { // Pick two divs at random var div1 = divs[Math.floor(Math.random() * size)], div2 = divs[Math.floor(Math.random() * size)]; // Ensure they are different divs if(div1.is(div2)) { continue; } // Swap the two divs div1.clone().insertAfter(div2); div2.detach().insertAfter(div1); div1.detach(); } }; shuffle(divs, 1000); 

Although this is likely to be better if you put divs .hide () and then divs .show () so you don't see the beating. However, maybe this is what you want? You might want to linger there and use the jQuery animation function to make it a fantasy. This particular solution requires the img position in the DOM to determine the location. A more complicated solution would be to swap the css position during the loop.

 var savedLeft = div1.css("left"), savedTop = div1.css("top"); div1.css("left", div2.css("left")); div1.css("top", div2.css("top")); div2.css("left", savedLeft); div2.css("top", savedTop); 

Actually I have NOT EXCLUDED this yet, but it looks right here: P

0
source

Source: https://habr.com/ru/post/1400690/


All Articles