嗨,我编写了代码,但唯一的问题是当有墙或越界时不要移动。我理解做到这一点的困难方式是编码类似

if (CHARACTER == line [2][0] && (dir.equalsIgnoreCase("l")) {}

"l"被留下)这样,当玩家想要离开时(因为有墙)它不会在那个特定位置移动,但是我必须在所有情况下都这样做,这似乎很繁琐。有什么帮助吗?谢谢。

如果有帮助,这是其中的一部分:

private final static char CHARACTER = 'X';
private final static char BLANK = '.';
private final static char GOAL = 'O';
private final static char WALL = 'W';

private final static int SIZE = 4;

public static void main(String[] args) {

    char[][] line = new char[SIZE][SIZE];

    for(int i = 0; i < line.length; i++)
    {
        for(int j = 0; j < line[i].length; j++)
        {
            line[i][j] = BLANK;
        }
    }

    line[2][0] = CHARACTER;
    line[0][0] = GOAL;
    line[1][0] = WALL;
    line[1][1] = WALL;
    line[1][3] = WALL;
    line[2][1] = WALL;
    line[2][3] = WALL;
    int xPos = 2;
    int yPos = 0;
}

最佳答案

您可以使用索引来检查是否超出范围或是否有墙。我建议这样(注意:这仅适用于Java 7或更高版本)

// I assume your board is always square because of new char[SIZE][SIZE]
private static boolean isOutOfBounds(int coord) {
    return coord < 0 || coord >= SIZE;
}

/**
 * Checks, if the given coordinate is inside bounds and is not a wall.
 */
private static boolean isValid(int x, int y) {
    return !isOutOfBounds(x) &&
           !isOutOfBounds(y) &&
           line[x][y] != WALL;
}

// I assume you have directions "u", "r", "d", "l"
public static boolean canGoDirection(String direction, int currX, int currY) {
    switch(direction) {
        case "u": return isValid(currX, currY - 1);
        case "r": return isValid(currX + 1, currY);
        case "d": return isValid(currX, currY + 1);
        case "l": return isValid(currX - 1, currY);
        default: throw new IllegalArgumentException(direction + " is not a valid direction.");
    }
}


现在,您可以将canGoDirection()与当前坐标和所需方向一起使用。如果返回true,则可以使用该方法来更新新职位。

08-15 21:54