package pac;
import java.applet.Applet;
import java.awt.*;

public class RunPac extends Applet implements Runnable {
    int x;
    int y = 30;
    int r = 25;
    int op = 0; // angle of mouth open
    boolean mouthopen = true; // true = opening, false = closing  
    boolean direction = true; // true = right, false = left

    int maxx = 400; // size of applet x axis

    Thread thread;

    /**
     * Called to start the applet. You never need to call this method
     * directly, it is called when the applet's document is visited.
     * @see java.applet.Applet#start
     */
    public void start() {
	if (thread == null) {
	    thread = new Thread(this);
	    thread.start();
	}
    }

    /**
     * Called to stop the applet. It is called when the applet's document is
     * no longer on the screen. It is guaranteed to be called before destroy()
     * is called. You never need to call this method directly.
     * @see java.applet.Applet#stop
     */
    public void stop() {
	if (thread != null) {
	    thread.stop();
	}
    }

    /**
     * Initializes the applet.
     * You never need to call this directly, it is called automatically
     * by the system once the applet is created.
     * @see java.applet.Applet#init
     */
    public void init() {
	resize(400, 60);
	x = r;

    }

    /**
     * Paints the component.
     * @param g the specified Graphics window
     * @see java.awt.Component#paint
     */
    public void paint(Graphics g) {
	g.setColor(Color.yellow);
	if (direction) {
	    g.fillArc(x, y, r, r, op, 360-2*op); // draw Pac
	} else {
	    g.fillArc(x, y, r, r, op+180, 360-2*op); // draw Pac
	}
    }

    /**
     * java.lang.Runnable stuff
     */
    public void run()  {
	while (true) {
	    try {
		Thread.sleep(10);

		if (op > 45) {
		    mouthopen = false;
		} else if (op < 0) {
		    mouthopen = true;
		}
		if (mouthopen) {
		    op += 5; 
		} else {
		    op -= 5;
		}

		
		if (direction) {
		    x += 2;
		} else {
		    x -= 2;
		}

		if (x >= (maxx + r)) {
		    x = -r;
		} else if (x < -r) {
		    x = maxx + r;
		}
		repaint();
	    } catch (InterruptedException e) {}
	}
    }

    public void changeDirection() {
	direction = !direction;
    }

    /**
     * Called if the mouse is down.
     * @param evt the event
     * @param x the x coordinate
     * @param y the y coordinate
     * @see java.awt.Component#mouseDown
     */
    public boolean mouseDown(Event evt, int x, int y) {
	changeDirection();
	return true;
    }
}
