我正在制作一个javascript记忆游戏,它实际上正在运行,但我希望图像以随机顺序加载。只是我不知道该怎么做。
目前的情况如下:
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);
}
}
答案 0 :(得分:0)
可能是这样的:
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;
}
答案 1 :(得分:0)
您可以使用要显示的图像创建另一个数组,然后使用随机数生成器显示该数组的随机生成索引,确保将随机范围设置为数组的长度,否则它将返回数字超出您的索引。然后删除阵列中该位置的图像元素,只留下未显示的图片。