2 回答

TA貢獻1852條經驗 獲得超7個贊
我發現您的代碼與教程中的代碼不同。
if (!moved)
return;
switch (event.getCode()) {
.
.
.
}
moved = false;
在您的代碼中,缺少 if(!moved) 之后的 return 語句。我試圖將它添加到我的代碼中,然后它對我有用。
希望這可以解決您的問題。干杯馬耳他

TA貢獻1893條經驗 獲得超10個贊
問題是每次KeyFrame觸發時,您都會重置moved標志。這需要用戶在幀之間觸發至少 2 個KEY_PRESSED事件才能獲得改變的方向。
假設您想阻止用戶在第一幀之前改變方向,您應該刪除if條件中的否定。(根據您嘗試使用標志實現的目標,您可能需要不同的修復)。
scene.setOnKeyPressed(event -> {
if (moved) {
switch (event.getCode()) {
case W:
if (direction != Direction.DOWN)
direction = Direction.UP;
break;
case S:
if (direction != Direction.UP)
direction = Direction.DOWN;
break;
case A:
if (direction != Direction.RIGHT)
direction = Direction.LEFT;
break;
case D:
if (direction != Direction.LEFT)
direction = Direction.RIGHT;
break;
default:
break;
}
}
});
此外,您可以通過使用 aMap并向Direction枚舉添加屬性來改進代碼的一些方面。
public enum Direction {
UP(0, -1), RIGHT(1, 0), DOWN(0, 1), LEFT(-1, 0);
private final int dx;
private final int dy;
private Direction(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
/**
* Tests, if 2 directions are parallel (i.e. both either on the x or the y axis).<br>
* Note: Depends on the order of the enum constants
* @param other the direction to compare with
* @return true, if the directions are parallel, false otherwise
*/
public boolean isParallel(Direction other) {
return ((ordinal() - other.ordinal()) & 1) == 0;
}
}
在里面KeyFrame
...
double tailX = tail.getTranslateX();
double tailY = tail.getTranslateY();
Node head = snake.get(0);
tail.setTranslateX(head.getTranslateX() + BLOCK_SIZE * direction.dx);
tail.setTranslateY(head.getTranslateY() + BLOCK_SIZE * direction.dy);
moved = true;
...
final Map<KeyCode, Direction> keyMapping = new EnumMap<>(KeyCode.class);
keyMapping.put(KeyCode.W, Direction.UP);
keyMapping.put(KeyCode.S, Direction.DOWN);
keyMapping.put(KeyCode.A, Direction.LEFT);
keyMapping.put(KeyCode.D, Direction.RIGHT);
Scene scene = new Scene(createContent());
scene.setOnKeyPressed(event -> {
if (moved) {
Direction newDirection = keyMapping.get(event.getCode());
if (newDirection != null && !direction.isParallel(newDirection)) {
direction = newDirection;
}
}
});
添加回答
舉報