java swing keylistener 2d boulderdash

前端 未结 1 2017
走了就别回头了
走了就别回头了 2020-12-22 05:40

I\'m looking to make a boulderdash problem but first i\'m just trying to get the player to move around, he\'s allowed to move to any space that is not a rock(1) or a wall(0)

1条回答
  •  生来不讨喜
    2020-12-22 06:11

    First of all never use the numeric constants instead of the field constants,

    public void keyPressed(KeyEvent k) {
        int keyCode = k.getKeyCode();           
        if(keyCode == KeyEvent.VK_R) // not keyCode == 82
    }
    

    What would be a better approach is to use an InputMap and ActionMap, which I think is also called "Key Binding" (as suggested by MadProgrammer). The input map maps a key stroke to an action name, and the action map maps the action name to the action you want to take.

    Replace your line (and the whole KeyListener extended class)

    this.addKeyListener(new MyKeyListener());
    

    with something like

    this.getInputMap().put(KeyStroke.getKeyStroke("control L"), "link");
    

    where you need to refer to the documentation of KeyStroke.getKeyStroke to modify the specified key stroke to your needs. In my example "link" is the name of the action to be taken when CTRL+L is pressed. Now we need to specify what "link does"

    this.getActionMap().put("link", new LinkAction());
    

    where LinkAction is my class extending AbstractAction which in your case should includes your methods such as levelReaderObject.setCurrentLevel(presentLevel);.

    Note that you don't need to create an Action for every key. For movement (up, down, left, right) I would bind all of the movement buttons to different action names ("move up" etc.), but then map all the action names to the same action and let the methods inside that action do the work:

    this.getActionMap().put("move up", new MoveAction(0));
    this.getActionMap().put("move down", new MoveAction(1));
    this.getActionMap().put("move right", new MoveAction(2));
    this.getActionMap().put("move left", new MoveAction(3));
    

    with

    class MoveAction extends AbstractAction {
    
        int direction;
    
        public MoveAction (int direction) {
    
            this.direction = direction;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
            switch(direction) // perform the action according to the direction
        }
    }
    

    Please note that my suggestion to grouping the movement actions together is a design decision and you should decide how to structure the bindings yourself (you could use one action for everything or one action for each).

    0 讨论(0)
提交回复
热议问题