import java.awt.image.BufferedImage;
public class PuzzlePiece {
private static final int DIST = 32;
private BufferedImage image;
private PuzzlePiece north, east, south, west;
private boolean n, e, s, w;
private int x, y;
public PuzzlePiece(BufferedImage image) {
this.image = image;
north = null;
east = null;
south = null;
west = null;
n = false;
e = false;
s = false;
w = false;
x = 0;
y = 0;
}
public BufferedImage getImage() {
return image;
}
public void setNorthLink(PuzzlePiece p) {
north = p;
}
public void setEastLink(PuzzlePiece p) {
east = p;
}
public void setSouthLink(PuzzlePiece p) {
south = p;
}
public void setWestLink(PuzzlePiece p) {
west = p;
}
public PuzzlePiece getNorthLink() {
return north;
}
public PuzzlePiece getEastLink() {
return east;
}
public PuzzlePiece getSouthLink() {
return south;
}
public PuzzlePiece getWestLink() {
return west;
}
public void linkToNorth() {
n = true;
}
public void linkToEast() {
e = true;
}
public void linkToSouth() {
s = true;
}
public void linkToWest() {
w = true;
}
public boolean isLinkedToNorth() {
return n;
}
public boolean isLinkedToEast() {
return e;
}
public boolean isLinkedToSouth() {
return s;
}
public boolean isLinkedToWest() {
return w;
}
public void setPos(int x, int y) {
if(x != this.x && y != this.y) {
this.x = x;
this.y = y;
if(n) {
getNorthLink().setPos(x, y - Game.pieceHeight);
}
if(e) {
getEastLink().setPos(x + Game.pieceWidth, y);
}
if(s) {
getSouthLink().setPos(x, y + Game.pieceHeight);
}
if(w) {
getWestLink().setPos(x - Game.pieceWidth, y);
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void updateConnections() {
if(north != null && !n) {
int xDist = getX() - getNorthLink().getX();
int yDist = getY() - getNorthLink().getY() - Game.pieceHeight;
if(Math.abs(xDist) <= DIST && Math.abs(yDist) <= DIST) {
linkToNorth();
getNorthLink().linkToSouth();
PuzzlePiece t = getNorthLink();
setPos(t.x, t.y + Game.pieceHeight);
}
}
if(east != null && !e) {
int xDist = getX() - getEastLink().getX() + Game.pieceWidth;
int yDist = getY() - getEastLink().getY();
if(Math.abs(xDist) <= DIST && Math.abs(yDist) <= DIST) {
linkToEast();
getEastLink().linkToWest();
PuzzlePiece t = getEastLink();
setPos(t.x - Game.pieceWidth, t.y);
}
}
if(south != null && !s) {
int xDist = getX() - getSouthLink().getX();
int yDist = getY() - getSouthLink().getY() + Game.pieceHeight;
if(Math.abs(xDist) <= DIST && Math.abs(yDist) <= DIST) {
linkToSouth();
getSouthLink().linkToNorth();
PuzzlePiece t = getSouthLink();
setPos(t.x, t.y - Game.pieceHeight);
}
}
if(west != null && !w) {
int xDist = getX() - getWestLink().getX() - Game.pieceWidth;
int yDist = getY() - getWestLink().getY();
if(Math.abs(xDist) <= DIST && Math.abs(yDist) <= DIST) {
linkToWest();
getWestLink().linkToEast();
PuzzlePiece t = getWestLink();
setPos(t.x + Game.pieceWidth, t.y);
}
}
}
}