import java.awt.event.*;

/** Controls the user's movement. To take effect, this object
 * must be registered as a KeyListener with whichever component
 * has the keyboard focus, and the <code>start</code> method
 * (inherited from Thread) must be executed so that the user
 * will move in the background. */
public class UserController extends Thread implements KeyListener {
	private User user;
	private int turn; // 1: clockwise, -1: counterclockwise
	private int dir; // 1: forward, -1: backward

	public UserController(User u) {
		user = u;
		turn = 0;
		dir = 0;
	}

	public void run() {
		while(true) {
			try {
				Thread.sleep(40);
			} catch(InterruptedException e) { }

			waitUntilMoving();

			user.turnAndStep(0.05 * turn, 0.1 * dir);
		}
	}

	private synchronized void waitUntilMoving() {
		while(turn == 0 && dir == 0) {
			try {
				wait();
			} catch(InterruptedException e) { }
		}
	}

	// KeyListener methods
	public void keyTyped(KeyEvent e) { }
	public synchronized void keyPressed(KeyEvent e) {
		switch(e.getKeyCode()) {
		case KeyEvent.VK_LEFT:  turn =  1; notifyAll(); break;
		case KeyEvent.VK_RIGHT: turn = -1; notifyAll(); break;
		case KeyEvent.VK_UP:    dir  =  1; notifyAll(); break;
		case KeyEvent.VK_DOWN:  dir  = -1; notifyAll(); break;
		}
	}
	public synchronized void keyReleased(KeyEvent e) {
		switch(e.getKeyCode()) {
		case KeyEvent.VK_LEFT:  turn =  0; notifyAll(); break;
		case KeyEvent.VK_RIGHT: turn =  0; notifyAll(); break;
		case KeyEvent.VK_UP:    dir  =  0; notifyAll(); break;
		case KeyEvent.VK_DOWN:  dir  =  0; notifyAll(); break;
		}
	}
}
