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;
}
}
});
添加回答
举报