我试图将对象存储在一个多维数组中以试图保存游戏板状态中的每个位置,但是在应该将每个实例设置为它的循环后#' 39;自己的参数它们都以相同的变量结束。我没有链接正确的数组或设置错误吗? 还有很多" square.something应该以静态方式访问"。
square.var或World [x] [y] .var是引用对象变量的正确方法吗?
public static void generateMap() {
MapSquare[][] World = new MapSquare[10][10]; //2D array init.
//Choose a square for the home position.
Random homeRandom = new Random();
int HomeX = homeRandom.nextInt(10);
int HomeY = homeRandom.nextInt(10);
//Chooses a key room.
int KeyX = homeRandom.nextInt(10);
int KeyY = homeRandom.nextInt(10);
//Loop through the objects and set each's parameters.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
MapSquare square = new MapSquare();
//World[i][j] = square;
//Calculate the level of the square from the distance to home.
int distX = HomeX - i;
int distY = HomeY - j;
int CalcX = Math.abs(distX); //Convert to positive if negative.
int CalcY = Math.abs(distY); //Convert to positive if negative.
//Generate contents of the square.
int newRandom = random.nextInt(5) + 1;
switch(newRandom) {
case 1: // Spawn a monster only.
{
square.monster = true;
square.treasure = false;
square.trap = false;
square.home = false;
square.peekable = false;
square.key = false;
square.mapLevel = CalcX + CalcY;
//Generate the monsters stats.
Monster monster = new Monster();
monster.setLevel(square.mapLevel);
monster.setMaxHealth(monster.getLevel() * 5);
monster.setHealth(monster.getMaxHealth());
monster.setDamage(monster.getLevel() * 2);
break;
}
}
}
}
//Generate home square.
World[HomeX][HomeY].monster = false;
World[HomeX][HomeY].treasure = false;
World[HomeX][HomeY].trap = false;
World[HomeX][HomeY].home = true;
World[HomeX][HomeY].peekable = true;
World[HomeX][HomeY].key = false;
World[HomeX][HomeY].mapLevel = 0;
World[HomeX][HomeY].visited = true;
}
答案 0 :(得分:0)
static
关键字基本上意味着方法可以独立于其所在类的特定实例使用。例如您正在使用的Math.abs(int i)
函数,您不必创建<{1}}类的一个实例,可以使用它。
如果您打算使用类来存储数据,那么包含静态方法通常是个坏主意,因为它们无法访问该数据。