//
//Puzzle - copyright 1998, Ken Perlin; all rights reserved.

import java.awt.*;
import java.net.*;

public class Puzzle extends BufferedApplet //BufferedApplet
{
   int w = 100, i = 3, j = 3, I[][] = new int[4][4], J[][] = new int[4][4];
   Image src = null;

   public void render(Graphics g) {
      if (src == null) {                 //First time: fetch the image.
         try {
            src = getImage(new URL(getParameter("src")));
         } catch (MalformedURLException e) { System.err.println(e); }
         for (int u = 0 ; u < 4 ; u++)
         for (int v = 0 ; v < 4 ; v++) {
            I[u][v] = v;                 //Squares begin in transposed order.
            J[u][v] = u;
         }
      }
      for (int u = 0 ; u < 4 ; u++)      //To render: paste on each square,
      for (int v = 0 ; v < 4 ; v++)
         g.create(u*w,v*w,w,w).drawImage(src, -I[u][v]*w, -J[u][v]*w, this);
      g.setColor(Color.gray.brighter());
      g.fill3DRect(i*w,j*w,w,w, false);  //then draw the blank square.
   }

   public boolean mouseUp(Event e, int x, int y) {
      int u = x / w, v = y / w;
      if (u>=0 && u<4 && v>=0 && v<4 && Math.abs(u-i)+Math.abs(v-j) == 1) {
         I[i][j] = I[u][v];
         J[i][j] = J[u][v];             //User clicked on a square that's
         i = u;                         //next to the blank square:
         j = v;                         //move the clicked-on square.
      }
      return true;
   }
}