首页 > 解决方案 > 蛇游戏中的Java ArrayIndexOutOfBoundException错误

问题描述

我正在尝试构建一个蛇游戏。我几乎完成了它。问题是有时候蛇吃掉敌物的时候会弹出这个错误--->

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 33

er.java:814)

这是敌人的位置单元--->

private int[] enemyYpos = {25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500,525,550,575,600,625,650,675,700,725,750,775,800,825,850};
private int[] enemyXpos = {100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500,525,550,575,600,625};

这是随机数--->

private int xpos = r.nextInt(34);
private int ypos = r.nextInt(20);

现在我使用这些来绘制敌人,方法是使用一个 for 循环,其中定义了敌人的位置 -->

 enemy = new ImageIcon("E:\\Netbeans\\old files\\Game\\src\\game\\bug.png");
    if((enemyXpos[xpos] == snakeXlength[0] && enemyYpos[ypos] == snakeYlength[0])){
    lengthsnake++;
    xpos = r.nextInt(34);
    ypos = r.nextInt(20);
    }
    enemy.paintIcon(this, g, enemyXpos[xpos], enemyYpos[ypos]); //The Exception error shows that the mistake is in this line

我希望这么多信息就足够了。提前致谢!:)

标签: javaarraysswingcompiler-errorsawt

解决方案


您的问题是您将 Xs 和 Ys 混合在一起。它应该是

xpos = r.nextInt(20);
ypos = r.nextInt(34);

而不是相反。


推荐阅读