我正在做一个作业,其中涉及用Java编写破砖游戏。有一个gui和2个枚举类。我们必须编写4个类,Level,Paddle,Ball和Brick。目前,我被困在Level班上。我正在尝试输出一个砖块数组,但是在第120行:String index out of range: 2
上得到了if (brickConfig[x].substring(i, i + 1).equals("*"))
。我唯一坚持使用的构造器包含brickConfig
。我不相信我还没有找到砖之间的像素间距,但是我假设它将在此类的数组创建中的某个位置。积木类中的-1
转换为牢不可破的积木。
public class Level
{
private int startLeft = 10;
private int startTop = 10 * 4;
private Ball levelBall;
private Paddle levelPaddle;
private int width;
private int height;
private Brick[][] levelStructure = new Brick[5][7];
private GameState gState;
public Level(int widthIn, int heightIn)
{
width = widthIn;
height = heightIn;
levelBall = new Ball(width / 2, height / 2);
levelPaddle = new Paddle(0, 420);
}
/**Creates a level with a given dimension and specified brick
* configuration. The Brick configuration is specified through an
* array of String values where each character corresponds to a
* single Brick.This array of Strings is guaranteed to contain 5
* valid Strings, each of which will have 7 characters.Characters
* in the string will correspond to one value in
* {'*', '0', '1', '2', '3'} where:
* '*' signifies a brick that cannot be broken
* '0' signifies a "ghost brick" that is already broken
* '1' signifies a brick that requires one hit to break
* '2' signifies a brick that requires two hits to break
* '3' signifies a brick that requires three hits to break
*
* Input strings are assumed valid and no error checking is
* provided.
*
* Bricks are arranged starting 40 pixels from the top edge of
* the screen and 10 pixels from the left edge of the screen.
* Bricks should be spaced with 5 pixels between each Brick in
* both dimensions.
*
* The Ball will start in the center of the screen, and the
* Paddle's top-left edge should be positioned at the left edge
* and 20 pixels up from the bottom of the screen.
*
* @param widthIn The logical width of the new level in pixels.
* @param heightIn The logical height of the new level in pixels.
* @param brickConfig The configuration array specifying the grid of Bricks to use in this new level.
*/
public Level(int widthIn, int heightIn, java.lang.String[] brickConfig)
{
width = widthIn;
height = heightIn;
gState = GameState.PLAYING;
for (int x = 0; x < levelStructure.length; x++)
{
for (int i = 0; i < levelStructure[x].length; i++)
{
if (brickConfig[x].substring(i, i + 1).equals("*"))
{
levelStructure[x][i] = new Brick(startTop, startLeft, -1);
}
else
{
levelStructure[x][i] = new Brick(startTop, startLeft,
Integer.parseInt(brickConfig[x].substring(i, i + 1)));
}
}
}
}
答案 0 :(得分:0)
问题是您遍历字符串的方式。 i + 1可能是最后一个字符+ 1,这超出了范围。尝试使用string.length