import java.util.Random; import java.util.Scanner; ///////////////////////////////////////////////////////////////////////////////////////// // Add code only at the positions indicated below by the comments, leaving the rest of // // the code untouched. Do not import any additional classes beyond the ones provided. // ///////////////////////////////////////////////////////////////////////////////////////// public class Puzzle { private final int SIZE = 4; public static final int UP = 8; public static final int DOWN = 2; public static final int LEFT = 4; public static final int RIGHT = 6; ///////////////////////////////////////////// // ADD APPROPRIATE INSTANCE VARIABLES HERE // ///////////////////////////////////////////// ///////////////////////////////////////// // ADD AN APPROPRIATE CONSTRUCTOR HERE // ///////////////////////////////////////// public String get(int row, int col) { return "" + (grid[row][col] == 16 ? " " : "" + grid[row][col]); } public boolean isSolved() { //////////////////////////////////////////////// // ADD CODE HERE SO THAT THIS METHOD. // // RETURNS true WHEN THE PUZZLE IS "IN ORDER" // //////////////////////////////////////////////// } public void slide(int direction) { ////////////////////////////////////////////// // ADD CODE HERE TO CHANGE THE STATE OF THE // // PUZZLE IN ACCORDANCE TO SLIDING A TILE // // UP, DOWN, LEFT, OR RIGHT AS POSSIBLE AND // // IN ACCORDANCE WITH THE CONSTANTS DEFINED // // ABOVE // ////////////////////////////////////////////// } public void shuffle() { //////////////////////////////////////////// // ADD CODE HERE TO SHUFFLE THE PUZZLE BY // // TRYING TO SLIDE A TILE INTO THE SPACE // // FROM A RANDOM DIRECTION 1000 TIMES // //////////////////////////////////////////// } public String toString() { String s = ""; for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { int num = grid[r][c]; s += (num < 10 ? " " : "") + (num == 16 ? " X" : num) + " "; } s += System.lineSeparator(); } return s; } public static void main(String[] args) { Puzzle puzzle = new Puzzle(); System.out.println("The goal is to get the numbers in the grid in order, with the (open) X in the bottom right"); System.out.println("Enter 2, 4, 8, and 6 to slide a tile down, left, up, or right, into the open X"); System.out.println("Repeat as needed, to solve the puzzle."); System.out.println(puzzle); // these are a couple slides to shuffle it "just a little" so that you can quickly solve it // feel free to add more slides to test the other directions puzzle.slide(LEFT); puzzle.slide(UP); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int direction = scanner.nextInt(); if (direction == 0) break; // which ends the program puzzle.slide(direction); if (puzzle.isSolved()) System.out.println("YOU SOLVED IT!"); System.out.println(puzzle); } } }