如何在 JavaFX 中的两个用户界面事件更新之间创建延迟?

问题描述 投票:0回答:1

我一直在尝试使用 JavaFX 编写俄罗斯方块代码,虽然游戏逻辑有效,但我一直在解决一个问题。 对于这个项目,我使用矩形对块进行建模;我使用 setLayoutX 和 setLayoutY 方法移动这些矩形形状,并使用 scene.setOnKeyPressed 方法获取用户键盘输入。我正在使用 AnimationTimer 来运行游戏循环。到目前为止,一切都很好,但是…… 众所周知,在俄罗斯方块游戏中,当一行被填满时,该行就会被消除,并且该行上方的所有方块都会向下移动。我想在删除填充行之前突出显示它。 我想改变填充行中的块的颜色,然后延迟执行半秒,然后才消除填充行中的块。 我不知道如何实现延迟。 我已经尝试过(a)创建新线程并使用 Platform.runLater,(b)任务,(c)while 循环,但都不起作用。我将在这里留下我正在处理的部分代码:

/* some code above */
if(isFilledRow) {
    for(int j=0;j<nCol;j++) {
        for(int k=0;k<blocks.size();k++) {
            BlockUnit bu=blocks.get(k);
            if(bu.getY()==i && bu.getX()==j) {
                bu.getShape().setFill(Color.BROWN);
            }
        }
    }
        /* the delay should happen here */
    for(int j=0;j<nCol;j++) {
        for(int k=0;k<blocks.size();k++) {
            BlockUnit bu=blocks.get(k);
            if(bu.getY()==i && bu.getX()==j) {
                blocks.remove(bu);
                root.getChildren().remove(bu.getShape());
            }
        }
    }
}
/* some code below */
java multithreading javafx tetris
1个回答
0
投票

我认为你可以使用javafx的时间轴来实现这一点。

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;

/* After highlighting the blocks.. you can add the below code to execute after a delay */
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(500),
        e -> {
            for (int j = 0; j < nCol; j++) {
                for (int k = 0; k < blocks.size(); k++) {
                    BlockUnit bu = blocks.get(k);
                    if (bu.getY() == i && bu.getX() == j) {
                        blocks.remove(bu);
                        root.getChildren().remove(bu.getShape());
                    }
                }
            }
        }));
timeline.play();
© www.soinside.com 2019 - 2024. All rights reserved.