从Flash CC中的电影片段(或时间线中的标签)阵列中获取随机元素.行动脚本3



我现在正在flashCC中制作一个非常巧妙的智力竞赛游戏,我肯定需要你的帮助。我的技能更多的是在设计方面,而不是在编程方面。所以对你们中的许多人来说,这可能是一个幼稚的问题(以前问过很多次),但从我目前看到的所有答案来看,我的项目没有任何结果。

事情是这样的:我需要EXACT脚本来创建一个数组(里面有movieclips?或者mcs的实例名?这是怎么回事?)以及一种方法,在不重复的情况下从这个数组中随机选择一个元素,直到"游戏结束"。

Paul

从数组中挑选随机元素而不重复的最简单方法是首先用"random"函数对数组进行排序,然后从中取出popshift项,直到数组为空。

假设您有一个项目数组,可以用实例或实例名称填充,您选择了实例名称::

var FirstArray:Array = ["blau", "orange", "green"];

现在,您需要一个随机排序函数:

// you do not need to modify this function in any way. 
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that    
function randomSort(a:Object, b:Object):int
{
    return Math.random() > .5 ? -1 : 1;
}

排序函数的正常工作方式是比较两个对象,如果第一个项在第二个项之前,则返回-1;如果相反,则返回1;如果相同,则返回0。

因此,我们在上面的函数中所做的是随机返回-1或1。当你调用时,这应该会把数组弄得一团糟

FirstArray.sort(randomSort);

现在数组是随机排序的,您可以开始从中提取项目,如下所示:

if(FirstArray.length) // make sure there's at least one item in there
{
    // since you are using instance names, you'll need to use that to grab a reference to the actual instance:
    var currentQuizItem:MovieClip = this[FirstArray.pop()];
    // if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
    // every time you call pop on an array, you're removing the last item
    // this will ensure that you won't repeat any items
    // do what you need to do with your MovieClip here
}
else
{
    // if there aren't any items left, the game is over
}

当串在一起时,上面的代码应该足以让您启动并运行。

您可以尝试以下操作:

var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0) 
{
    shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}
trace('shuffledArray: ', shuffledArray, 'nrandom item: ', shuffledArray[0]);

最新更新