gpt4 book ai didi

javascript - 随机播放一组图像而不重复

转载 作者:行者123 更新时间:2023-12-02 15:29:41 25 4
gpt4 key购买 nike

我正在尝试将 3 个数组打乱(不是在一起),以创建一个拼图游戏。 var 单元格内的信息来 self 在 HTML 代码中定义每个部分等时的信息。当我重新加载页面时,我需要出现三个数组之一,并且需要内容按随机顺序排列。拼接对我没有任何帮助...我有时拥有所有拼图元素,有时缺少一个(我知道,我知道,拼接会删除)。有什么想法吗?

var cells = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11", "c12",];

var imageSet1 = ["./images1/img1-1.jpg", "./images1/img1-2.jpg", "./images1/img1-3.jpg", "./images1/img1-4.jpg", "./images1/img1-5.jpg", "./images1/img1-6.jpg", "./images1/img1-7.jpg", "./images1/img1-8.jpg", "./images1/img1-9.jpg", "./images1/img1-10.jpg", "./images1/img1-11.jpg", "./images1/img1-12.jpg"];

var imageSet2 = ["./images2/img2-1.jpg", "./images2/img2-2.jpg", "./images2/img2-3.jpg", "./images2/img2-4.jpg", "./images2/img2-5.jpg", "./images2/img2-6.jpg", "./images2/img2-7.jpg", "./images2/img2-8.jpg", "./images2/img2-9.jpg", "./images2/img2-10.jpg", "./images2/img2-11.jpg", "./images2/img2-12.jpg"];

var imageSet3 = ["./images3/img3-1.jpg", "./images3/img3-2.jpg", "./images3/img3-3.jpg", "./images3/img3-4.jpg", "./images3/img3-5.jpg", "./images3/img3-6.jpg", "./images3/img3-7.jpg", "./images3/img3-8.jpg", "./images3/img3-9.jpg", "./images3/img3-10.jpg", "./images3/img3-11.jpg", "./images3/img3-12.jpg"];

var imgSet = [imageSet1, imageSet2, imageSet3];
var imgShuffed = imgSet[Math.floor(Math.random() * imgSet.length)];
for (c in cells) {
var index = Math.floor(Math.random() * imgSet.length);
document.getElementById(cells[c]).src = imgShuffed[index];
imgShuffed.splice(index,1);
}

最佳答案

将问题分解为几个部分。首先,让我们看看如何对数组进行洗牌。

我能想到的打乱数组的最简单方法是不断选择随机元素,直到所有元素都消失:

function shuffleArray(arr) {
var newarray = [];
while(arr.length > 0) {
var chosenIndex = Math.floor(Math.random() * arr.length); //choose a number thats in the array
var chosenValue = arr[chosenIndex];
newarray.push(chosenValue); //add the new value to the array
arr.splice(chosenIndex, 1); //and "remove" it from the old array by creating a new array without it
}
return newarray;
}

console.log(shuffleArray([1,2,3,4,5])); //example

接下来,选择您正在做的正确谜题。

var imgSet = [imageSet1, imageSet2, imageSet3];
var chosenSet = imgSet[Math.floor(Math.random()*imgSet.length)];

然后随机播放所选集合:

var shuffledChosenSet = shuffleArray(chosenSet);

现在,使用该打乱的集合来完成工作。

关于javascript - 随机播放一组图像而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33430304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com