[英]how do I make changes to a 2d array stick?
我查找了一些与此类似的问题,但没有发现任何有用的东西。
我正在创建一个棋盘游戏,我正在使用 2d arrays。 我正在尝试将“房间”object 添加到“板”object。
食宿都是2d arrays。 我将它们保留为 String arrays 并在绘图方法中运行它们以显示 position (这是电路板的一小部分)。
我正在尝试将 Board 2d 数组的内容更改为包含 Room 2d 数组。
这是板 Class:
public class Board {
private String[][] board;
public Board(int x, int y) {
board = new String[x][y];
for (int i = 0;i < x; i++) {
for (int j = 0; j < y; j++) {
board[i][j] = "floor";
}
}
}
public void addToSquare(int x, int y, String item) {
String currentItems = this.getFromSquare(x,y);
currentItems.concat(item);
board[x][y] = currentItems;
}
public void clearSquare(int x, int y) {
board[x][y] = "";
}
public void addRoom(Room room, int centrePointX, int centrePointY) {
for (int i = 0; i < room.roomX; i++) {
for(int j = 0; j < room.roomY; j++) {
String roomContents = room.getContents(i,j);
int roomOriginX = room.radX;
int roomOriginY = room.radY;
this.clearSquare((centrePointX-2 + i), (centrePointY-2 + j));
this.addToSquare((centrePointX-2 + i), (centrePointY-2 + j), roomContents);
}
}
}
public String getFromSquare(int x, int y) {
return board[x][y];
}
public String[][] getShownPosition(int playerX, int playerY, int shownWidth, int shownHeight){
String[][] shownPosition = new String[shownWidth][shownHeight];
int radX = shownWidth / 2;
int radY = shownHeight /2;
for (int i = 0; i < shownPosition.length; i++) {
for(int j = 0; j < shownPosition.length; j++) {
if (!((playerX-radX)+i <0 || (playerY -radY)+j <0 || (playerX-radX)+i >= board.length || (playerY -radY)+j >= board.length)) {
shownPosition[i][j] = board[(playerX - radX) + i][(playerY - radY) + j];
}else{
shownPosition[i][j] = "blackSpace";
}
}
}
return shownPosition;
}
}
当我开始绘制 position 时,我运行“ShownPosition”并显示基于字符串的图像。
这可能不是正确的方法,但是 - 直到房间部分 - 一切正常。
问题是房间没有出现。 正如你所看到的,我已经用“墙壁”填满了整个房间,只是为了更容易看到它何时加载。
我添加了“clearsquare”和“addtosquare”方法,就像我之前所说的 board[x][y] = roomContents.
在我写的更新方法中
shownPosition = mBoard.getShownPosition(player.boardx,
player.boardy,
shownBoardX,
shownBoardY);
但无论我尝试什么,我都无法获得一个“房间”来展示。
任何帮助表示赞赏!
您似乎忽略了currentItems.concat(item);
的结果在Board::addToSquare
中,因此它实际上从未向其中添加任何内容。 它应该是
public void addToSquare(int x, int y, String item) {
String currentItems = this.getFromSquare(x,y);
currentItems = currentItems.concat(item);
board[x][y] = currentItems;
}
此外,当涉及到二维 arrays 和坐标时,请确保您实际存储值并使用正确的坐标访问它们。 例如,查看以下代码生成的内容:
for(int x=0; x<3; x++){
System.out.println("\n");
for(int y=0; y<5; y++){
System.out.printf("%s,%s\t", x, y);
}
}
Output:
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
您可能会注意到,数组是以 Y 实际代表列而 X 代表行的方式生成的。 为了在您的代码中解决此问题,您需要以相反的顺序生成每个二维数组,即首先遍历行然后遍历列:
for (int j=0; j<y; j++){ // <- these two
for (int i=0; i<x; i++){ // <- lines
board[i][j] = "floor";
}
}
或切换坐标:
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
board[j][i] = "floor"; // <- here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.