尝试在棋盘式棋盘上移动我的角色穿过终端。我确信有一种更优雅的方式来编写这段代码,但我对如何操作有一个大脑屁。
// move your character.
public void moveYou(String wasd, You person) {
if (wasd.equals("w")) {
// swaps ground in front of you with you.
ground[person.getX()][person.getY()] = ground[person.getX() - 1][person.getY()];
// replaces you with ground above you.
ground[person.getX() - 1][person.getY()] = person;
person.setXandY(person.getX() - 1, person.getY());
person.setDir("[ ^ ]");
} else if (wasd.equals("s")) {
ground[person.getX()][person.getY()] = ground[person.getX() + 1][person.getY()];
ground[person.getX() + 1][person.getY()] = person;
person.setXandY(person.getX() + 1, person.getY());
person.setDir("[ v ]");
} else if (wasd.equals("a")) {
ground[person.getX()][person.getY()] = ground[person.getX()][person.getY() - 1];
ground[person.getX()][person.getY() - 1] = person;
person.setXandY(person.getX(), person.getY() - 1);
person.setDir("[ < ]");
} else if (wasd.equals("d")) {
ground[person.getX()][person.getY()] = ground[person.getX()][person.getY() + 1];
ground[person.getX()][person.getY() + 1] = person;
person.setXandY(person.getX(), person.getY() + 1);
person.setDir("[ > ]");
}
printMap();
}
答案 0 :(得分:4)
通过Enum
public enum Move {
UP("w", "^", new CoordinateChange(1, 0)),
DOWN(...),
LEFT(...),
RIGHT(...);
private final String key;
private final String direction;
private final coordinateChange;
private CoordinateChange {
private int x;
private int y;
// getter, setter, constructor
}
public static Move of(String keyboard) {
// COnvert key board `w`,`s`, `a`, `d` to specific Move
}
}
现在将您的&#34;转换为&#34;像这样的行动:
if (wasd.equals("w")) {
// swaps ground in front of you with you.
ground[person.getX()][person.getY()] = ground[person.getX() - 1][person.getY()];
// replaces you with ground above you.
ground[person.getX() - 1][person.getY()] = person;
person.setXandY(person.getX() - 1, person.getY());
person.setDir("[ ^ ]");
}
调用以下方法:
public void changeCoordination(String wasd)
Move move = Move.of(wasd);
// ground[person.getX()][person.getY()] = ground[person.getX() - 1][person.getY()];
// Don't know what you're trying to do here but hope you got the idea, just place the coordinate change to `Move`
ground[person.getX() + move.getCoordinateChange().getX()][person.getY() + move.getCoordinateChange().getY()] = person;
person.setDir(move.getDirection());
}
你不再拥有if / else了。只需编写该函数并传递wasd
值。