我有一个名为Tile的类,它代表游戏中的一个区块。在我的主屏幕中,我有一个在用户屏幕上绘制图块的循环。我想把每个瓷砖都变成自己的对象。我需要将每个图块(坐标等)的数据存储在一个数组中,以便以后可以访问它们。我还需要将此数组存储在类属性中,以便我可以在主屏幕类的任何方法中访问它们。我的代码在行boardTiles[totalTiles] = new Tile(...);
上抛出异常我假设它是因为我不正确地以某种方式将对象分配给数组。我该如何解决这个问题?
主屏幕java代码:
public class MyGame extends JPanel {
public Tile[] boardTiles;
private void drawHexGridLoop(Graphics g, Point origin, int size, int radius, int padding) {
double ang30 = Math.toRadians(30);
double xOff = Math.cos(ang30) * (radius + padding);
double yOff = Math.sin(ang30) * (radius + padding);
int half = size / 2;
int[] diceSpaces = {2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12};
diceSpaces = shuffleInts(diceSpaces);
String[] resourcesDefault = new String[]{
"Lumber", "Lumber", "Lumber", "Lumber",
"Whool", "Whool", "Whool", "Whool",
"Stone", "Stone", "Stone",
"Wheat", "Wheat", "Wheat", "Wheat",
"Brick", "Brick", "Brick",
"Wasteland"};
String[] resources = shuffleStrs(resourcesDefault);
int totalTiles = 0;
for (int row = 0; row < size; row++) {
int cols;
cols = size - java.lang.Math.abs(row - half);
for (int col = 0; col < cols; col++) {
int xLbl = row < half ? col - row : col - half;
int yLbl = row - half;
int x = (int) (origin.x + xOff * (col * 2 + 1 - cols));
int y = (int) (origin.y + yOff * (row - half) * 3);
String resource;
resource = resources[totalTiles];
int assignedDice;
if(resource.equals("Wasteland")){
assignedDice = 0;
} else {
assignedDice = diceSpaces[totalTiles];
}
drawHex(g, x, y, radius, resource, assignedDice);
boardTiles[totalTiles] = new Tile(totalTiles, xLbl, yLbl, resource, diceSpaces[totalTiles]);
totalTiles++;
}
}
}
}
Tile.java:
import java.awt.*;
import javax.swing.*;
public class Tile {
public int xCoord;
public int yCoord;
public int xPoly;
public int yPoly;
public String resource;
public int diceNumber;
//Starts in top left, goes clockwise. Indicates what occupies a corner(settlement or city and player that owns it.
public String Corner1;
public String Corner2;
public String Corner3;
public String Corner4;
public String Corner5;
public String Corner6;
//Starts on top, goes clockwise. Indicates if a player's road occupies a certain side of the tile.
public String Side1;
public String Side2;
public String Side3;
public String Side4;
public String Side5;
public String Side6;
public boolean hasRobber;
private PolygonObject hexagon;
Tile(int ID, int posX, int posY, String resource, int diceNumber){
this.diceNumber = diceNumber;
this.resource = resource;
}
}
答案 0 :(得分:0)
您需要在实际使用之前初始化电路板磁贴阵列:
public Tile[] boardTiles = new Tile[size*size];