关灯游戏代码

来源:互联网 发布:wp7.8软件下载 编辑:程序博客网 时间:2024/04/30 10:47

 

ViewController.m 文件

- (void)viewDidLoad

{

   [super viewDidLoad];

   //循环绘制74列的view,并指定大小

   for (int i=0; i<<spanstyle="color: #0433ff">4; i++) {

       for (int j=0; j<<spanstyle="color: #0433ff">7; j++) {

          LightView *lv=[[LightView alloc]initWithFrame:CGRectMake(20+70*i, 10+65*j, 48, 48)];

          //表明每个viewtag

          lv.tag=100+10*i+j;

          [self.view addSubview:lv];

       }

   }

}

记得创建子类LightView。

LightView.h 声明文件

#import

@interface LightView :UIView

@property (assign,nonatomic) BOOLflag;//标示图形的状态true对应红旗,false对应绿旗。

@property (retain,nonatomic)UIGestureRecognizer *gr;

@end


LightView.m 实现文件

//宏定义

#define REDFLAG [UIColorcolorWithPatternImage:[UIImage imageNamed:@"h"]]

#define GREENFLAG [UIColorcolorWithPatternImage:[UIImage imageNamed:@"g"]]

 

@implementation LightView

 

@synthesize flag,gr;


 

-(id)initWithFrame:(CGRect)frame

{

    self =[super initWithFrame:frame];

    if (self){

       

      //BOOL值的默认值为假,所以得指定它的默认值为真,且图像为g

      //初始的时候指定背景图像

       self.flag=true;

      self.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"g"]];

       

       //创建单击

       self.gr=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];

       //添加手势

      [selfaddGestureRecognizer:self.gr];

       //Initialization code

   }

   return self;

}


//单击调用方法

-(void)tap:(UITapGestureRecognizer *)sender{

   NSLog(@"单击");

   //为什么要强转,不强转,类型不匹配。

       LightView *lv1=(LightView *)[self.superview viewWithTag:self.tag-1];

       LightView *lv2=(LightView *)[self.superview viewWithTag:self.tag+1];

       LightView *lv3=(LightView *)[self.superview viewWithTag:self.tag-10];

       LightView *lv4=(LightView *)[self.superview viewWithTag:self.tag+10];

   [selfchangeLight];

    [lv1changeLight];

    [lv2changeLight];

    [lv3changeLight];

    [lv4changeLight];

}

//方法

-(void)changeLight{

   //开始动画,beginAnimations:是动画名;context:是参数

   [UIView beginAnimations:nilcontext:nil];

   //动画执行1

   [UIView setAnimationDuration:1];

   //动画翻转,从右翻转

   [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRightforView:self cache:YES];

   //判断背景颜色为真的时候,图片是h,否则为假,为g

   //记住BOOL值的默认值为假

//    if(self.flag==true) {

//      self.backgroundColor=REDFLAG;

//       self.flag=false;

//   }else{

//      self.backgroundColor=GREENFLAG;

//       self.flag=true;

//   }

   //以下这两行相当于上面的if判断

   //如果为真就是REDFLAG;如果为假就是GREENFLAG;

   self.backgroundColor=self.flag?REDFLAG:GREENFLAG;

   self.flag=!self.flag;

   //执行动画

   [UIView commitAnimations];

}

@end


当然,做关灯游戏需要素材,图片什么的自己定义。这几段代码使用手势和view结合写的。当然也可以用button来写,就是把所有的view定义成button。做的比较粗糙,见谅哈!


0 0
原创粉丝点击