Game Development Reference
In-Depth Information
mismatch = true;
break;
}
}
if (!mismatch){
[matchingRows addObject:[NSNumber numberWithInt:r]];
}
}
return matchingRows;
}
The task
findMatchingRows
creates a new
NSMutableArray
called
matchingRows
to store any results.
Matching rows are found by looking at each row in turn and inspecting the coin at each column.
This is done by storing the coin at column 0 as the variable
coin0
and then by comparing
coin0
to each coin in the other columns. If a coin is found that does not match
coin0
, we know that
there is no match, and mismatch is set to true. If no mismatches are found, we add the value
r
to the
NSMutableArray matchingRows
, which is the result of this task. The implementation for
findMatchingCols
is trivially different and is omitted for brevity.
We also know that after matching rows are found,
CoinsController
will have to randomize any
matches to prepare for the next turn the user takes. This is done with the tasks
randomizeRows:
and
randomizeCols:
. The task
randomizeRows:
is shown in Listing 4-19.
Listing 4-19. CoinsGame.m (randomizeRows:)
-(void)randomizeRows:(NSMutableArray*)matchingRows{
for (NSNumber* row in matchingRows){
for (int c=0;c<colCount;c++){
int index = [self indexForCoord:CoordMake([row intValue], c)];
int newCoin = arc4random()%3;
[coins replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:newCoin]];
}
}
}
The task
randomizeRows
takes an
NSMutableArray
filled with
NSNumbers
. Each
NSNumber
is a row. By
iterating over each row, we set a new random value for every coin in that row. The implementation of
randomzeCols:
is similar; we simply randomize each coin for the columns passed in.
Now that you have an understanding of the class
CoinsGame
, you can take a further look at
CoinsController
and see how this class used the data stored in
CoinsGame
to interpret user input,
manage the views representing the coins, and create animations based on game state.
Interpreting User Input
When the user touches one of the coins, we want to mark it as selected. Looking back at Listing 4-8,
we know that a
UITapGestureRecognizer
was created and added to the
UIView coinsView
. This
UITapGestureRecognizer
calls the task
tapGesture:
whenever it registers a tap gesture. Let's look at
the first part of
tapGesture:
in Listing 4-20.