IOS —— 关灯游戏(纯代码,简化版)

 1 - (void)viewDidLoad
 2 {
 3     [super viewDidLoad];
 4     arr=[[NSMutableArray alloc]initWithCapacity:16];
 5  
 6     for (int i=0; i<4; i++) {
 7         for (int j=0; j<4; j++) {
 8             UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(j*60+10, i*60+100, 40, 40)];
 9             btn.backgroundColor=[UIColor lightGrayColor];
10             [btn addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
11           
12             [self.view addSubview:btn];
13             
14             [arr addObject:btn];
15         }
16     }
17    
18   
19 }
20 -(void) btn:(UIButton*)btn{
21     int i=0;
22     for (;i<16;i++) {
23         if (btn==arr[i]) {
24             break;
25         }
26     }
27     //判断位置,如果点击按钮在右边缘则不让i+1位置的按钮判断关灯与否
28     UIButton* btn1=[UIButton new];
29     if ((i+1)%4!=0) {
30         btn1=arr[i+1];
31     }
32    //判断位置,如果点击的位置在左边缘则不让i-1位置的按钮判断关灯与否
33    UIButton* btn2=[UIButton new];
34     if ((i+1)%4!=1) {
35       btn2=arr[i-1];
36     }
37     //判断位置,如果点击的位置在第一行,则不能判断i-4位置的按钮关灯与否,因为i-4没按钮可判断
38     UIButton* btn3=[UIButton new];
39     if (i>=4) {
40       btn3=arr[i-4];
41     }
42     //判断位置,如果点击的位置在最后一行,则不能判断i+4位置的按钮关灯与否,因为i+4没按钮可判断
43     UIButton* btn4=[UIButton new];
44     if (i<12) {
45         btn4=arr[i+4];
46     }
47     
48     NSArray* arr1=@[btn,btn1,btn2,btn3,btn4];
49     for (i=0; i<5;i++) {
50         UIButton* tampButton=arr1[i];
51         
52         if (tampButton.backgroundColor!= [UIColor yellowColor]) {
53             tampButton.backgroundColor=[UIColor yellowColor];
54         }
55         else {
56             tampButton.backgroundColor=[UIColor lightGrayColor];
57         }
58         
59     }
60     
61 }

 

posted on 2015-10-06 15:33  摩羯小伟  阅读(173)  评论(0编辑  收藏  举报

导航