#import "MyViewController.h"
#define BOOMWIDTH 40
#define BOOMHEIGHT 40
@interface MyViewController ()
@end
@implementation MyViewController
-(void)loadView
{
[super loadView];
NSMutableArray *array = [NSMutableArray array];
// 铺地板
CGRect rect = CGRectMake(0, 0, BOOMWIDTH, BOOMHEIGHT);
for (int i = 0; i < 8; i++) {
rect.origin.y = BOOMHEIGHT * i + 40;
for (int j = 0; j < 8; j++) {
rect.origin.x = BOOMWIDTH * j + 20;
UILabel *boomLabel = [[UILabel alloc] initWithFrame:rect];
[self.view addSubview:boomLabel];
[boomLabel release];
[boomLabel setBackgroundColor:[UIColor whiteColor]];
[boomLabel.layer setBorderWidth:0.8];
[boomLabel.layer setBorderColor:[[UIColor grayColor] CGColor]];
[boomLabel setTag:(i + 1) * 100 + j + 1];
[array addObject:boomLabel];
}
}
// 随机产生雷, 产生一个雷, 就在雷的周围产生数字(随机抽出一个,然后移除)
//随机出5个雷
for (int i = 0; i < 5; i++) {
unsigned int rIndex = arc4random() % array.count;
UILabel *boomLabel = [array objectAtIndex:rIndex];
[boomLabel setText:@"*"];
[array removeObject:boomLabel];
[boomLabel setTextAlignment:NSTextAlignmentCenter]; // 居中;
[boomLabel setFont:[UIFont systemFontOfSize:30]];
// 添加数字
// 先算出tag值,取出label 在 + 1;(放在数组中)
int offset[8] = {-100 - 1, -100, -100 + 1, -1, +1, +100 - 1, +100, +100 + 1};
// 雷的周围写上数字
for (int i = 0; i < 8; i++) {
NSInteger newTag = boomLabel.tag + offset[i];
UILabel *newLabel = (UILabel *)[self.view viewWithTag:newTag];
if ([newLabel.text isEqualToString:@"*"]) {
continue; // 雷的地方不能在覆盖数字
}
NSInteger number = newLabel.text.integerValue + 1;// 雷数
[newLabel setText:[NSString stringWithFormat:@"%ld", number]];
}
}
}