jquery - Adding images to random divs each time -
i asked question made long , not specific enough here again.
i creating game fun found instructions how online. there 12 cards images facedown click on 2 cards , if images match stay faced , win 2 points untill find matches.
what need add each image random location, twice! need generate random locations each image , add images correct corresponding location in page. can think of game board 4 x 3 grid. each empty in "row" gets 1 image.the problem having 1 image being choosen @ random , not 6 choosen twice @ random
here jsfiddle: http://jsfiddle.net/26pda/1/
here images :
http://efreeman.userworld.com/jquery/images/cheese.gif http://efreeman.userworld.com/jquery/images/eggs.gif http://efreeman.userworld.com/jquery/images/kitchen_blender.gif http://efreeman.userworld.com/jquery/images/tea.gif http://efreeman.userworld.com/jquery/images/kitchen_collander.gif http://efreeman.userworld.com/jquery/images/kitchen_teapot.gif
here html:
<!doctype html> <html> <head> <title>jquery: manipulating , traversing elements project</title> <meta charset="utf-8"> <style> div.container, div.row, form { clear: both; } div.row > div { position: relative; float: left; width: 100px; height: 170px; padding: 30px; margin: 10px; border: 1px solid black; box-shadow: 3px 3px 5px grey; vertical-align: bottom; } div.row > div > img { display: inline-block; position: absolute; width: 100px; bottom: 30px; } .visible { visibility: visible; } .hidden { visibility: hidden; } .done { visibility: visible; } </style> <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> <script src="game.js"> </script> </head> <body> <div class="container"> <div class="row"> <div></div> <div></div> <div></div> <div></div> </div> <div class="row"> <div></div> <div></div> <div></div> <div></div> </div> <div class="row"> <div></div> <div></div> <div></div> <div></div> </div> </div> <form> <input type="button" value="play again"> </form> </body> </html>
this code use:
var images = ['...']; //your images above var imagesused = []; $('.container div:not(.row)').each(function() { var rand = math.floor(math.random() * images.length); $(this).append('<img src="' + images[rand] + '"/>'); if (imagesused.search(images[rand]) != -1) images.splice(rand, 1); else (imagesused.push(images[rand]); });
what we're doing here simple. make array store images used. iterate through each <div>
needs image.
then pick random image. done choosing random index of images
array. after that, make new <img>
element , set source randomly chosen image.
then check see if image used in imagesused
array. if is, remove image array of images can still used. if isn't, add image onto array.
the reason 2 images (and not 1 or 3+) because use once before it's been pushed onto imagesused
array, when use second time, remove images
array, it's no longer available use. if unconditionally removed images array each iteration, you'd use once.
Comments
Post a Comment