標籤:
學習iOSUI階段第三天掌握了一些視圖相關的技巧,於是想到做個小app來鞏固一下。
晚上沒事就做了這個點燈的小遊戲。
關於點燈遊戲的相關資訊參考百度百科。
一下是我的實現步驟:
第一步:素材準備
準備好兩張圖片作為遊戲中燈的兩種狀態,一張名為red.jpg(代表燈滅),另一張為:blue.jpg(代表燈亮)。
第二步:製作遊戲布局
遊戲布局是一個N*N的正方形,我使用了UIButton 作為燈來通過迴圈進行了一個N*N的遊戲布局。
剛開始想到了用兩層for迴圈來進行布局,但是仔細思考後發現用一層for迴圈就可以實現了。實現代碼如下:
for (int i=0; i<self.ShuLiang; i++) { UIButton *btn=[[UIButton alloc] initWithFrame: CGRectMake((i%line)*btnwidth+(i%line+1)*jx, ((i/line)+1)*jx+(i/line)*btnwidth+100, btnwidth, btnwidth)]; btn.backgroundColor=[UIColor redColor]; btn.tag=i+1; [btn setImage:[UIImage imageNamed:@"red.jpg"] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(calculate:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; }
其中self.ShuLiang 是每一關卡中燈的數量,我設定為關卡的平方數。 line是每行的數量,也就是關卡。
通過迴圈最終會在螢幕上畫出一個line*line的遊戲布局。
添加按鈕的同時給每個按鈕設定一個點擊方法,即calculate方法:
-(void)calculate:(UIButton*)ClickedButton{ [self showStepCount]; //獲得點擊的按鈕 NSLog(@"%ld",ClickedButton.tag); long index=ClickedButton.tag ; [self toggleLight:index]; if ((index-1)%self.Level!=0) { [self toggleLight:index-1]; } if (index%self.Level!=0) { [self toggleLight:index+1]; } if ((index+self.Level)<=pow(self.Level, 2)) { [self toggleLight:index+self.Level]; } if ((index-self.Level)>0) { [self toggleLight:index-self.Level]; } if ([self isWin]) { UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"恭喜" message:@"您過關啦!" delegate:self cancelButtonTitle:@"下一關" otherButtonTitles:@"重玩",@"退出", nil]; [alert show]; } ; }
calculate方法的功能就是用來判斷並改變被點擊按鈕和四周按鈕的狀態的。很簡單吧。
下面改變按鈕狀態的方法:
//改變狀態-(void)toggleLight:(NSInteger)index{ if([self.view viewWithTag:index].backgroundColor==[UIColor redColor]) { [self.view viewWithTag:(index)].backgroundColor=[UIColor blueColor]; [((UIButton*)[self.view viewWithTag:(index)]) setImage:[UIImage imageNamed:@"blue.jpg"] forState:UIControlStateNormal]; } else { [self.view viewWithTag:(index)].backgroundColor=[UIColor redColor]; [((UIButton*)[self.view viewWithTag:(index)]) setImage:[UIImage imageNamed:@"red.jpg"] forState:UIControlStateNormal]; }}
判斷按鈕全部點亮(過關)
-(BOOL)isWin{ int j=0; for(int i=0;i<self.ShuLiang;i++) { if ([self.view viewWithTag:i+1].backgroundColor==[UIColor blueColor]) { j++; } } if (j==self.ShuLiang) { return YES; } else { return NO; }}以上就是大致的實現步驟了,對於初學者來說還是有協助的。哈哈 運行出來自娛自樂還是蠻有意思的。
附上:
IOS點燈小遊戲