我有一个小问题,当我尝试在游戏中绘制多层瓷砖时,只会显示顶层。例如,我有一个for循环来绘制气垫,而在下面,我有另一个要绘制石块。不管我做什么,只有空气砖会绘制,而石材砖则不会。这是我的地图类:
public class Map {
public static final int CLEAR = 0;
public static final int STONE = 1;
public static final int GRASS = 2;
public static final int DIRT = 3;
public static final int WIDTH = 32;
public static final int HEIGHT = 24;
public static final int TILE_SIZE = 25;
static ArrayList<ArrayList<Integer>> map = new ArrayList<ArrayList<Integer>>(WIDTH * HEIGHT);
Image air, grass, stone, dirt;
public Map() {
for (int x = 0; x < WIDTH; x++) {
ArrayList<Integer> yaxis = new ArrayList<Integer>();
for (int y = 0; y < HEIGHT; y++) {
yaxis.add(CLEAR);
}
map.add(yaxis);
}
for (int x = 0; x < WIDTH; x++) {
ArrayList<Integer> yaxis = new ArrayList<Integer>();
for (int y = 0; y < HEIGHT; y++) {
yaxis.add(STONE);
}
map.add(yaxis);
}
try {
init(null, null);
} catch (SlickException e) {
e.printStackTrace();
}
render(null, null, null);
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
air = new Image("res/air.png");
grass = new Image("res/grass.png");
stone = new Image("res/stone.png");
dirt = new Image("res/dirt.png");
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) {
for (int x = 0; x < map.size(); x++) {
for (int y = 0; y < map.get(x).size(); y++) {
switch (map.get(x).get(y)) {
case CLEAR:
air.draw(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
break;
case STONE:
stone.draw(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
break;
case GRASS:
grass.draw(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
break;
case DIRT:
dirt.draw(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
break;
}
}
}
}
}
如果有人可以帮助,那就太好了!
最佳答案
您要添加空气行,然后在此处添加石行:
for (int x = 0; x < WIDTH; x++) {
ArrayList<Integer> yaxis = new ArrayList<Integer>();
for (int y = 0; y < HEIGHT; y++) {
yaxis.add(CLEAR);
}
map.add(yaxis);
}
for (int x = 0; x < WIDTH; x++) {
ArrayList<Integer> yaxis = new ArrayList<Integer>();
for (int y = 0; y < HEIGHT; y++) {
yaxis.add(STONE);
}
map.add(yaxis);
}
问题在于石砖超出了预期的地图大小(32 x 24),因为您添加的行数比您想象的要多两倍。
尝试用数组替换列表列表,您会发现自己超出了范围。
编辑:这是使用随机数据初始化地图的正确方法:
java.util.Random random = new java.util.Random();
for (int x = 0; x < WIDTH; x++) {
ArrayList<Integer> yaxis = new ArrayList<Integer>();
map.add(yaxis);
for (int y = 0; y < HEIGHT; y++) {
yaxis.add(random.nextInt(4));
}
}
请注意,之后您将无需添加图块,而只需更改值即可。
map.get(10).set(5, CLEAR);