在尝试运行我的java游戏时出错

时间:2014-04-28 19:50:13

标签: java

以下是我在尝试运行游戏时在控制台中收到的代码here

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 64
at com.comli.blah.rainofwrath.graphics.Screen.<init>(Screen.java:22)
at com.comli.blah.rainofwrath.game.<init>(game.java:38)
at com.comli.blah.rainofwrath.game.main(game.java:123)

代码:

public class Screen {

private int width, height;
    public int[] pixels;
    public final int MAP_SIZE = 64;
    public final int MAP_SIZE_MASK = MAP_SIZE - 1;

    public int[] tiles = new int[8 * 8];

    private Random random = new Random();

    public Screen (int width, int height) {
        this.width = width;
        this.height = height;
        pixels = new int[width * height]; // 50,400

        for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {
            tiles[i] = random.nextInt(0xffffff);
        }
    }

    public void clear() {
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = 0;
        }
    }

    public void render(int xOffset, int yOffset) {
        for (int y = 0; y < height; y++) {
            int yy = y + yOffset;
        //  if (yy < 0 || yy >= height) break;
            for (int x = 0; x < width; x++) {
                int xx = x + xOffset;
            //  if (xx < 0 || xx >= width) break;
                int tileIndex = ((xx >> 4) & MAP_SIZE_MASK) + ((yy >> 4) & MAP_SIZE_MASK) * MAP_SIZE;
                pixels[x + y * width] = Sprite.grass.pixels[(x&15) + (y&15) * Sprite.grass.SIZE];
            }
        }

    }

}

1 个答案:

答案 0 :(得分:2)

这里的问题出在tiles数组中。它在初始化期间有64(8 * 8)个元素,而在你循环中指定i < MAP_SIZE * MAP_SIZEMAP_SIZE = 64)为stop-rule时,你试图超出这个限制。我相信它应该是:

public int[] tiles = new int[MAP_SIZE * MAP_SIZE]