1

我正在创建一个迷宫程序以在 Java 中进行更多练习。我有一个移动玩家的方法,boolean如果移动成功(即它没有撞到墙),它会返回一个值。

这是有问题的方法:

public boolean move(Direction direction) {
    if(currentLocation == (currentLocation = maze.movePlayer(this, direction))) {
        return false;
    } else {
        return true;
    }
}

显然,这将始终返回 false。我想知道是否有一种方法可以检查是否currentLocation没有更改(或等于的返回值,maze.movePlayer(...)如果不是,则将它们设置为相等)。我不知道是否可以在不调用该方法两次或使用局部变量的情况下执行此操作。

我希望这是有道理的!

4

3 回答 3

3

您可以使用条件运算符:

public boolean move(Direction direction) {
     return (currentLocation == (currentLocation = maze.movePlayer(this, direction))) ? false : true;
}
于 2012-07-05T16:26:54.537 回答
2

equals假设一种合理的方法,这可以按照您的预期工作,使用单行。

(我通过 aLocation而不是转换 a Direction,但机制是相同的。)

public class Main {

    private Location loc = new Location(0, 0);

    public boolean move(Location newLoc) {
        return !loc.equals(loc = newLoc);
    }

    public static void main(String[] args) {
        Main m = new Main();

        // Not same; moved from 0, 0: true--move successful.
        System.out.println(m.move(new Location(42, 69)));

        // Same; moved from 42, 69: false--move failed.
        System.out.println(m.move(new Location(42, 69)));

        // Not same; moved from 42, 69, 0: true--move successful.
        System.out.println(m.move(new Location(69, 42)));
    }
}

这使用了一个简单的Location实现;注意equals, 由 IntelliJ 自动生成:

public class Location {

    private int x;
    private int y;

    public Location(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Location location = (Location) o;

        if (x != location.x) {
            return false;
        }

        if (y != location.y) {
            return false;
        }

        return true;
    }

}
于 2012-07-05T16:49:41.067 回答
0

使用临时变量的另一种方法:

public boolean move(Direction direction) {
    Location oldLocation = currentLocation;
    currentLocation = maze.movePlayer(this, direction));
    return !oldLocation.equals(currentLocation);
}
于 2012-07-05T16:33:53.270 回答