Langton蚂蚁的问题很简单.一只蚂蚁走在白板和黑色方块的板上.
当"游戏"开始时,棋盘全是白色的.
我已经实施了模拟但是有一个非常丑陋的步行和转弯解决方案,我需要帮助改进.现在步行如下:
if (dir == "NORTH") {
    // Walk up
} else if (dir == "EAST") {
    // Walk right
} else if (dir == "SOUTH") {
    // Walk down
} else if (dir == "WEST") {
    // Walk left
}           
Run Code Online (Sandbox Code Playgroud)
以及改变方向的功能:
private void turn(String leftOrRight){
    if(dir == "NORTH" && lor == "RIGHT" ){
        dir = "EAST";
    } else if (dir == "NORTH" && leftOrRight == "LEFT" ){
        dir = "WEST";
    } else if (dir == "EAST" && leftOrRight == "RIGHT" ){
        dir = "SOUTH";
    } else if (dir == "EAST" && leftOrRight == "LEFT" ){
        dir = "NORTH";
    } else if (dir == "SOUTH" && leftOrRight == "RIGHT" ){
        dir = "WEST";
    } else if (dir == "SOUTH" && leftOrRight == "LEFT" ){
        dir = "EAST";
    } else if (dir == "WEST" && leftOrRight == "RIGHT" ){
        dir = "NORTH";
    } else if (dir == "WEST" && leftOrRight == "LEFT" ){
        dir = "SOUTH";
    }
}
Run Code Online (Sandbox Code Playgroud)
我曾考虑使用int而不是字符串,但不太确定我应该怎么做.任何帮助或提示表示赞赏.
编辑:现在我改变了一些.我创建了一个包含变量的Ant类
int x, int y, Direction dir
Run Code Online (Sandbox Code Playgroud)
并使用以下方法运行它:
private void runAnt(Ant ant) {
    int x = ant.getX();
    int y = ant.getY();
    // Check rule 1
    if (matrix[x][y] == true) {
        matrix[x][y] = false;
        w.setDot(x, y, Color.WHITE);
        ant.setDirection(ant.getDirection().right());
    // Check rule 2
    } else if (matrix[x][y] == false) {
        matrix[x][y] = true;
        w.setDot(x, y, Color.BLACK);
        ant.setDirection(ant.getDirection().left());
    }
    // Moves one unit forward according to direction.
    if (ant.getDirection().equals(Direction.N)) {
        ant.setY((ant.getY() - 1 + wSize) % wSize);
    } else if (ant.getDirection().equals(Direction.E)) {
        ant.setX((ant.getX() + 1) % wSize);
    } else if (ant.getDirection().equals(Direction.S)) {
        ant.setY((ant.getY() + 1) % wSize);
    } else if (ant.getDirection().equals(Direction.W)) {
        ant.setX((ant.getX() - 1 + wSize) % wSize);
    }
}
Run Code Online (Sandbox Code Playgroud)
我的第一个枚举:
public static enum Direction {
    N, E, S, W;
    private static Direction[] vals = values();
    public Direction right() {
        return vals[(this.ordinal() + 1) % vals.length];
    }
    public Direction left() {
        return vals[(this.ordinal() + vals.length - 1) % vals.length];
    }
}
Run Code Online (Sandbox Code Playgroud)
    |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2953 次  |  
        
|   最近记录:  |