/* Copyright 1996 Rujith de Silva. Modified 2002-03-07 */ package rujith.pentominoes; /** * A piece composed of adjoining squares on a rectangular grid that * can be rotated or swapped (flipped over). */ public class Piece { // Multiplier to get the x-coordinate for each of the four // directions static private final int xmul[][] = { { 1, 0 }, { 0, -1 }, { -1, 0 }, { 0, 1 } }; // Multiplier to get the y-coordinate for each of the four // directions static private final int ymul[][] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; // Initial (x,y) positions of the five squares private final int init[][] = new int[5][2]; // Initial direction of the piece. private int direction = 0; // Is the piece flipped or not. private boolean swap = false; /** * Current (x,y) positions of the five squares. Do not update * these values directly. */ final protected int current[][] = new int[5][2]; /** * Create a new Piece. * * @param init Initial (x,y) positions of the five squares. A * (5x2) array. */ public Piece (int init[][]) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 2; ++j) { this.init[i][j] = init[i][j]; this.current[i][j] = init[i][j]; } } } /** * @return Current direction of the piece */ public int getDirection () { return this.direction; } /** * Update the direction of the piece * * @param i New direction. Varies between 0 and 3. */ synchronized public void setDirection (int i) { i %= 4; if (this.direction != i) { this.direction = i; this.update (); } } /** * @return Current swap (flip) setting of the piece */ public boolean getSwap () { return this.swap; } /** * Update whether the piece is flipped or not * * @param sw True if piece should be flipped */ synchronized public void setSwap (boolean sw) { if (this.swap != sw) { this.swap = sw; this.update (); } } // Update the current positions of the squares synchronized private void update () { int dir = this.direction; int xm1 = xmul[dir][0]; int xm2 = xmul[dir][1]; int ym1 = ymul[dir][0]; int ym2 = ymul[dir][1]; // Perform simple matrix multiplication to get the new squares for (int i = 0; i < 5; ++i) { int i0 = this.init[i][0]; int i1 = this.init[i][1]; if (this.swap) i1 = - i1; this.current[i][0] = i0 * xm1 + i1 * xm2; this.current[i][1] = i0 * ym1 + i1 * ym2; } } }