我遇到鼠标事件的问题。有些代码似乎在其他代码之前完成。我用蒙特卡罗模拟写了一个GO游戏。
holder.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(mouseX > 0 && mouseY > 0 && player1){
boolean[][] availableFields = GameBoard.checkAvailableFields(GameBoard.stoneColor.WHITE);
if (availableFields[arrayX][arrayY] == true) {
System.out.println("White rock on " + arrayX + ", " + arrayY);
putRock(arrayX, arrayY, GameBoard.stoneColor.WHITE);
gameBoard.setField(arrayX, arrayY, GameBoard.stoneColor.WHITE);
player1 = false;
System.out.println("Rock put");
} else{
System.out.println("no put");
}
gameBoard.printFields();
MonteCarlo montecarlo = new MonteCarlo(gameBoard);
int field = montecarlo.nextMove();
int x = field % 5;
int y = field / 5;
arrayToMouseXY(x, y);
arrayX = x;
arrayY = y;
System.out.println("Black rock on " + field + ": " + arrayX + ", " + arrayY);
putRock(arrayX, arrayY, GameBoard.stoneColor.BLACK);
gameBoard.setField(arrayX, arrayY, GameBoard.stoneColor.BLACK);
player1 = true;
gameBoard.printFields();
}
}
});
函数putRock(int x, int y, GameBoard.stoneColor color)
在屏幕上绘制图像。问题是在计算整个蒙特卡罗模拟之前,第一块岩石不会被涂漆。我怎么能阻止这个?
答案 0 :(得分:2)
您可以尝试在后台线程上运行模拟,并在后台线程完成后立即使用模拟结果更新GUI。
示例:强>
// Task for your simulation
Task<Integer> task = new Task<Integer>(){
@Override
protected Integer call() throws Exception {
MonteCarlo montecarlo = new MonteCarlo(gameBoard);
return montecarlo.nextMove();
}
};
// If you want to disable the GUI while your simulation runs (root is the root Node of your Scene graph)
// root.setDisable(true);
// When the task finished, update the GUI with the step
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
int field = task.getValue();
int x = field % 5;
int y = field / 5;
arrayToMouseXY(x, y);
arrayX = x;
arrayY = y;
System.out.println("Black rock on " + field + ": " + arrayX + ", " + arrayY);
putRock(arrayX, arrayY, GameBoard.stoneColor.BLACK);
gameBoard.setField(arrayX, arrayY, GameBoard.stoneColor.BLACK);
player1 = true;
gameBoard.printFields();
// "release" the GUI
// root.setDisable(false);
}
});
// Start the thread
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();