简体   繁体   English

具有用户输入击键的Java Switch

[英]Java Switch with user input keystrokes

I'm making a snake game in Java and need to use user keystrokes to control the direction of the movement. 我正在用Java制作蛇类游戏,需要使用用户击键来控制运动的方向。 Is this possible through a switch statement? 通过switch语句可以做到吗? I was originally using a Scanner s = new Scanner(System.in) to allow user to type 'u','d', etc. to move snake, but I would like to use the keyboard arrows instead. 我最初使用的是Scanner s = new Scanner(System.in) ,允许用户键入'u','d'等移动蛇,但是我想使用键盘箭头代替。

Here is what I have right now: 这是我现在所拥有的:

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;
    } 

}

I was going to insert something like this, but not sure how to: 我打算插入类似的内容,但不确定如何:

     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);

     }
     });

What would be the best way to accomplish this? 做到这一点的最佳方法是什么?

It is possible to use switch statement with String from JDK 7: 可以在JDK 7中将switch语句与String一起使用:

Strings in switch Statements switch语句中的字符串

And seems you are developing a console game. 看来您正在开发主机游戏。 If you are using Swing, you can consider using InputMap together with ActionMap instead: 如果使用的是Swing,则可以考虑同时使用InputMapActionMap

How to Use Key Bindings 如何使用键绑定

I see you are using Swing. 我看到您正在使用Swing。 You can make use of KeyListener interface. 您可以使用KeyListener接口。 Something like this. 这样的事情。

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.
            }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM