import java.awt.*;
import java.applet.*;


public class Mancala extends Applet implements Runnable {

  int lookdepth;
  boolean captures;
  boolean astarts;
  String whosemove;
  
  Position cp;    // current position

  Thread thinker;

  //Construct the applet
  public Mancala() {
  }

  //Initialize the applet
  public void init() {
    lookdepth = 14;
    captures = true;
    astarts = true;
    mouseUp(null,0,0);
  }

  //Start the applet
  public void start() {
  }

  //Stop the applet
  public void stop() {
    while (thinker != null) {
      cp.stopflag = true;
      Thread.yield();
    }
  }

  //Destroy the applet
  public void destroy() {
  }

  //Get Applet information
  public String getAppletInfo() {
    return "Applet Information";
  }

  //Get parameter info
  public String[][] getParameterInfo() {
    return null;
  }

  public void run() {

    cp.evaluate(cp.a2move,lookdepth);
    thinker = null;
  }

  public void paint(Graphics g) {
    Dimension d = size();
    int dx = d.width / 16;
    int dy = d.height / 4;
    int i;
    for ( i = 0; i < 6; i++ ) {
      g.drawOval( (i+1)*2*dx+2, 2, 2*dx-4, 2*dy-4 );
      g.drawString(String.valueOf(cp.pits[12-i]),((i+1)*2+1)*dx,dy);
      g.drawOval( (i+1)*2*dx+2, 2*dy+2, 2*dx-4, 2*dy-4 );
      g.drawString(String.valueOf(cp.pits[i]),((i+1)*2+1)*dx,3*dy);
      }
    g.drawOval( 2, 2, 2*dx-4, 4*dy-4 );
    g.drawString(String.valueOf(cp.pits[13]),dx,2*dy);
    g.drawOval( 14*dx+2, 2, 2*dx-4, 4*dy-4 );
    g.drawString(String.valueOf(cp.pits[6]),15*dx,2*dy);
    g.drawString(whosemove,0,d.height);
  }

  public boolean mouseUp(Event e, int x, int y) {
    Dimension d = size();
    x = 8*x/d.width;
    y = 2*y/d.height;
    if (x==0) {
      stop();
      cp = new Position();
      cp.a2move = astarts;
      astarts = !astarts;
    }
    else {
      x = (y!=0)? x-1: 13-x;  // x = pit index
      if (x==6) {
        Graphics g = getGraphics();
        boolean i = true;
        while (thinker!=null) {
          whosemove = i? "/": "\\";
          i = !i;
          g.clearRect(0,d.height-12,10,12);
          g.drawString(whosemove,0,d.height);
          try {
            Thread.sleep(250);
          }
          catch (InterruptedException ie) {
          }
        }
        cp = cp.move();
      }
      else {
        stop();
        cp = cp.move(x);
      }
      cp.sib = null;
    }
    thinker = new Thread(this);
    cp.stopflag = false;
    thinker.start();
    whosemove = cp.a2move? "A": "B";
    repaint();
    return true;
  }

}


