Java2D数组-如何将数组指定为值?
背景Java2D数组-如何将数组指定为值?,java,arrays,Java,Arrays,背景 我正在为我的java类做一个游戏项目,我们正在使用一个网格系统作为游戏区。50宽25高。这些方块是根据显示器的大小动态调整的,这需要一些数学知识。我将其从下面的示例中删除,以便更容易查看 我现在决定做的是将网格正方形存储在一个漂亮简单的2D阵列中,这样我们就可以根据需要访问和更新游戏区域。这是代码: // Updates when told to, saves new values public static void GridList() { // Record which grid s
我正在为我的java类做一个游戏项目,我们正在使用一个网格系统作为游戏区。50宽25高。这些方块是根据显示器的大小动态调整的,这需要一些数学知识。我将其从下面的示例中删除,以便更容易查看 我现在决定做的是将网格正方形存储在一个漂亮简单的2D阵列中,这样我们就可以根据需要访问和更新游戏区域。这是代码:
// 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;
}
}
}
//通知时更新,保存新值
公共静态void GridList(){
//记录哪些方格是开放的(0)或封闭的(1)
//X=行,Y=列
对于(int x=0;x<50;x++){
对于(int y=0;y<25;y++){
网格列表[x][y]=0;
}
}
}
我们的问题现在,当我继续保存表示这些网格正方形中间的顺序对(x,y)时,问题就开始了。例如,根据我们计算显示器尺寸所做的所有计算,我们制作了一个50宽25高的网格,现在需要保存这些正方形中间的(x,y)坐标。这使得我们的AI知道将敌人转移到哪里;一点一点,只要它是开放的 到目前为止,我已经将X坐标和Y坐标保存在它们自己的数组中:
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.*;
}
}
}
publicstaticvoidnodelist(){
对于(int x=0;x<50;x++){
对于(int y=0;y<25;y++){
nodeListX[x][y]=*删除了所有数学运算。*;
nodeListY[x][y]=*删除了所有数学运算。*;
}
}
}
我们的目标是什么我真正想做的是为每个网格正方形保存一个数组,如下所示:
public static void NodeList() {
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
nodeList[x][y] = *array{x,y}*;
}
}
}
`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;
}
`
publicstaticvoidnodelist(){
对于(int x=0;x<50;x++){
对于(int y=0;y<25;y++){
节点列表[x][y]=*数组{x,y}*;
}
}
}
这在Java中可能吗?我想不出来。我看到了一些关于列表的内容,但我们还没有涵盖这些内容,所以我很困惑。Java实际上没有存储一对数字的方法。但您可以创建一个类似这样的坐标类:
public static void NodeList() {
for (int x = 0; x < 50; x++ ) {
for ( int y = 0; y < 25; y++ ) {
nodeList[x][y] = *array{x,y}*;
}
}
}
`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;
}
`
然后你可以创建一个坐标数组。老实说,我看不出你或fdsa的解决方案有什么问题。但如果您正在寻找另一种方法,则始终可以使用三维数组,其中三维数组包含X和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};
}
}
}
publicstaticvoidnodelist(){
对于(int x=0;x<50;x++){
对于(int y=0;y<25;y++){
int xPos=*删除了所有数学运算。*;
int yPos=*删除了所有数学运算。*;
nodeList[x][y]=newint[]{xPos,yPos};
}
}
}
只需确保将
nodeList
声明为int[][[]
当我有更多时间时,我需要看看这个,但这似乎没有多大帮助。我仍然有两个独立的变量/数组,需要在循环中调用和组合以提取坐标。我有1250个有序对,需要尽快保存和访问。你说的符号数组{x,y}是什么意思?我来自PHP背景,所以它的意思是数组。在PHP中,这意味着:$gridSquare=$nodeList[x][y];然后我可以像这样拉出X和Y:$gridSquare[0]$gridSquare[1];我很难将其与Java联系起来,似乎3D数组更符合我的要求,但我还没有尝试过。与其使用内部数组,不如使用类坐标。是一样的。