0

I'm making a javascript memory game and it's actually working, but I want the images to load in a random order. It's just that I have no idea how to.

This is what it currently looks like:

var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg",
    "img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg"];

var hardImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg",
    "img/frog.jpg", "img/fly.jpg", "img/bat.jpg", "img/bug.jpg",
    "img/cat.jpg", "img/dog.jpg", "img/frog.jpg", "img/fly.jpg"]

var imagesToShow;

var imagesContainer = document.getElementById("images-container");

var questionMark = "img/memory-bg.jpg";


if (selectedDifficulty == "easy") {
    imagesToShow = easyImages;
}

else if (selectedDifficulty == "hard") {
    imagesToShow = hardImages;
}

imagesContainer.innerHTML = "";

if (imagesToShow !== "") {
    for (var i = 0; i < imagesToShow.length; i++) {
        var img = document.createElement("img");

        img.addEventListener("click", flipImage);

        img.src = questionMark;

        img.dataset.img = imagesToShow[i];

        imagesContainer.appendChild(img);
    }
}

2 Answers2

0

Maybe something like:

var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg",
"img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg"];

var number_of_numbers=10
while(easyImages.length < number_of_numbers){
  var randomnumber=Math.ceil(Math.random()*100)
  var found=false;
  for(var i=0;i<easyImages.length;i++){
    if(easyImages[i]==randomnumber){found=true;break}
  }
  if(!found)easyImages[easyImages.length]=randomnumber;
}
Petro
  • 3,484
  • 3
  • 32
  • 59
0

You could create another array with the images you want to display, and then use a random number generator to display the randomly generated index of that array, make sure to set the random range to the lenght of the array or else it will return numbers outisde your index. Then remove the image element at that position in the array, leaving you with only the pictures which have not been displayed.

jettmann
  • 36
  • 4