Reputation: 5
I am currently creating a game that allows the user to click on numerous amounts of images. Depending on which image they click, different things will happen. I have looked at previous questions and they all seem to ask "How do I randomly select an item inside an array". However, mine is slightly different to these. Sorry if you feel that my answer lies somewhere else. But anyhow!
My question is simply:
How do I randomly select an array? My code so far contains a function that can check whether an integer exists within an array. This is my code so far.
//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)){
Currently, this all works perfectly fine. Granted it might not be the most efficent way, but it achieves what I have so far wanted.
But I now want to have multiple arrays that contain integers. This is because if the user reloads the game then they know exactly which images to press for them to win. I am therefore wanting to create several arrays and one of which will be selected at random at the beginning of the game.
For example..
example0=new Array(1,2,3);
example1=new Array(4,5,6);
example2=new Array(7,8,9);
I believe I should be using the following code.
var num=Math.floor(Math.random()*3);
And then somehow link that number to the word 'example'.
That way, this part of my code
if(isItThere(image)){
can stay the same, as it is the isItThere that deals with the choosing of a random array.
Hopefully you get what I'm trying to ask for. I have tried to be as descriptive as possible. To summarise once again, I want to be able to select one array at the beginning of the game so that the game can be played multiple times. Can you write the code I need? I have a feeling its very simple. But ive spent days looking.
Thanks for the help :)
Upvotes: 0
Views: 199
Reputation: 39859
You should do an array of arrays, and choose with random :
var myArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
var theArray = myArray[Math.random() * 3)];
Upvotes: 0
Reputation: 19049
How about making a parent array and then referring to this parent array?
var childArray1 = [1,2,3],
childArray2 = [4,5,6],
childArray3 = [7,8,9],
parentArray = [childArray1, childArray2, childArray3];
You can also add them with parentArray.push(childArray1); , just which one suits you better.
Upvotes: 2