IOS点灯小游戏
来源:互联网 发布:ubuntu16.04优化 编辑:程序博客网 时间:2024/05/21 22:42
学习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; }}以上就是大致的实现步骤了,对于初学者来说还是有帮助的。哈哈 运行出来自娱自乐还是蛮有意思的。
附上截图:
1 1
- IOS点灯小游戏
- 点灯小游戏
- ios小游戏
- IOS简单关灯小游戏
- IOS关灯小游戏
- iOS之关灯小游戏
- iOS之拼图小游戏
- iOS TriLogic小游戏 教程
- 点灯小游戏 平台:VS2015 需要安装图形库EasyX(600K左右)基于C++语言的win32控制台应用程序
- 【代码笔记】iOS-钢琴小游戏
- 星星点灯
- 星星点灯
- 星星点灯
- FPGA点灯
- 点灯问题
- 星星点灯
- 点灯游戏
- S3C2440 点灯
- 消除类游戏案例:Sushi Crush(二)
- Eclipse Resin 运行Java Application配置(基于J2EE Web Application)过程
- 疯狂Java之学习笔记(22)------------抽象类和接口
- Linux编程学习之Posix信号量
- Freemaker遍历map注意事项
- IOS点灯小游戏
- 未能加载文件或程序集“Oracle.DataAccess”或它的某一个依赖项。试图加载格式不正确的程序。
- ECLIPSE支持多个JDK版本共存的设置
- 使用递归判断一个数组是否为升序
- JNDI和数据库连接池
- SqlServer 审核(脚本示例)
- 深入Java集合学习系列:ArrayList的实现原理
- childNodes,children和noteType
- UVaOJ 674 Coin Change