jeudi 16 avril 2015

Randomize/shuffle cards in stack with jQuery

I am building a very simple memory game for a small project. The logic is as follows:



  1. click on the input field to choose with how many pairs would you like to play

  2. create divs with classes card1, card2 etc.

  3. clone divs and randomize their place in the array


Here is my script (fork in JSFiddle):



$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());

for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}

// randomize cards in stack
var cards = $(".cards");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
});


what I need now is to adjust the 3rd step, meaning to dynamically create the target vars, and the last line of the code



cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));


So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!





Aucun commentaire:

Enregistrer un commentaire