lifewahaha

学习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;}}以上就是大致的实现步骤了,对于初学者来说还是有帮助的。哈哈 运行出来自娱自乐还是蛮有意思的。

附上截图:

失败是成功的亲娘,没有失败哪来的成功呢?诺贝尔如果不经历千万次的失败,

lifewahaha

相关文章:

你感兴趣的文章:

标签云: