1,首先创建4*4的16个按钮,先把所有按钮设置为白色,再在每层产生一个0-3的随机数,将对应的按钮设置为黑色显示出来,如图:
代码如下:
for (int j = 0; j < 4; j++) {
int arc = arc4random() % 4;
for (int i = 0; i < 4; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(80 * i, 120 * j, 80, 120);
button.tag = 101 + i + j * 10;
button.layer.borderWidth = 0.5;
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor whiteColor];
if (button.tag == 101 + j * 10 + arc) {
button.backgroundColor = [UIColor blackColor];
}
[self.view addSubview:button];
}
}
2,每当点击按钮时,通过button的tag值判断,只有点击最下层按钮才会有反应,当点击到黑色块时最下层消失,集体下移一层,当点击到白色块时游戏结束,如图:
代码如下:
- (void)buttonClick:(UIButton *)button
{
if (button.tag == 131 || button.tag == 132 || button.tag == 133 || button.tag == 134) {
if (button.backgroundColor == [UIColor whiteColor]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你输了!" delegate:nil cancelButtonTitle:@"再来一次" otherButtonTitles:@"确定", nil];
[alertView show];
[alertView release];
} else {
NSMutableArray *arr = [NSMutableArray array];
// 取出上面一排颜色为黑色的按钮的tag值
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 4; i++) {
UIButton *button1 = (UIButton *)[self.view viewWithTag:101 + i + j * 10];
if (button1.backgroundColor == [UIColor blackColor]) {
[arr addObject:[NSString stringWithFormat:@"%d",button1.tag]];
}
}
}
int arc = arc4random() % 4;
int tag = 101 + arc;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
UIButton *button3 = (UIButton *)[self.view viewWithTag:101 + i + j * 10];
button3.backgroundColor = [UIColor whiteColor];
if (button3.tag == tag) {
button3.backgroundColor = [UIColor blackColor];
}
}
}
for (int i = 0; i < arr.count; i++) {
int tag = [[arr objectAtIndex:i]integerValue];
UIButton *button2 = (UIButton *)[self.view viewWithTag:tag + 10];
button2.backgroundColor = [UIColor blackColor];
}
}
}
}