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
TileView
s.
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
.
main.m
PuzzleAppDelegate
View
TileView
20.png
)
is not used.
00.png
01.png
02.png
10.png
11.png
12.png
20.png
21.png
22.png
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"….
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));
TileView
that cannot move.