Game Development Reference
In-Depth Information
Listing 4-14. CoinsGame.m (initRandomWithRows:Cols:)
-(id)initRandomWithR.ows:(int)rows Cols:(int)cols{
self = [super init];
if (self != nil){
coins = [NSMutableArray new];
colCount = cols;
rowCount = rows;
int numberOfCoins = colCount*rowCount;
for (int i=0;i<numberOfCoins;i++){
int result = arc4random()%3;
[coins addObject:[NSNumber numberWithInt:result]];
}
//Ensure we don't start with any matching rows and cols.
NSMutableArray* matchingRows = [self findMatchingRows];
NSMutableArray* matchingCols = [self findMatchingCols];
while ([matchingCols count] > 0 || [matchingRows count] > 0){
[self randomizeRows: matchingRows];
[self randomizeCols: matchingCols];
matchingRows = [self findMatchingRows];
matchingCols = [self findMatchingCols];
}
remaingTurns = 10;
score = 0;
}
return self;
}
In Listing 4-14, we see the initializer task used to create a new CoinsGame object with randomized
coins. After creating a new NSMutableArray and setting it to the variable coins and populate it with
the total number of coins we will have in the game. The value of the result will be 0, 1, or 2.
After we set up the first set of random values, we have to make sure we don't start the game
with any matches. This is done by first finding any matched by calling findMatchingRows and
findMatchingCols and seeing whether they contain anything. If they do, we randomize those
matches until no more matches are found. Finally, we set the number of remaining turns to 10 and
make sure the score starts out at 0. Continuing our exploration of the class CoinsGame , let's look at
coinForCoord: , shown in Listing 4-15.
Listing 4-15. CoinsGame.m (coinForCoord:)
-(NSNumber*)coinForCoord:(Coord)coord{
int index = [self indexForCoord:coord];
return [coins objectAtIndex:index];
}
 
Search WWH ::




Custom Search