Fifteen
In this exercise we will develop a model class for the
Fifteen Puzzle:
The class must be called FifteenModel. Once it is complete
you can extract the code in fifteen.zip to a folder on your
computer. Put your model class in the same folder and then compile
and run GraphicsMain.java. You will get a fully functional puzzle.
Alternatively you can compile and run TextMain to get the same puzzle
working in the terminal.
You need to complete four tasks:
- The easiest way to model the state of the puzzle is via a
two dimensional array of size 4 by 4. Each element in the array
will contain a number from 0 to 15. When the number at position
(i,j) is zero then this would mean that the hole in the puzzle is in
position (i,j). If the number is between 1 and 15
then this means that the piece labeled with that number is
at the corresponding position in the puzzle. In addition it would
be handy to always keep track of the current position of the hole
in separate integer variables.
Define the following instance variables to model the state of the puzzle:
private int[][] state;
private int hrow, hcol;
Here state is the array of numbers and hrow and hcol
are the row and column where the hole is currently located.
Define a constructor which initializes the variables in such a way
that the initial state of the puzzle will be the same as on the picture
above.
public FifteenModel ()
- Define a method getState which returns the current
state at position (row, col).
public int getState(int row, int col)
- Define a method tryMovePieceAt which tries to move the hole
to position (row, col). This is possible only if
the hole is currently adjacent to the target position, i.e. it is
located to the left, to the right, above or bellow the target position.
If the hole is successfully moved then the method should return true,
otherwise it must return false.
public boolean tryMovePieceAt(int row, int col)
- Define a method which shuffles the current state of the puzzle.
The easiest way to do that is to call tryMovePieceAt
one thousand times with a random row and column. Many of the movements
will fail but enough will succeed to produce a shuffled puzzle.
public void shuffle()