1
\$\begingroup\$

I want to write a Snake game in Java. How can I continuously monitor input and if user pressed W set variable Char lastDirection = 'w'; //hence, Direction.UP?

I know about the Scanner method: Scanner scan= new Scanner(System.in);... But then user would have to hit enter each time he presses the button. Document Listener (Swing) seems better, but then I would have a long string of user input saved somewhere that I don't need. What is the right method for listening to keyboard and remembering the last character?

\$\endgroup\$
3
\$\begingroup\$

You need a Listener indeed.

Then you can store the pressed keys in an array, and manage it like this.

bool keyPressed[256];
// Do not forget to initialize all to false if java does not do it;

onKeyPressed(event e) {
    keyPressed[e.keyCode] = true;
}

onKeyReleased(event e) {
    keyPressed[e.keyCode] = false;
}

// in game loop you can then check like this
if (keyPressed[keyCode("w")])
    moveUp();

Note that all of this is pseudo-code.

EDIT :

The previous code is not really adapted for snake as the snake is supposed to keep moving on even if the key has been released.

Using booleans to keep track of the current direction as stated in OP's own answer is indeed the best solution I can think of.

\$\endgroup\$
  • \$\begingroup\$ Does it require a separate thread? Or it runs in the same thread as the JFrame component? \$\endgroup\$ – Stepan Jan 12 '17 at 15:09
  • \$\begingroup\$ By default I think it executes on the same thread. \$\endgroup\$ – realUser404 Jan 12 '17 at 15:11
  • 1
    \$\begingroup\$ You can find exhaustive documentation about events on oracle website docs.oracle.com/javase/tutorial/uiswing/events/index.html \$\endgroup\$ – realUser404 Jan 12 '17 at 15:14
0
\$\begingroup\$

I've find this Snake game implementation: http://zetcode.com/tutorials/javagamestutorial/snake/

It uses extends KeyAdapter.

private class TAdapter extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
            leftDirection = true;
            upDirection = false;
            downDirection = false;
        }

        if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
            rightDirection = true;
            upDirection = false;
            downDirection = false;
        }

        if ((key == KeyEvent.VK_UP) && (!downDirection)) {
            upDirection = true;
            rightDirection = false;
            leftDirection = false;
        }

        if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
            downDirection = true;
            rightDirection = false;
            leftDirection = false;
        }
    }
}

The use of four boolean flags seems dated and enum seems better for this purpose, but KeyAdapter fits the task well.

\$\endgroup\$
  • \$\begingroup\$ I guess using the 4 boolean flags make sense in a game like snake, as the snake is supposed to keep moving even if the key has been released. My current answer is a bit off in this aspect \$\endgroup\$ – realUser404 Jan 12 '17 at 16:29
0
\$\begingroup\$

In Swing, there are many, many different kinds of event listeners. In particular, KeyListener will do the job in this situation. Oracle has a great tutorial about event handling so I won't go into any details here.

Do you really need to remember the last key pressed? It seems to me that it would be more useful to keep track of the current direction the snake is moving and change direction as appropriate. For example, if the snake is moving up and the user presses down, you do not care about the key pressed. You only care if the user presses left or right.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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