I am making a snake game, and I want my snake to be moving continuously once a key is pressed. So, I press the down key, and it keeps moving even if the key is released. Right now, it just moves while the key is being held down.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
mySegment[0].moveSouth();
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
mySegment[0].moveNorth();
repaint();
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
mySegment[0].moveWest();
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
mySegment[0].moveEast();
repaint();
}
for (int a = 0; a < 10; a++) {
if (myFruit[a].distance (mySegment[0].getX(), mySegment[0].getY())
<= 20) {
myFruit[a].hide();
}
}
The "mySegment [0]" is the snake, and the "moveSouth" or whatever direction just moves it 5 pixels in that directin
Use a "game loop" to drive the animation. Since this looks to be possibly a Swing or AWT GUI, then your best bet is to use a Swing Timer -- please check out the tutorial. The gist is that within the Timer's ActionListener you increment the position of the snake, changing its direction depending on the state of your key press.
I would use an enum to indicate Direction {UP, DOWN, LEFT, RIGHT}:
AND then a
Map<Direction, Boolean>
to indicate which direction to head:Elsewhere you would initialize the Map to hold false in all values:
Then change the state of the items in the Map within your code for listening to key presses and releases -- call
map.put(Direction.UP, true)
for instance when the up key is pressed, and likewise callmap.put(Direction.UP, false)
when it has been released, same for the other keys. Note that if yours is a Swing application, I'd use Key Bindings and not a KeyListener to do this. In the listener, I'd then callrepaint()
on the GUI.Within the Swing Timer, iterate through the Map, setting the direction based on the state of the Map.
class fields:
Within the ActionListener
For example (not a snake but a ball -- I'll leave the Snake to you)
If you want to keep the snake moving you need some kind of game-loop (as mentioned before). The easiest way is having a single field containing the current direction, and set it based on the input. So here are a few methods/classes you could use to set the correct direction/position
The Direction Enum
The method to set the current direction. (This assumes there is a field named 'currentDirection' which contains an enum (Direction) representing the current direction)
This is somewhere in your game loop (either an timer, or a while loop including a 'sleep' call to prevent CPU hugging)
And of course instead of calling 'mySegment[0].moveNorth();' or someting equalivant in the actionHandlers for the keyEvents, you should only call 'setDirection();' to make the snake move.
I hope this helped you out.