我的作业需要帮助。 作业是编写递归方法,解决每个简单的级别 来自游戏“推箱子”。它应该使用Cloneable接口和hashSets来完成。 这就是我问这个的原因。我已经在我的代码中编写了递归方法,但它总是让我得到一个StackoverflowError。
我希望你能帮助我!
import java.util.HashSet;
public class Solver implements Cloneable {
HashSet<Level> fieldSet;
public Solver () {
fieldSet = new HashSet<Level>();
}
public final static char WALL = '#';
public final static char PLAYER = '@';
public final static char GOAL = '.';
public final static char CHEST = '$';
public final static char CHESTONGOAL = '*';
public final static char PLAYERONGOAL = '+';
public final static char FLOOR = ' ';
public String solve (Level l) {
Level fieldUp = l.clone();
Player playerUp = fieldUp.getPlayer();
playerUp.move(0, -1);
if (this.fieldSet.add(fieldUp)) {
if (!fieldUp.isCompleted()) {
return "up, " + this.solve(fieldUp);
} else {
return "up.";
}
}
Level fieldRight = l.clone();
Player playerRight = fieldRight.getPlayer();
playerRight.move(1, 0);
if (this.fieldSet.add(fieldRight)) {
if (!fieldRight.isCompleted()) {
return "right, " + this.solve(fieldRight);
} else {
return "right.";
}
}
Level fieldDown = l.clone();
Player playerDown = fieldDown.getPlayer();
playerDown.move(0, 1);
if (this.fieldSet.add(fieldDown)) {
if (!fieldDown.isCompleted()) {
return "down, " + this.solve(fieldDown);
} else {
return "down.";
}
}
Level fieldLeft = l.clone();
Player playerLeft = fieldLeft.getPlayer();
playerLeft.move(-1, 0);
if (this.fieldSet.add(fieldLeft)) {
if (!fieldLeft.isCompleted()) {
return "left, " + this.solve(fieldLeft);
} else {
return "left.";
}
}
return "";
}
}