我用Java制作蛇游戏,需要使用用户按键来控制移动方向。这可以通过switch
声明吗?我最初使用Scanner s = new Scanner(System.in)
允许用户键入' u' d'等等来移动蛇,但我想使用键盘箭头代替。
这就是我现在所拥有的:
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);
}
});
实现这一目标的最佳方法是什么?
答案 0 :(得分:4)
可以使用来自JDK 7的String
的switch语句:
似乎你正在开发一款控制台游戏。如果您使用的是Swing,则可以考虑使用InputMap
和ActionMap
代替:
答案 1 :(得分:1)
我看到你正在使用Swing。您可以使用KeyListener接口。这样的事情。
yourButton.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
snake.changeDirection(Point.NORTH);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
snake.changeDirection(Point.SOUTH);
}
//Likewise for left and right arrows
}
@Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});