挑選從陣列的隨機元素而不必重複是陣列具有「隨機」功能pop
或shift
項目,直到該數組爲空先進行排序,然後在它外面的最簡單方法。
比方說,你有哪些可填充的實例或實例名稱的項目,你選擇的實例名稱的數組:
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,如果如果情況相反,和0,如果它們是相同的第一個項目之前的第二項,1。
所以我們在上面的函數中做的是隨機返回-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 FirstArray:Array = [「blau」,「orange」,「green」];作爲我現在的陣列。所以「blau」,「orange」等等是mcs-properties中mcs的實例名稱。那函數randomSort(a:Object,b:Object):int - 你寫的東西對我來說還是太難修改了(我對此很感興趣^^)是一個對象的例子,它是來自AS3的命令嗎?或兩者都不?我只需要得到一個小例子腳本運行,從那裏我會做到。 「= clips.pop();」對我來說也是新的。 – randompaul