Write a program that lets the user to move Karel around with arrow keys. Karel should start in the top-left corner of the screen and move exactly 100 pixels in the direction specified. (Hint: make sure to click on the program window after starting the program to let it start receiving keyboard events).

Note that because you are not restricting Karel to the screen, Karel is free to move off-screen.

Here is a Karel to help you out. You should save this Karel as karel.png into your Eclipse project folder.

Solution

/**
 * Class: KeyboardKarel
 * -----------------
 * Karel moves around an infinite world.
 */
public class KeyboardKarel extends GraphicsProgram {

	/**
	 * Width and height of application window, in pixels.
	 * These should be used when setting up the initial size of the game,
	 * but in later calculations you should use getWidth() and getHeight()
	 * rather than these constants for accurate size information.
	 */
	public static final int APPLICATION_WIDTH = 500;
	public static final int APPLICATION_HEIGHT = 500;

	GImage karel = null;
	private static final int STEP = 100;

	public void run() {
		karel = new GImage("karel.png");
		add(karel, 0, 0);
		addKeyListeners();
	}

	/* When a key is pressed, move Karel.
	 */
	public void keyPressed(KeyEvent k) {
		int code = k.getKeyCode();
		if(code == KeyEvent.VK_UP) {
			karel.move(0, -STEP);
		} else if(code == KeyEvent.VK_DOWN){
			karel.move(0, STEP);
		} else if(code == KeyEvent.VK_LEFT){
			karel.move(-STEP, 0);
		} else if(code == KeyEvent.VK_RIGHT){
			karel.move(STEP, 0);
		}
	}
}