我正试图在java中制作一个roguelike来练习。这是我生成一个楼层的代码(现在只是一个带有墙砖的大房间)。我正在尝试将我的瓷砖阵列中的某些瓷砖设置为墙砖或地砖。虽然当他们离开setTile方法时,他们会在进入方法之前恢复其值。我疯了。这是我的代码:
public Floor(int width, int height) {
this.tiles = new Tile[(width+1)*(height+1)];
this.width = width;
this.height = height;
generateTiles();
boolean test = false;
}
public Tile getTile(int x, int y)
{
return tiles[y * width + x];
}
public void setTile(int x, int y, Tile tile)
{
Tile tileToSet = getTile(x,y);
tileToSet = tile;
}
private void generateTiles() {
for (int i = 0; i < tiles.length; i++)
{
tiles[i] = new Tile();
}
//make the top wall
for (int i = 0; i<width;i++)
{
setTile(i,0,new WallTile());
}
}
}
答案 0 :(得分:1)
此代码将相同的变量设置为两次并且不执行任何操作。
public void setTile(int x, int y, Tile tile)
{
Tile tileToSet = getTile(x,y);
tileToSet = tile;
}
我想你想要这样的东西:
public void setTile(int x, int y, Tile tile)
{
tiles[y * width + x] = tile;
}
这会将tiles数组中存储的值更改为提供的Tile对象。
答案 1 :(得分:1)
查看您的setTile
方法:
public void setTile(int x, int y, Tile tile)
{
Tile tileToSet = getTile(x,y);
tileToSet = tile;
}
您将在x,y处获取切片值并将其设置为局部变量(tileToSet
),然后将tile
值设置为变量tileToSet
。当然它不会改变x,y处的瓦片。 tileToSet
只是对值的引用,它永远不是对数组元素的引用。
替换为:
public void setTile(int x, int y, Tile tile)
{
tiles[y * width + x] = tile;
}
如果你想要一个返回tile index 的方法,就像你在命令中说的那样,你可以像这样重写get / set对:
public void setTile(int x, int y, Tile tile)
{
tiles[getTileIndex(x, y)] = tile;
}
public Tile getTile(int x, int y)
{
tiles[getTileIndex(x, y)] = tile;
}
public int getTileIndex(int x, int y)
{
return y * width + x;
}
答案 2 :(得分:1)
你需要做的是这样的事情:
public Floor(int width, int height) {
this.tiles = new Tile[(width+1)*(height+1)];
this.width = width;
this.height = height;
generateTiles();
boolean test = false;
}
public Tile getTile(int x, int y)
{
return tiles[y * width + x];
}
public void setTile(int x, int y, Tile tile)
{
tiles[y * width + x] = tile;//this works cuz it takes the ref from the array and assigns it the copy of the reference passed in
}
private void generateTiles() {
for (int i = 0; i < tiles.length; i++)
{
tiles[i] = new Tile();
}
//make the top wall
for (int i = 0; i<width;i++)
{
setTile(i,0,new WallTile());
}
}
}
查看此文章以获取解释:http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
答案 3 :(得分:1)
您的setTile
没有意义。您正在检索当前位于该位置的磁贴,将其存储在本地变量 tileToSet
中,然后覆盖该值那个变量。
您尝试要做的是将给定的磁贴存储在tiles
数组中。类似于getTile
的实现方式,您可以使用以下方法执行此操作:
public void setTile(int x, int y, Tile tile)
{
tiles[y * width + x] = tile;
}
请注意, 等效(但您似乎认为是)<:p>
public void setTile(int x, int y, Tile tile)
{
Tile tileToSet = tiles[y * width + x];
tileToSet = tile;
}