Game Development Reference
In-Depth Information
The task
coinForCoord:
takes a
Coord
and returns the type of coin at that location. Finding the
NSNumber
object at the given index in the
NSMutableArray coins
does this. The
index
is determined
by calling
indexForCoord:
, shown in Listing 4-16.
Listing 4-16. CoinsGame.m (indexForCoord:)
-(int)indexForCoord:(Coord)coord{
return coord.row*colCount + coord.col;
}
The task
indexForCoord:
takes a
Coord
struct. This simple task multiplies the number of columns in
the game by the row value of
coord
and adds the col value.
CoinsGame.m
that should be explored to help you understand what
is doing during different parts of its life cycle. Let's continue by looking at the task
, shown in Listing 4-17.
CoinsGame.m (swap:With:)
int indexA = [self indexForCoord:coordA];
int indexB = [self indexForCoord:coordB];
NSNumber* coinA = [coins objectAtIndex:indexA];
NSNumber* coinB = [coins objectAtIndex:indexB];
[coins replaceObjectAtIndex:indexA withObject:coinB];
[coins replaceObjectAtIndex:indexB withObject:coinA];
}
The task
swap:With:
takes two
Coords
,
coordA
and
coordB
. This task switches the type of coins at
these two coordinates by finding the index of each coordinate, the current value of that index in
coins, and switching them. We know that after coins are swapped,
CoinsController
will have to look
for any matches. This is done with the tasks
findMatchingRows
and
findMatchingCols
. Listing 4-18
shows findMatchingRows.
Listing 4-18. CoinsGame.m (findMatchingRows)
-(NSMutableArray*)findMatchingRows{
NSMutableArray* matchingRows = [NSMutableArray new];
for (int r=0;r<rowCount;r++){
NSNumber* coin0 = [self coinForCoord:CoordMake(r, 0)];
BOOL mismatch = false;
for (int c=1;c<colCount;c++){
NSNumber* coinN = [self coinForCoord:CoordMake(r,c)];
if (![coin0 isEqual:coinN]){