2012-05-03 264 views
0

我目前正在創建一個遊戲,允許用戶點擊大量的圖像。根據他們點擊的圖像,不同的事情會發生。我看過以前的問題,他們似乎都問:「我如何隨機選擇一個數組內的項目」。但是,我的情況與這些稍有不同。對不起,如果你覺得我的答案在別的地方。但無論如何!如何隨機選擇一個數組?

我的問題很簡單:

如何隨機選擇一個數組?到目前爲止,我的代碼包含一個函數,可以檢查數組中是否存在整數。這是我的代碼到目前爲止。

//The array below contains the integers. 
example=new Array(1,2,3); 


//The function below checks whether 'image' (which is an integer) is the same as any integers within the example array. 

function isItThere(obj) { 
    var j = false; 
    for (var i = 0; i < example.length; i++) { 
     if (example[hits] == obj) { 
      j = true; 
      break; 
     } 
    } 
    return j; 
} 
//This is the IF statement I have used. After the integer associated with 'image' has been passed through the 'isItThere' function either A or B will happen. (A happens if the number exists). 
if(isItThere(image)){ 

目前,這一切都工作得很好。當然,這可能不是最有效的方式,但它實現了我迄今爲止想要的。

但我現在想要有多個包含整數的數組。這是因爲如果用戶重新加載遊戲,那麼他們確切地知道要按下哪些圖像來獲勝。因此,我想創建幾個數組,其中一個數組將在遊戲開始時隨機選擇。

例如..

example0=new Array(1,2,3); 
example1=new Array(4,5,6); 
example2=new Array(7,8,9); 

我相信我應該使用下面的代碼。

var num=Math.floor(Math.random()*3); 

然後以某種方式將該數字鏈接到「示例」一詞。

這樣,我的代碼

if(isItThere(image)){ 

這部分可以保持不變,因爲它是一個隨機排列的選擇交易的isItThere。

希望你得到我想要的東西。我儘量保持描述性。總而言之,我希望能夠在遊戲開始時選擇一個陣列,以便遊戲可以多次播放。你能寫我需要的代碼嗎?我有一種感覺很簡單。但我花了幾天的時間看。

感謝您的幫助:)

+0

創建一個*數組*數組,並選擇其中的一個隨機。請參閱:[從數組中獲取隨機值](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array)。每當你有一個*集合*的東西,使用一個數組或對象來管理它。 –

+0

[Select random function]可能重複(http://stackoverflow.com/questions/9791853/select-random-function) –

回答

2

如何做父母數組,然後參照這個父陣列?

var childArray1 = [1,2,3], 
childArray2 = [4,5,6], 
childArray3 = [7,8,9], 
parentArray = [childArray1, childArray2, childArray3]; 

您也可以用parentArray.push(childArray1)添加他們。,哪一個更適合你。

+0

你剛剛解決了我的問題!謝謝!所以是的,如果人們現在和我有同樣的問題 - 拿Zvonas回答。 – user1371984

0

你應該做一個數組的數組,並選擇隨機:

var myArray = [ 
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9], 
]; 

var theArray = myArray[Math.random() * 3)]; 
+0

我不知道我在這裏做錯了什麼。但如果我要用你的答案。我是否正確地將我的代碼更改爲 函數inArray(obj){var j = false; (var hits = 0; hits user1371984

+0

是的,它應該工作,實際上它與@zvona答案完全相同,但不是有多個childArray,而是直接在家長。而我的'myArray'與@ zvona的'parentArray'完全相同。 –