
import java.applet.*;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.util.*;


public class cartman extends Applet implements Runnable, MouseListener {

    MediaTracker tracker;         // tracks the loading of images

    Image bg;
    Image cartman_r[] = new Image[4];
    Image cartman_l[] = new Image[4];

    final int RIGHT=1;           // status stores whether character is
    final int LEFT=2;            // walking left or right

    int status = RIGHT;

    int index;                   // current character animation frame
    int x_offset;                // character offset from left

    Thread animator;            // Thread that does the animation.
                                // started and stopped by start() and stop()

    Graphics buffer;        // Graphics context to the buffer_image
    Image buffer_image;     // The offscreen double buffer.

    // Get the images for the background (id == 0)
    // and the animation frames (id == 1)
    // and add them to the MediaTracker

    public void init() {

        // Create double buffer image and the grahpics context
        // that is used to do all drawing to it.

        buffer_image = createImage(size().width, size().height);
        buffer = buffer_image.getGraphics();

        // Sound Stuff

        LoadSounds();

        addMouseListener(this);

        // Load in images

	    tracker = new MediaTracker(this);

        cartman_r[0] = getImage(getDocumentBase(), "cartman_r_1.gif" );
        cartman_r[1] = getImage(getDocumentBase(), "cartman_r_2.gif" );
        cartman_r[2] = getImage(getDocumentBase(), "cartman_r_3.gif" );
        cartman_r[3] = getImage(getDocumentBase(), "cartman_r_2.gif" );

	    cartman_l[0] = getImage(getDocumentBase(), "cartman_l_1.gif" );
	    cartman_l[1] = getImage(getDocumentBase(), "cartman_l_2.gif" );
	    cartman_l[2] = getImage(getDocumentBase(), "cartman_l_3.gif" );
	    cartman_l[3] = getImage(getDocumentBase(), "cartman_l_2.gif" );

	    // Add to media tracker that tracks loading
	    // add each with differend id

	    int id=0;

	    tracker.addImage(cartman_r[0], 0);
	    tracker.addImage(cartman_r[1], 0);
	    tracker.addImage(cartman_r[2], 0);
	    tracker.addImage(cartman_r[3], 0);

	    tracker.addImage(cartman_l[0], 1);
	    tracker.addImage(cartman_l[1], 1);
	    tracker.addImage(cartman_l[2], 1);
	    tracker.addImage(cartman_l[3], 1);
    }

    // Start the animation thread when applet is visible

    public void start() {
        animator = new Thread(this);
        animator.setPriority(Thread.MIN_PRIORITY);
        animator.start();
    }

    // Stop the animation thread when applet hidden.

    public void stop() {
        animator.stop();
        animator = null;
    }

    // Run the animation thread.
    // First wait for the background image to fully load
    // and paint.  Then wait for all of the animation
    // frames to finish loading. Finally, loop and
    // increment the animation frame index.

    public void run() {

        // Don't do anything until right walk images loaded
        try {
            tracker.waitForID(0);
	        tracker.waitForID(1);
        } catch (InterruptedException e) {
            return;
        }

        // Loop continualy until applet stop() function calls thread.stop()

        while (true) {

            try { Thread.sleep(200); }              // This pause governs walking speed
            catch (InterruptedException e) { return; }

            if (status==RIGHT) {   // walking RIGHT
                index++;
	            x_offset=x_offset+3;

	            if (x_offset>= (size().width-100)) {   // oo. got to edge, change direction
		            status = LEFT;
	            }

	            if (index >= 4)          // start at anim frame one again
		            index = 0;

             }
             else {   // walking LEFT
	            index++;
	            x_offset= x_offset-2;

	            if (x_offset<= 5) {                  // oo. get to edge, change direction
		            status = RIGHT;
	            }

	            if (index >= 4)      // start at anim frame one again
		            index=0;
             }

            repaint();
        }
    }

    // The background image fills the frame so we
    // don't need to clear the applet on repaints.
    // Just call the paint method.

    public void update(Graphics g) {
	    paint(g);
    }

    public void paint(Graphics g) {

        // Check is there has been an ERROR loading any of
        // the images.
        // If there has, then display a red rectangle.

        if ((tracker.statusAll(false) & MediaTracker.ERRORED) != 0) {
	        g.setColor(Color.red);
	        g.fillRect(0, 0, size().width, size().height);
	        g.setColor(Color.white);
	        g.drawString("An error occured",5,30);
	        g.drawString("loading images",5,50);

	        return;
	    }

        // If all images loaded then we can display.

	    if (tracker.statusAll(false) == MediaTracker.COMPLETE) {
	        buffer.setColor(Color.black);
	        buffer.fillRect(0,0, size().width, size().height);

	        if (status==RIGHT)
	            buffer.drawImage(cartman_r[index], x_offset, 0, this);
	        else
	            buffer.drawImage(cartman_l[index], x_offset,0, this);

            g.drawImage(buffer_image,0,0,this);
        }
        else
	    {
            g.drawString("loading",10,20);
	    }

    }


    public void mousePressed(MouseEvent e) {
        if (status == RIGHT) status = LEFT; else status = RIGHT;
        System.out.println("click"); PlaySound();
    }
    public void mouseClicked(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) { }


    /*
     * Functions to deal with loading and playing sounds
     */

    final int max_sounds = 9;
    AudioClip sounds[] = new AudioClip[max_sounds];

    private void LoadSounds() {
        sounds[0] = getAudioClip(getDocumentBase(),"cart_cka.au");
        sounds[1] = getAudioClip(getDocumentBase(),"cart_dem.au");
        sounds[2] = getAudioClip(getDocumentBase(),"cart_god.au");
        sounds[3] = getAudioClip(getDocumentBase(),"cart_hell.au");
        sounds[4] = getAudioClip(getDocumentBase(),"cart_hippy.au");
        sounds[5] = getAudioClip(getDocumentBase(),"cart_kickass.au");
        sounds[6] = getAudioClip(getDocumentBase(),"cart_pissed.au");
        sounds[7] = getAudioClip(getDocumentBase(),"cart_sick.au");
        sounds[8] = getAudioClip(getDocumentBase(),"cart_sob.au");
    }

    private void PlaySound() {
        int i = (int) (Math.random() * max_sounds);
        System.out.println("playing sound " + i);
        sounds[i].play();
    }


}


