首页 > 解决方案 > 在 Connect4 游戏 Javafx 中为彩色光盘创建掉落效果

问题描述

我正在尝试为 Connect4 游戏创建 JavaFx 应用程序。我需要一些建议来显示彩色圆盘如何落在每列中,在每个白色部分显示彩色圆盘以快速跨越然后进一步下降。

我创建了 7 列 VBox,每列内有 6 个圆圈。然后所有列都嵌入到一个巨大的 HBox 中。

在此处输入图像描述

所以当玩家点击一列时,圆盘会从顶部掉下来。为了显示光盘的掉落,我尝试了:

protected boolean fillColumnWithPlayerColor(VBox col) {

    ObservableList<Node> discs = col.getChildren();

    for (int i = discs.size() - 1; i >= 0; i--) {
        Circle circle = (Circle) discs.get(i);

        if (circle.getFill().equals(Color.WHITE)) {
            if (i > 0) {
                for (int j = 0; j < i; j++) {
                    Circle prevCircle = (Circle) discs.get(j);//Assigning the current disc to player color
                    prevCircle.setFill(playerColor); //playerColor -> Color chosen by player
                    try {
                        Thread.sleep(800); //Delay for display
                        prevCircle.setFill(Color.WHITE); //Setting the color back to White
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
            circle.setFill(playerColor);
            return true;

        }

    }

    return false;

}

但无论延迟持续时间是多少(Thread.sleep),光盘只会在总持续时间后显示在其最终位置,而不是“掉落”效果。

有什么建议么 ?

标签: javajavafx-8

解决方案


你不应该在 JavaFX 中使用 Thread.sleep()。您正在为您的圈子定义一条路径,因此您应该使用 Path Transition 包。

 import javafx.animation.transition.*;
 ...
      Path path = new Path();
      path.getElements().add(new MoveTo(0f, 50f));
      pathTransition.setDuration(Duration.millis(800));
      pathTransition.setNode(circle);
      pathTransition.setPath(path);
      pathTransition.play();

如需更多帮助,请参阅文档


推荐阅读