0

I am trying to build a snake game. I have almost completed it. The problem is that sometimes when the snake eats the enemy object, this error pops up --->

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

er.java:814)

This is the location cell for the enemy --->

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};

And this is for the random number --->

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

Now i use these to paint the enemy by using a for loop inside which the location of enemy is defined -->

 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

I hope this much info is enough. Thanks in advance! :)

Ankit Rath
  • 59
  • 7

2 Answers2

0

Your problem is that you are mixing your Xs and Ys. It should be

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

and not the other way around.

Halko Karr-Sajtarevic
  • 2,248
  • 1
  • 16
  • 14
0

I think you swapped the number of x elements and the number of y elements. Easiest fix. Change your generators to use the length of the arrays instead of magic numbers.

private int xpos = r.nextInt(enemyXpos.length);
private int ypos = r.nextInt(enemyYpos.length);

and

xpos = r.nextInt(enemyXpos.length);
ypos = r.nextInt(enemyYpos.length);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249