编辑:找到了答案!虽然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