2017-12-03 338 views
1

我正在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); 

    } 
    }); 

什麼是做到這一點的最好辦法?

+0

Swing是事件驅動的,這意味着你將無法使用'System.in'得到輸入,這不是它應該使用[Key Bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer

回答

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

由於[Key Bindings API](https:// docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)解決了與'KeyListener'相關的問題,作爲一般規則,不建議使用'KeyListener' – MadProgrammer