2d迷宫如何不移动到墙壁或超出界限



嗨,我已经做了我的代码,但我唯一的问题是不移动时,有一堵墙或越界。我理解的最难的方法是编写像

这样的代码

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,您可以按照该方式更新您的新位置。

我从你的问题中理解的是,如果下一个位置是墙,你的玩家不应该移动。假设玩家的起始位置不是墙。

我想你一定有一些方法来跟踪玩家当前的位置。在游戏的主循环中保持这两个索引的更新。检查下一个位置的数组值,如果它是不移动的(不更新索引)。

相关内容

最新更新