我正在Java中做蛇遊戲,需要使用用戶擊鍵來控制移動的方向。這可能通過switch
聲明嗎?我最初使用Scanner s = new Scanner(System.in)
來允許用戶輸入'u','d'等來移動蛇,但我想用鍵盤箭頭代替。Java開關與用戶輸入擊鍵
這是我現在所擁有的:
public void controlSnake(){
Scanner s = new Scanner(System.in);
String inputString = s.next();
switch (inputString) {
case "u":
case "U":
snake.changeDirection(Point.NORTH);
break;
case "d":
case "D":
snake.changeDirection(Point.SOUTH);
break;
case "r":
case "R":
snake.changeDirection(Point.EAST);
break;
case "l":
case "L":
snake.changeDirection(Point.WEST);
break;
}
}
我要插入這樣的事情,但不知道如何:
map1.put(KeyStroke.getKeyStroke("LEFT"), "moveLeft");
getActionMap().put("moveLeft", new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
snake.changeDirection(Point.WEST);
}
});
什麼是做到這一點的最好辦法?
Swing是事件驅動的,這意味着你將無法使用'System.in'得到輸入,這不是它應該使用[Key Bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer