java - 蛇游戏中的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
我希望这么多信息就足够了。提前致谢!:)
解决方案
您的问题是您将 Xs 和 Ys 混合在一起。它应该是
xpos = r.nextInt(20);
ypos = r.nextInt(34);
而不是相反。
推荐阅读
- mysql - MySQL存储过程将参数输入与表值进行比较
- unit-testing - 如何初始化对象一次并将其用于所有测试用例
- nativescript - Nativescript Vue:当数据更改时,RadListView 不刷新
- c++ - 在 getline 之前进行字符串流初始化的原因是什么,但反过来却不行?
- c - 程序一直打印一个零字节?
- android - Android Studio:房间:错误:找不到字段的吸气剂
- sql-server - 从 VB.NET 中的 SQL Server 返回布尔值
- java - 如何将固定字符串值作为短信发送?
- django - 尝试注销时的 Django NoReverseMatch
- scala - Scala 模棱两可的案例类生成和伴随的应用方法