Reputation: 1071
Background
I am doing a game project for my java class and we are using a grid system for the playing area. 50 wide by 25 tall. The squares are dynamically sized based on your monitor size and it involves a bit of math. I removed that from my example below so it is easier to look at.
What I currently decided to do is store the grid squares in a nice and simple 2D array so we can access and update the playing area as needed. Here is that code:
// Updates when told to, saves new values
public static void GridList() {
// Record which grid squares are open (0) or blocked (1)
// X = Row and Y = Column
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
gridList[x][y] = 0;
}
}
}
Our Problem
Now the trouble starts when I move on to saving order pairs (x,y) that represent the middle of these grid squares. For example, based on all the math we did to figure out your monitor size, we made a grid 50 wide by 25 tall and now need to save the (x,y) coordinates of the middle of those squares. This is so our AI knows where to move enemies; point by point as long as it is open.
This is what I have so far that saves X coordinates and Y coordinates in their own arrays:
public static void NodeList() {
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
nodeListX[x][y] = *Removed all the math.*;
nodeListY[x][y] = *Removed all the math.*;
}
}
}
What We Are Aiming To Have
What I would really like to do is save an array for every grid square like this:
public static void NodeList() {
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
nodeList[x][y] = *array{x,y}*;
}
}
}
Is this possible in Java? I can't figure this out. I saw things mentioned about lists but we have not covered that yet so I am at a loss.
Upvotes: 0
Views: 68
Reputation: 50726
Honestly, I don't see the problem with your or fdsa's solution. But if you're looking for another approach, you can always use a 3-dimensional array, with the third dimension containing 2 elements for X and Y:
public static void NodeList() {
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
int xPos = *Removed all the math.*;
int yPos = *Removed all the math.*;
nodeList[x][y] = new int[] {xPos, yPos};
}
}
}
Just make sure to declare nodeList
as int[][][]
.
Upvotes: 1
Reputation: 1409
Java doesn't really have a way to store a pair of numbers. But you could make a coordinate class like this:
`public class Coordinate
int x;
int y;
public Coordinate(x,y)
{
this.x=x;
this.y=y;
}
public int getX()
{
return x;
}
public int gety()
{
return y;
}
`
Then you can just create an array of coordinates.
Upvotes: 1