0

i am making a memory card game which has a structure like this,and i need to place this 6 pairs of images inside the divs randomly ,and make sure there are 2 of each and not more

heres my code i have 12 of this divs:

<div class="card">
    <div class="frontCard">
        <img id="image0" src="images/frontCard.jpg" alt="">
    </div>
    <div class="backCard">
        <img src="images/CardBack.png" alt="">
    </div>
</div>

<div class="card">
    <div class="frontCard">
        <img id="image1" src="images/frontCard.jpg" alt="">
    </div>
    <div class="backCard">
        <img src="images/CardBack.png" alt="">
    </div>
</div>

and js

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'images/frontCard.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'images/frontCard2.jpg';

imgArray[2] = new Image();
imgArray[2].src = 'images/frontCard3.jpg';

imgArray[3] = new Image();
imgArray[3].src = 'images/frontCard4.jpg';

imgArray[4] = new Image();
imgArray[4].src = 'images/frontCard5.jpg';

imgArray[5] = new Image();
imgArray[5].src = 'images/frontCard6.png';
max = 12;
for (i = 0; i < max; i++) {

     document.getElementById("image0").src = imgArray[Math.floor((Math.random() * 5))].src;
     //???
}

i have no idea how to do this in a short way without repeating myself

Butiri Dan
  • 1,759
  • 5
  • 12
  • 18
  • This might point you in the right direction: https://stackoverflow.com/questions/38499530/how-can-i-generate-a-random-sequence-of-numbers-in-javascript-with-conditions – Reverend Pete Jul 31 '19 at 20:03

2 Answers2

3

You're almost there. Instead of using document.getElementById("image0"), you should use document.getElementById("image" + i) -- this way you're not just replacing the same image over and over, but instead replacing image number i.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
0

Picking up randomly from the image array, will result in the same image being picked twice. Instead, you can shuffle the array and then just display them using a for loop.

Razvan
  • 3,017
  • 1
  • 26
  • 35