我目前正在創建一個遊戲,允許用戶點擊大量的圖像。根據他們點擊的圖像,不同的事情會發生。我看過以前的問題,他們似乎都問:「我如何隨機選擇一個數組內的項目」。但是,我的情況與這些稍有不同。對不起,如果你覺得我的答案在別的地方。但無論如何!如何隨機選擇一個數組?
我的問題很簡單:
如何隨機選擇一個數組?到目前爲止,我的代碼包含一個函數,可以檢查數組中是否存在整數。這是我的代碼到目前爲止。
//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。
希望你得到我想要的東西。我儘量保持描述性。總而言之,我希望能夠在遊戲開始時選擇一個陣列,以便遊戲可以多次播放。你能寫我需要的代碼嗎?我有一種感覺很簡單。但我花了幾天的時間看。
感謝您的幫助:)
創建一個*數組*數組,並選擇其中的一個隨機。請參閱:[從數組中獲取隨機值](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array)。每當你有一個*集合*的東西,使用一個數組或對象來管理它。 –
[Select random function]可能重複(http://stackoverflow.com/questions/9791853/select-random-function) –