編輯:找到了答案!雖然CAG確實讓我走上了正軌,所以我會獎勵他。儘管我提供了正確的答案。JavaFX Snake Thread.Sleep()不加載FXML
我正在使用Canvas在JavaFX中進行一場Snake遊戲。
我有一個while循環運行遊戲:
- 打印設置正確的垂直框細胞的 背景顏色網格的可視化表示。
- 等待輸入(的Thread.sleep(1000)。
- 產生下一個視覺效果。
的問題是,如果我使用了Thread.sleep(),我的畫布不加載所有的背後但是,遊戲仍然在運行,直到我撞到牆壁並死亡。
有沒有什麼我在這裏做錯了?是thread.sleep()暫停加載和顯示JavaFX節點的能力嗎?
Thread gameThread = new Thread() {
@Override
public synchronized void start() {
super.start();
printGridToGUI();
while (KEEP_PLAYING) {
generateNextGrid();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(SnakeGUIController.class.getName()).log(Level.SEVERE, null, ex);
}
Platform.runLater(() -> {
printGridToGUI();
});
}
/*Stop continuing to play. You either won or lost.*/
if (WON_GAME) {
System.out.println("Congratulations!");
} else {
System.out.println("You lose.");
}
}
};
gameThread.start();
其中printGrid()是:
/**
* Prints the grid, with chars in place of on and off areas.
*/
public void printGridToGUI() {
resetCanvas();
for (Coordinate c : coordinates) {
drawCell(c.row, c.col, true);
}
drawCell(food.row, food.col, true);
}
和resetCanvas是:
/**
* Clears the boolean array, setting all values to false. A quick way to
* wipe the grid.
*/
public final void resetCanvas() {
/*Lay out the grid on the canvas.*/
GraphicsContext gc = canvas.getGraphicsContext2D();
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
drawCell(row, col, false);
}
}
}
和drawCell是:
/**
* Draws a cell on the canvas at the specified row and col. The row, col
* coordinates are translated into x,y coordinates for the graphics context.
*
* @param row The row of the cell to paint.
* @param col The col of the cell to paint.
* @param cellON The state of the cell, if it is on or off.
*/
private void drawCell(int row, int col, boolean cellON) {
/*Translate the row, col value into an x-y cartesian coordinate.*/
int xCoord = 0 + col * CELL_SIZE;
int yCoord = 0 + row * CELL_SIZE;
/*Draw on the canvas.*/
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(xCoord, yCoord, CELL_SIZE, CELL_SIZE);
if (!cellON) {
gc.setFill(Color.WHITE);
int BORDER = 1;
gc.fillRect(xCoord + BORDER, yCoord + BORDER, CELL_SIZE - BORDER, CELL_SIZE - BORDER);
}
}
你究竟在哪裏使用'Thread.sleep()'?你能發佈一些代碼來支持你的問題嗎? – ItachiUchiha 2014-08-30 07:23:13
@IchichiUchiha已添加。 – 2014-08-30 07:57:42