TaskScheduler无法添加节点

时间:2019-06-07 18:58:51

标签: java javafx concurrency

我正在尝试通过我的ScheduledService实现来制作蛇形游戏,并通过移动矩形来模仿运动。

问题是ScheduledService似乎在添加新节点时遇到问题。为了检查即时消息是否正确,我尝试在运行时添加巨大的矩形,并且整个窗口都没有刷新(当我删除有关此矩形的线时,蛇仍在移动,但看不到食物)。如何确保该任务将节点添加到场景中?

我尝试了没有并发的方法,并且一切正常。

public class GameLoop extends ScheduledService {
    GameScene scene;
    Square first;
    Direction direction;


    GameLoop(GameScene scene){
        this.scene=scene;
        setPeriod(new Duration(150));
    }


    @Override
    protected Task createTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                if(!gameOver()){
                    if (scene.getSnake().move(direction, scene.getFood())) {
                        scene.placeFood();
                        return null;
                    }
                }else{
                    System.out.println("game over");
                    cancel(false);
                }
                return null;
            }
        };
    }


    public void setDirection(Direction direction){
        this.direction=direction;
    }
}
public class GameScene extends Scene {
    private Snake snake;
    private Square food;
    private Pane pane;
    int i=0;
    //======================================================================


    GameScene(double x, double y, Pane pane){
        super(pane, x, y);
        this.pane=pane;
        pane.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null)));
        snake=new Snake(x, y);
        placeFood();
        pane.getChildren().add(snake);

    }

    //=====================================================================

    public void placeFood(){
        //If i add this the whole window freezes
        /*
        if(i>0) {
            pane.getChildren().add(new Rectangle(100, 100, Color.BLUE));
        }
        */
        food=new Square(10, 10, Color.RED);
        System.out.println(food.hashCode());
        System.out.println("Setting new Food");
        do {
            food.setX(DataViability.roundTen(Math.random() *this.getWidth() - 10));
            food.setY(DataViability.roundTen(Math.random()*this.getHeight() - 10));
        }while(snake.onSnake(food, true));
        System.out.println("Broke out");
        pane.getChildren().add(food);
        // This sout doesnt appear on the console when adding food in a GameLoop
        System.out.println("Set food at : " + food.getX() + " " + food.getY());
        i++;
    }

0 个答案:

没有答案