public class Puzzle { public static void main(String[] args) { setup(); play(); } public static void setup() { Grid.window(8, 3); Draw.setTitle("Column Puzzle"); Grid.setLineColor(0, 0, 0); drawArrows(); drawAllTiles(); } public static void drawArrows() { Grid.setImage(0, 0, "left.gif"); Grid.setImage(0, 1, "left.gif"); Grid.setImage(0, 2, "left.gif"); Grid.setImage(7, 0, "right.gif"); Grid.setImage(7, 1, "right.gif"); Grid.setImage(7, 2, "right.gif"); } public static boolean isEmpty(int x, int y) { return Grid.getRed(x, y) == 0 && Grid.getGreen(x, y) == 0 && Grid.getBlue(x, y) == 0; } public static void drawOneTile(int red, int green, int blue) { int x; int y; x = Util.random(1, 6); y = Util.random(0, 2); while (!isEmpty(x, y)) { x = Util.random(1, 6); y = Util.random(0, 2); } Grid.setColor(x, y, red, green, blue); } public static void drawAllTiles() { //draw 3 tiles of each color but cyan int numTimes; numTimes = 0; while (numTimes < 3) { drawOneTile(0, 0, 255); //blue drawOneTile(255, 0, 0); //red drawOneTile(0, 255, 0); //green drawOneTile(255, 255, 0); //yellow drawOneTile(255, 0, 255); //magenta numTimes = numTimes + 1; } //draw 2 cyan tiles drawOneTile(0, 255, 255); drawOneTile(0, 255, 255); } public static void swapTiles(int x1, int y1, int x2, int y2) { int red; int green; int blue; red = Grid.getRed(x1, y1); green = Grid.getGreen(x1, y1); blue = Grid.getBlue(x1, y1); Grid.setColor(x1, y1, Grid.getRed(x2, y2), Grid.getGreen(x2, y2), Grid.getBlue(x2, y2)); Grid.setColor(x2, y2, red, green, blue); } public static void slideOneTile(int x, int y) { if (y > 0 && isEmpty(x, y - 1)) //can slide up? { swapTiles(x, y, x, y - 1); //slide up } else { if (y < Grid.getHeight() - 1 && isEmpty(x, y + 1)) //can slide down? { swapTiles(x, y, x, y + 1); //slide down } } } public static void slideLeft(int y) { int red; int green; int blue; //save leftmost color red = Grid.getRed(1, y); green = Grid.getGreen(1, y); blue = Grid.getBlue(1, y); //swap 1st with 2nd, then 2nd with 3rd, etc. int x; x = 0; while (x < Grid.getWidth() - 2) { swapTiles(x, y, x + 1, y); //swap x with x + 1 x = x + 1; } //set color of last tile Grid.setColor(Grid.getWidth() - 2, y, red, green, blue); } public static void slideRight(int y) { int red; int green; int blue; //save rightmost color red = Grid.getRed(Grid.getWidth() - 2, y); green = Grid.getGreen(Grid.getWidth() - 2, y); blue = Grid.getBlue(Grid.getWidth() - 2, y); //swap 2nd to last with last, then 3rd to 2nd to last, etc. int x; x = Grid.getWidth() - 3; while (x >= 1) { swapTiles(x, y, x + 1, y); //swap x with x + 1 x = x - 1; } //set color of first tile Grid.setColor(1, y, red, green, blue); } public static void play() { int x; int y; while (true) { Draw.pauseUntilMouse(); x = Grid.getMouseX(); y = Grid.getMouseY(); if (x == 0) { //clicked on left arrow slideLeft(y); } else { if (x == 7) { //clicked right arrow slideRight(y); } else { //clicked on a tile slideOneTile(x, y); } } } } }