Question regarding 2d arrays
Ok, this may seem like a dumb question, but I am doing a creative project for my AP computer science class, and I chose to do an RPG(original, huh? lol) anyway, it is text based and the way I have it is that you start off at a certain point on a grid (using 2d) array, and you go north south east and west.
Now, the problem is I need to know if there is a way to store different methods I guess, in the individual spaces in the 2d array. Is that even possible? I just want to be able to use this for each event that the player would encounter. Anyway, if this is not possible, can you tell me of a different way to do this?
Re: Question regarding 2d arrays
Yes it's possible to via reflection, but the better way would probably be to create an interface and have each tile hold an object which implements that interface.
Re: Question regarding 2d arrays
I am new to java, so bear with me, how exactly would you be able to have each tile hold an object that implements the interface? What would the code for that look like? Would it simply be for me to set a variable equal to the method? Or how would you do that? I am not completely sure what it would look like.
Re: Question regarding 2d arrays
Methods do NOT have an existence outside of a class. You can't move them around, assign them, store them etc. You do that with a class object.
As helloworld922 said, you create a class with the method.
Then you can create instances of that class and treat a reference to that instance like any other variable.
You can create an array that holds instances of your class. For example:
YourClass[] tableOfItems = new YourClass[13]; // create array to hold 13 YourClass objects
Re: Question regarding 2d arrays
Yes I knew that, but what I was confused on was how to store the instances of that class into an individual cell, that is what I need help on. Like I wanted to make 2darray[0][0] = some call to a method, or something. That is what I am trying to do. When they move down they will go to 2darray[1][0] in which would have a new method saying "You traveled south, blah blah, blah".
Re: Question regarding 2d arrays
Quote:
how to store the instances of that class into an individual cell
Just like with any data type:
tableOfItems[3] = new YourClass(); // store an instance of YourClass at index 3
Quote:
I wanted to make 2darray[0][0] = some call to a method
Say the class YourClass has a method: methodInYourClass()
To call the method:
tableOfItems[3].methodInYourClass(); // call a method on instance at index 3
Re: Question regarding 2d arrays
Ok, so what I would have to do is to store an instance of my class in each cell like at 0,0 all the way to 10,10 if I had a 10 X 10 grid. Correct?
Re: Question regarding 2d arrays
Yes, well almost. The max index in a 10x10 array would be 9,9
Re: Question regarding 2d arrays
Yeah, alright thanks guys for your help!