1、生成數(shù)據(jù)圖
/** 生成地圖數(shù)據(jù) */
- (void)createMapData{
for (int i = 0; i < self.mapRow; i++) {
NSMutableArray *subList = [NSMutableArray array];
for (int j = 0; j < self.mapCol; j++) {
//外圍輔0
if (i == 0 || j == 0 || i == self.mapRow - 1 || j == self.mapCol - 1) {
[subList addObject:@0];
}
//內(nèi)圍隨機(jī)
else{
NSInteger value = random() % (ElementTypeNum + 1);
[subList addObject:[NSNumber numberWithInteger:value]];
}
}
[self.mapList addObject:subList];
}
///數(shù)據(jù)圖
/////0000000000000/////
/////0273672362530/////
/////0565455354350/////
/////0354565346350/////
/////0544343452520/////
/////0000000000000/////
}
ElementTypeNum:代表多少種元素類型
數(shù)據(jù)圖中大于0的數(shù)據(jù)都將按類型替換成圖片
2、把數(shù)據(jù)換成圖片
/** 創(chuàng)建連連看元素*/
- (void)createElement{
for (int i = 0; i < self.mapList.count; i++) {//遍歷數(shù)據(jù)圖
NSMutableArray *subList = self.mapList[I];
for (int j = 0; j < subList.count; j++) {
NSInteger type = [subList[j] integerValue];
if (i == 0 || j == 0 || i == self.mapRow - 1 || j == self.mapCol - 1 || type == 0) {
continue;//過濾掉0,0代表無圖片
}
//生成元素
float elementX = (j % self.mapCol) * self.elementWH + Padding;
float elementY = (i % self.mapRow) * self.elementWH + self.topPadding;
__weak typeof(self) weakSelf = self;
LLKElement *element = [[LLKElement alloc] initWithFrame:CGRectMake(elementX, elementY, self.elementWH, self.elementWH) clickedBlock:^(UIButton *button) {
LLKElement *clickElement = (LLKElement *)button;
if (weakSelf.curElement) {
if (weakSelf.curElement.row == clickElement.row && weakSelf.curElement.col == clickElement.col && weakSelf.curElement.type == clickElement.type) {
//如果行列類型全相等 則表示用戶點(diǎn)了兩次該按鈕
return;
}
weakSelf.oldElement = weakSelf.curElement;
}
weakSelf.curElement = clickElement;
[weakSelf checkElementConnection];
}];
//賦值坐標(biāo)給元素
element.row = I;
element.col = j;
element.type = type;
[self.elementDic setValue:[NSNumber numberWithInteger:type] forKey:[NSString stringWithFormat:@"%d%d", i,j]];
[self addSubview:element];
}
}
}
(元素的點(diǎn)擊事件可以先不看,以免影響理解)創(chuàng)建元素方法做了以下幾件事
0:無元素占據(jù),所以要過濾掉
按數(shù)據(jù)圖給的數(shù)據(jù)生成元素,并把坐標(biāo)和類型賦值給元素
以坐標(biāo)為key,元素為value 存到元素字典
效果圖:

頂上是時(shí)間條控制游戲進(jìn)度的.png