Valhalla Legends Forums Archive | Java Programming | KeyListener - Reading Arrow Keys?

AuthorMessageTime
JoeTheOdd
I can't figure out how to get this to work. Anyone wanna give it a shot?

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyEvent.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyListener.html

[code]// Key listener
import java.awt.event.*;

// Window
import javax.swing.*;
import java.awt.*;

// Timer
import java.util.Timer;
import java.util.TimerTask;

public class Snake extends JFrame implements KeyListener
{
private static final int DIR_NULL  = 0; // Direction's for the snake to move
private static final int DIR_UP    = 1;
private static final int DIR_DOWN  = 2;
private static final int DIR_LEFT  = 3;
private static final int DIR_RIGHT = 4;

private static final int SIZE = 15; // Size of the snake

private Container c; // Container, marking the JFrame background
private Timer snakeMoveTimer = new Timer(); // Timer used to fire snake moving events

private int xPos = SIZE; // X coordinate of snake
private int yPos = SIZE; // Y coordinate of snake

private int direction = DIR_NULL; // direction snake is moving

private int xPosFood = 0; // X coordinate of food
private int yPosFood = 0; // Y coordinate of food

private int score = 0; // Score!


/**
* Program entry-point
* @param args Commandline arguments
*/
public static void main(String args[])
{
new Snake();
// calls class constructor
}

/**
* Class constructor
* Creates a new instance of Snake
*/
public Snake()
{
// Set up JFrame
super("Snake!");
this.setSize(800, 500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
c = getContentPane();
this.setBackground(Color.white);
this.setVisible(true);

// Add a key listener
this.addKeyListener(this);

// Create the task to move the snake with
snakeMoveTimer.schedule(new SnakeMoveTask(), 1000, 100);
}

/**
* Fired by keyListener
* @param e KeyEvent struct, telling us what happened in this event
* Used to tell the snake which direction to move
*/
    public void keyReleased(KeyEvent e)
    {
switch(e.getKeyCode())
{
case KeyEvent.VK_KP_UP:
this.direction = DIR_UP;
break;
case KeyEvent.VK_KP_DOWN:
this.direction = DIR_DOWN;
break;
case KeyEvent.VK_KP_RIGHT:
this.direction = DIR_LEFT;
break;
case KeyEvent.VK_KP_LEFT:
this.direction = DIR_RIGHT;
break;
default:
switch (e.getKeyChar())
{
case 'w': // up
this.direction = DIR_UP;
break;
case 's': // down
this.direction = DIR_DOWN;
break;
case 'a': // left
this.direction = DIR_LEFT;
break;
case 'd': // right
this.direction = DIR_RIGHT;
break;
}
break;
}
    }

/**
* Fired when run of SnakeMoveTask calls repaint
* Resonsible for moving the snake
*/
    public void paint(Graphics g)
    {
if((xPosFood == 0) || (yPosFood == 0))
{
// Draw food
g.setColor(Color.black);
xPosFood = (int)(Math.random() * 800 / SIZE) * SIZE;
yPosFood = (int)(Math.random() * 500 / SIZE) * SIZE;
g.fillRect(xPosFood, yPosFood, SIZE, SIZE);
}
int old_x = xPos, old_y = yPos;
switch (direction)
{
case DIR_UP:
yPos -= SIZE;
break;
case DIR_DOWN:
yPos += SIZE;
break;
case DIR_LEFT:
xPos -= SIZE;
break;
case DIR_RIGHT:
xPos += SIZE;
break;
}
if ((xPos == xPosFood) && (yPos == yPosFood))
{
g.setColor(Color.black);
g.clearRect(xPosFood, yPosFood, SIZE, SIZE);
xPosFood = (int)(Math.random() * 800 / SIZE) * SIZE;
yPosFood = (int)(Math.random() * 500 / SIZE) * SIZE;
g.fillRect(xPosFood, yPosFood, SIZE, SIZE);
score += 10;
}
g.setColor(Color.yellow);
g.clearRect(old_x, old_y, SIZE, SIZE);
g.fillRect(xPos, yPos, SIZE, SIZE);

// Border check
if ((xPos < 0) || (xPos > 800) || (yPos < 0) || (yPos > 500))
{
// Game over
xPos = SIZE;
yPos = SIZE;
direction = DIR_NULL;
g.clearRect(0, 0, 800, 500);
JOptionPane.showMessageDialog(null, "Game over!\n Your score: " + score + ".");
score = 0;
}
}

class SnakeMoveTask extends TimerTask
{
/**
* Called by snakeMoveTimer when it fires
* Responsible for calling repaint, to fire paint of Snake
*/
public void run()
{
repaint();
}
}


// A few stubs
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}

}[/code]
March 13, 2006, 3:46 PM
kamakazie
What is the problem?
March 13, 2006, 4:25 PM
JoeTheOdd
Arrow keys won't control the movement of the snake. The WSAD keys will, though, so I know that my KeyListener is set up and everything.

PS -
I'm in class right now. ^_^
March 13, 2006, 6:20 PM
kamakazie
[quote author=Joe link=topic=14501.msg148279#msg148279 date=1142274010]
Arrow keys won't control the movement of the snake. The WSAD keys will, though, so I know that my KeyListener is set up and everything.

PS -
I'm in class right now. ^_^
[/quote]

VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT.

Really simple problem to solve. Just put some println() statements in keyReleased() to determine what keys are being pressed. Then compare with what you're switching against and you should be able to determine the problem. In this case, you're comparing against the wrong constants.
March 13, 2006, 8:32 PM
JoeTheOdd
Hi. I love you.

[code] /**
* Fired by keyListener
*
* @param e
*            KeyEvent struct, telling us what happened in this event Used
*            to tell the snake which direction to move
*/
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
this.direction = DIR_UP;
break;
case KeyEvent.VK_DOWN:
this.direction = DIR_DOWN;
break;
case KeyEvent.VK_RIGHT:
this.direction = DIR_RIGHT;
break;
case KeyEvent.VK_LEFT:
this.direction = DIR_LEFT;
break;
default:
switch (e.getKeyChar())
{
case 'w': // up
this.direction = DIR_UP;
break;
case 's': // down
this.direction = DIR_DOWN;
break;
case 'a': // left
this.direction = DIR_LEFT;
break;
case 'd': // right
this.direction = DIR_RIGHT;
break;
}
break;
}
}[/code]
March 14, 2006, 2:16 AM

Search