我正在尝试使用JavaFX编写2048游戏,但遇到了问题。
@Override
public void start(Stage primaryStage){
primaryStage.setResizable(false);
Scene scene = new Scene(firstContent());
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent e){
KeyCode key = e.getCode();
if((key.equals(KeyCode.UP))){
System.out.println("recieved UP");
Scene scene = new Scene(createContent());
primaryStage.setScene(scene);
primaryStage.show();
} else if(key.equals(KeyCode.DOWN)){
System.out.println("recieved DOWN");
}
}
});
}
因此,我在这里打开用firstContent初始化的窗口(基本上,它创建一个空瓦片数组,并用2或4个随机填充其中的两个),显示它并开始监听按键。想法是使每个箭头键(上左下右)具有相应的行为,这将相应地移动磁贴。这是通过以下createContent()方法完成的:
public Parent createContent(){
String c = "";
List<Integer> known = new ArrayList<Integer>();
Pane root = new Pane();
root.setPrefSize(740, 700);
Random rand = new Random();
int pos1 = rand.nextInt(15);
if(tiles.get(pos1) != new Tile("")){
known.add(pos1);
pos1 = rand.nextInt(15);
if(known.contains(pos1)){
known.add(pos1);
pos1 = rand.nextInt(15);
}
}
for(int i = 0; i < NB_TILES; i++){
tiles.add(new Tile(c));
}
tiles.set(pos1, new Tile("2048"));
for(int i = 0; i < tiles.size(); i++){
// boring stuff to set the tile display to the right size
}
return root;
}
现在是问题所在:当应用程序运行时,如果我按下向下箭头,我确实会按我预期的次数在终端上收到“收到的DOWN”文本。但是,如果我按下向上箭头,则该应用程序只会收到一次,并且该应用程序似乎被冻结(这意味着如果我再次按下,则什么也不会发生)。 您可能会猜到,我希望能够为每次按键调用我的方法,以便能够移动我的图块并最终将它们组合在一起以得到可播放的2048版本。有人知道我的应用为什么被冻结了吗? >
如果需要,我可以提供其他代码,但我认为我提供了必要的代码。只是知道firstContent()基本上与createContent相同,只是它会生成两个随机数以获取游戏的第一个图块。
预先感谢您的帮助。