编辑:找到答案!虽然CAG确实让我走上了正确的道路,所以我会奖励他。不过,正确的答案是由我提供的。
我正在用画布在JavaFX中制作一个Snake游戏。
我让游戏在while循环中运行:
-
通过设置
正确VBox单元格的背景色。
-
等待输入(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);
}
}