2
\$\begingroup\$

This is how I read the keyboard in my game:

    @Override
public void keyPressed(KeyEvent key) {
    keypressed=true;

    if (key.getKeyCode() == KeyEvent.VK_UP) {
        keyup=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_DOWN) {
        keydown=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_ENTER) {
        keyenter=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_ESCAPE) {
        keyesc=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_W) {
        keyw=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_S) {
        keys=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_A) {
        keya=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_D) {
        keyd=true;
    }  
}

Is there a more efficient, simpler, or neater way to do this?

\$\endgroup\$
1
  • 3
    \$\begingroup\$ So you've succeeded in setting some variables based on the keys pressed. Then what do you do with all those variables? \$\endgroup\$ Commented Apr 15, 2014 at 7:42

1 Answer 1

5
\$\begingroup\$

Yes there is. As KeyEvent is an enumeration type, you can instead use a switch-statement:

char key;
boolean isSpecialKey = false;
SpecialKey specialKeyValue;
switch(key.getKeyCode()){
    case KeyEvent.VK_UP:
       key = '';
       isSpecialkey = true;
       specialKeyValue = SpecialKey.ARROW_UP;
       break;
    case KeyEvent.VK_W:
       key = 'w';
       break;
    //Continue...
}

I took the liberty of creating a new SpecialKey enum that is supposed to handle special keys when pressed. For these, there is also the isSpecialKey flag. You simply wouldn't create a case for Keys that you don't handle. Instead, do nothing in the default case.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.