首页 > 代码库 > OC实现简单的关灯游戏
OC实现简单的关灯游戏
//将灯的图片在视图上布局,5行5列 for (int i = 0; i < 5; i++) { for (int j = 0 ; j < 5; j++) { UIButton *lightButton = [UIButton buttonWithType:UIButtonTypeSystem]; lightButton.frame = CGRectMake(i * 64, 120 + (j *64), 64, 64); [lightButton setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal]; [lightButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; [self.window addSubview:lightButton]; lightButton.tag = 100 + j + 10 * i;//左右button的tag相差1,上下button的tag相差10 } }
//button的点击事件 - (void)click:(UIButton *)button { //定义数组存储所点击的button和他的上下左右的button int array[5] = {button.tag , button.tag + 1, button.tag + 10, button.tag - 1, button.tag - 10}; //判断当前buton的背景图片是不是亮灯(2.png是亮等图片名) if ([button.currentBackgroundImage isEqual:[UIImage imageNamed:@"2.png"]]) { //遍历数组 for (int i = 0; i < 5; i++) { UIButton *aButton = (UIButton*)[self.window viewWithTag:array[i]]; //判断所点击button的前后左右button的状态,如果是灭着的灯就将其背景图片变为亮着的灯(1.png是灭着的灯的图片) if ([aButton.currentBackgroundImage isEqual:[UIImage imageNamed:@"1.png"]]) { [ aButton setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal]; } else { [aButton setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal]; } } //else判断当前buton的背景图片是不是灭灯 } else { for (int i = 0; i < 5; i++) { UIButton *aButton = (UIButton*)[self.window viewWithTag:array[i]]; if ([aButton.currentBackgroundImage isEqual:[UIImage imageNamed:@"2.png"]]) { [ aButton setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal]; } else [aButton setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal]; } } }
OC实现简单的关灯游戏
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。