Classic Puzzle

Classic game of eight movable tiles in a 3 × 3 square with one missing. The original photo from the Wikipedia article was chopped into nine smaller pieces (of which eight are displayed) by a Unix shellscript using the Netpbm toolkit. You probably would rather chop it up using a differnt application.

The application delegate creates one big white View. The View creates eight smaller TileViews. Each TileView is derived from class UIImageView and holds a 100 × 100 UIImage. It also holds a row number and a column number which change as the TileView is moved around. We saw class UIImage here, and class UIImageView here.

subclass of UIView is specialized for holding a
UILabel single-line NSString
UITextView multi-line NSString
UIImageView UIIimage

The View contains the row number and column number of the currently empty place. To permit the TileView to access the numbers in the View, these numbers are properties of the View and we gave each TileView a pointer to the View.

Source code in Puzzle.zip

  1. main.m
  2. Class PuzzleAppDelegate
  3. Class View
  4. Class TileView
  5. The lower left image (20.png) is not used.
    00.png 01.png 02.png
    10.png 11.png 12.png
    20.png 21.png 22.png

Create the project

Put the eight .png files in the folder that holds the project and then add them to the project. Highlight the Supporting Files folder in the Project Navigator. Right-click on the Supporting Files folder and select Add Files to "Puzzle"….

Things to try

  1. Rearrange the pieces randomly when the app is launched. Change the NSSet set into an NSArray named array. Paste the following loop into the initWithFrame: method of class View immediately after changing the bounds of the View. It will make the game touch itself 50 times in random places. The value of r is a randomly selected integer in the range 0 to 8 inclusive.
    	for (int i = 0; i < 50; ++i) {
    		NSUInteger r = rand() % array.count;
    		TileView *touch = [array objectAtIndex: r];
    		[touch touchesBegan: nil withEvent: nil];
    	}
    
    Paste the following statement into the main function in main.m immediately before the call to UIApplicationMain. It will seed the random number generator, i.e., shake up the internal dice. This will generate different random numbers each time the app is run.
    	srand(time(NULL));
    

  2. Count how many moves the user has made.

  3. Punish the user with a beep if he or she touches a TileView that cannot move.