Hello all. I have a problem that seems like it should be relatively simple to fix but I have been scouring the internet and can't find an answer =(
I am trying to add a keylistener to this code, but it doesn't recognize the method addKeyListener(this); I am working with kareltherobot so that's where all of the methods like pickBeeper() and facingNorth() etc. are from. Any help would be appreciated.
import java.awt.event.*;
import kareltherobot.*;
public class PacMan extends Robot implements KeyListener, Directions
{
public PacMan(int street, int avenue, Direction direction, int beepers)
{
super(street, avenue, direction, beepers);
addKeyListener(this); //this is the part that doesn't work
}
/**Method definitions for the KeyListener interface (there aren't any errors in this part)
**/
public void keyTyped(KeyEvent evt) {
char key = evt.getKeyChar();
if (key == 'w') {
while(!facingNorth())
turnLeft();
if(frontIsClear())
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'a') {
while(!facingWest())
turnLeft();
while(nextToABeeper())
pickBeeper();
}
if (key == 's') {
while(!facingSouth())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'd') {
while(!facingEast())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
}
public void keyPressed(KeyEvent evt) {
char key = evt.getKeyChar();
if (key == 'w') {
while(!facingNorth())
turnLeft();
if(frontIsClear())
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'a') {
while(!facingWest())
turnLeft();
while(nextToABeeper())
pickBeeper();
}
if (key == 's') {
while(!facingSouth())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'd') {
while(!facingEast())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
}
public void keyReleased(KeyEvent evt) {
char key = evt.getKeyChar();
if (key == 'w') {
while(!facingNorth())
turnLeft();
if(frontIsClear())
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'a') {
while(!facingWest())
turnLeft();
while(nextToABeeper())
pickBeeper();
}
if (key == 's') {
while(!facingSouth())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
if (key == 'd') {
while(!facingEast())
turnLeft();
move();
while(nextToABeeper())
pickBeeper();
}
}
}