I am trying to make memory game and have been struggled to make images that are in div, to randomly shuffle. I would like to hear some advices and that would be really helpful for me to finish my first project. I do not know about Jquery so it would be nice to have answers using just vanilla Javascript. Thank you.
I have tried:
<div >
<div id="container-1">
<img src="/image/elephant.jpg" />
</div>
<div id="container-2">
<img src="/image/koalas.jpg" />
</div>
<div id="container-3">
<img src="/image/lion.jpg" />
</div>
</div>
<div >
<div id="container-4">
<img src="/image/elephant.jpg" />
</div>
<div id="container-5">
<img src="/image/koalas.jpg" />
</div>
<div id="container-6">
<img src="/image/lion.jpg" />
</div>
"use strict";
const container = document.querySelectorAll(".img-container");
const image = document.querySelectorAll(".hidden");
let imgArr = ["/image/elephant.jpg", "/image/koalas.jpg", "/image/lion.jpg"];
// Flip cards
for (let i = 0; i < container.length; i )
container[i].addEventListener("click", function () {
image[i].classList.remove("hidden");
});
// Shuffle cards
const shuffle = function (imgArr) {
for (let i = imgArr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[imgArr[i], imgArr[j]] = [imgArr[j], imgArr[i]];
}
return imgArr;
};
console.log(shuffle(imgArr));
It does shuffle the array in the console but does not affect the actual visualization.
CodePudding user response:
The image elements have set src
values which you are not changing after the shuffle.
Here is your img
element:
<img src='image/lions.jpg' />
and here is your imgArr
:
imgArr = ["/image/elephant.jpg", "/image/koalas.jpg", "/image/lion.jpg"]
There is no co-relation between the actual img
elements and the imgArr
array.
What you can do is, change the src
attribute of the img
elements after calling shuffle
. Something like this:
const images = document.querySelectorAll('img');
.
.
.
const shuffleArr = function (imgArr) {
for (let i = imgArr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[imgArr[i], imgArr[j]] = [imgArr[j], imgArr[i]];
}
return imgArr;
};
const shuffleInUI = function () {
shuffleArr(imgArr);
images.forEach((img, index) => {
let calcIndex = index >= imgArr.length ? ((index 1)/2) - 1 : index
img.src = imgArr[calcIndex]
})
};
shuffleInUI();
CodePudding user response:
You'll have to use an array that stores your images, then loop through it in javascript. This way you can shuffle the array before displaying it in the DOM.
images = ['image1.png', 'image2.png'...]
Example of shuffling an array:
images.sort(() => Math.random() - 0.5);
You can read more here on how to display it in the DOM