by Marko Riedel
The goal is to implement the sixteen puzzle. The classic version of this puzzle consists of fifteen pieces that are placed in a box that is four pieces wide and four pieces high. There is one empty slot. Pieces in the same row as the empty slot can move horizontally and those in the same column can move vertically. The pieces are scrambled and the goal is to restore the start position, which lists the pieces sequentially, starting from the top row. There seems to be some confusion as to whether this puzzle should be called the fifteen puzzle or the sixteen puzzle, we choose the latter. The start position is shown in Fig. 8.
We will let the user choose how many pieces there should be to a single row or column. The user can pick any TIFF image she likes to use as the content of the pieces. These parameters are passed in via the command line.
There are two components to this application. There is a view that displays the pieces and a controller that creates auxiliary objects like the main menu and the window that holds the view.
Start by declaring some constants: the minimum and maximum number of pieces per row/column and the minimum width and height of a single piece.
The class SixteenView implements a view that draws all the pieces (a different approach might use one view for every piece). This view has two states: either scrambled or not scrambled. It displays the source image as is when it is in the latter state, otherwise it displays the individual pieces. It must also react to mouse clicks and move pieces accordingly.
Now discuss the variables. The view must remember the state of the board. It stores the state in the two-dimensional array board, where the first index determines the row and the second the column. The entries are integers where the integer m represents the piece that sits in row m∕d, where d is the size, and column m%d in the source image. The value -1 represents the blank. The variable bdim is used to store the number of pieces per row or column. We record the position of the blank in the variables blankX and blankY. There is a flag that indicates whether the view is scrambled or not. We store the source image in the variable image and the dimensions of the individual pieces in the variable pieceSize. We’ll be copying rectangular portions of the source image whose size is given by pieceSize in order to construct the image of the scrambled board.
There are only a few methods to SixteenView. There is an initializer that is invoked with the origin of the view, the source image, and the number of pieces per row and column.
We implement acceptsFirstResponder so that the board can be scrambled with a click on the application’s main menu. The method totalPositioned tells us how many pieces are in the right position. It will help us determine when the board is properly scrambled and when the user has solved the puzzle.
The method doMoveX:Y: is used to move pieces in response to clicks and while we scramble the pieces. Suppose the user clicks on a piece anywhere in the same row or column as the blank. The pieces move so that the blank is in the position that the user clicked on (there is only one way for them to go). The method scramble: scrambles the pieces. The last two methods are important: drawRect: must draw the view according to its internal state and mouseDown: processes mouse clicks by the user.
The first thing the initializer does is to compute the frame of the view. It is determined by the position that was passed in as an argument and the size of the image. The width and the height of the image may not always be divisible by the number of rows and columns. Any leftover at the right or at the top will not be displayed, hence we reduce the frame size by those leftover amounts. We then invoke NSView’s method initWithFrame: as required to initialize the view.
The initializer stores the source image in the instance variable and computes the width and height of the individual pieces. It raises an exception if either is too small. We may store the dimension if there was no problem.
Next we indicate that a new SixteenView is not in the scrambled state and initialize the board accordingly. The blank goes in the last column of the bottom row.
We implement acceptsFirstResponder so that the view may respond to action messages.
The method totalPositioned iterates over all positions on the board and records the number of pieces that are in the correct position.
The method doMoveX:Y: responds to a click at the position that is given by the two arguments. There are four cases. There is nothing to do if the user has clicked on the blank or on a piece that shares neither row nor column with the blank. The interesting cases occur when the user clicks on a piece in the same row or column as the blank. We move the pieces that lie between the click position and the blank, each piece by one position. They move down, if the user clicked above the blank, up, if the user clicked below, right, if the user clicked to the left and finally, left, if the user clicked to the right. These four cases are handled by loops that shift the pieces. We update the position of the blank.
The method scramble: scrambles the board. It makes maxIter valid moves, where maxIter is the total number of pieces and checks that at most a quarter of the pieces are in the correct position. The process repeats if this is not the case (too many pieces placed correctly).
There is an outer loop that checks the number of correctly placed pieces and an inner loop that carries out maxIter moves. Moves are determined as follows: first flip a coin to decide whether to move horizontally or vertically. Then pick a random position that is not equal to the position of the blank and carry out the move. How to avoid the position of the blank? First pick a position that is not the last position, then add one if it is larger than or equal to the blank’s position. This guarantees a uniformely random choice between the available positions, which exclude the blank.
The last thing scramble: does is to record the fact that the view has been scrambled and mark it for display.
The method drawRect: is important. It draws the view according to its internal state. Almost everything is done by compositing rectangular portions of the source image. The easy part is first. Simply composite the rectangle that needs drawing when the view is not scrambled, and draw a boundary around the entire image.
It stays quite simple even when the view is scrambled. Iterate over the positions of the board. The current row and column tell us where content of the piece should go. The actual value of the board at that position tells us where in the source image the piece is to be found. We do not draw the blank.
We compute the source rectangle (where the piece resides in the source image) and the destination rectangle (where it is on the board) for each position of the board, do the composite operation and draw a boundary around the piece; there is nothing to draw for the blank.
The last method of SixteenView is the method mouseDown:. It must respond to clicks by the user and reposition pieces accordingly. The first step is to compute the location of the click in the view’s coordinate system (not essential here, but good practice). Next we determine what piece has been clicked. There is nothing to do when the user clicks and the view is not scrambled; the same goes for clicks that are not in the same row/column as the blank. If the click makes sense then we process it.
The last step is to check whether the user has solved the puzzle, which occurs when there are as many pieces in place as there are positions on the board, minus the blank. In this case display the complete image right away and congratulate the user, otherwise mark the view as needing display.
The controller is very simple. It builds the window and the view once the application has been launched, sets the main menu and processes command line arguments.
We need to get at the arguments, so we obtain them from the process info object. One of these is the path to the source image, which is a string and will be stored in the variable imgPath. There is the variable img that holds the image itself. We also obtain the number of pieces per row or column from the command line: this is recorded in the variable size. We declare variables to hold the window, the main menu, the SixteenView and the content rectangle of the window.
The first action is to seed the random number generator so that we get different results from a scramble operation every time the program is run. We build the main menu with two entries, one to scramble the view and another to quit the application, and display it right away.
The arguments are processed next. There must be three of them: the application binary, the size and the image. We raise an exception when we do not have the right number of arguments or when the size is to small for a meaningful game or too large for the board.
We try to read the image from the file and raise an exception if there is a problem.
We allocate the instance of SixteenView next. The initializer of the view computes the size of the view from the size of the image and we use this value as the size of the window’s content rectangle.
Finally we allocate the window, set its title, make the SixteenView the content view and the initial first responder, center the window and order it to the front.
The function main is the same as in the df frontend recipe: it allocates the application and the controller and runs the application.