开发者

How should i program mouse/key input in an advanced java game?

I am a self taught programmer, so I do not know the proper ways to do things. I have made simple games like asteroids a开发者_如何转开发nd snake, but in those games, you can easily modify the variables within the keyevent functions. Here is how I did it in my simple Asteroids game:

/*
 * key listener events
 */
public void keyReleased(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = false;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = false;
            break;

        case KeyEvent.VK_UP:
            accel = false;
            break;

        case KeyEvent.VK_1:
            cls = true;
            break;
        case KeyEvent.VK_ENTER:
            break;
        case KeyEvent.VK_SPACE:
            fire = false;
    }
}
public void keyTyped(KeyEvent K){}
public void keyPressed(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = true;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = true;
            break;

        case KeyEvent.VK_UP:
            accel = true;
            break;

        case KeyEvent.VK_1:
            cls = false;
            break;
        case KeyEvent.VK_ENTER:
            clearAllBullets();
            break;
        case KeyEvent.VK_SPACE:
            fire = true;
    }
}

If I were to make a more advanced game (with a main menu, options, main game, etc.) How should I do the key/mouse input?

Also, if I were to go into the single-player, should I put all of the gameplay code into one class? Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?

Thank you for your time!

P.S. Any links or source is extremely appreciated. :D


"Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?"

Yes, there is way to encapsulate all event-based behaviours- http://en.wikipedia.org/wiki/Mediator_pattern but, it can make yor code very complicated, so firstly try to implement your game in more "normal" way.

Anyway - you will need other classes, to present domain model of your game (Player, Gameboard, UserInterfaces etc...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜