Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
3  
So you've succeeded in setting some variables based on the keys pressed. Then what do you do with all those variables? –  200_success Apr 15 '14 at 7:42

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.