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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.