用UIBUtton实现关灯小游戏

本文介绍如何使用Swift和UIKit实现一个简单的关灯小游戏。通过在界面上布局按钮,并实现点击按钮时灯光效果的切换,玩家可以体验到交互式的编程乐趣。此外,还提供了设置关卡的功能,增加了游戏的挑战性和可玩性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用UIButton,实现简单的关灯小游戏,

思路:1.首先用两个循环把UIButon放到View上

2,实现点击按钮,被点击的图片本身及其上下左右(tag值)的灯被点亮(可以用UIButton的UIControlStateNormal,UIControlStateSelected两个状态实现)

3.反转被点击按钮及其四周的状态

4.还可以设置关卡

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    LightOffView *lightView = [[LightOffView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    [self.view addSubview:lightView];

    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];

    image.image = [UIImage imageNamed:@"666.jpg"];

    [lightView addSubview:image];

    [lightView release];

    

       for (int i = 0; i < 6; i ++) {

        for (int j = 0; j < 8; j++) {

            UIButton *lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];lightBtn.frame = CGRectMake(30 + 55 * i, (j + 1) * 55, 55, 55);

            lightBtn.backgroundColor = [UIColor redColor];

            [lightBtn setImage:[UIImage imageNamed:@"1.png"] forState:

             UIControlStateNormal];

            [lightBtn setImage:[UIImage imageNamed:@"2.png"] forState:

             UIControlStateSelected];

            [lightBtn addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchDown];

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

            [self.view addSubview:lightBtn];

//            [self setLevel:@[@102, @101, @103]];

         }

    }

}


- (void)handleButton:(UIButton *)btn{

     btn.selected = !btn.selected;

    UIButton *leftBtn = (UIButton *)[self.view viewWithTag:btn.tag - 1];

    leftBtn.selected = !leftBtn.selected;

    UIButton *rightBtn = (UIButton *)[self.view viewWithTag:btn.tag + 1];

    rightBtn.selected = !rightBtn.selected;

    UIButton *upBtn = (UIButton *)[self.view viewWithTag:btn.tag - 10];

    upBtn.selected = !upBtn.selected;

    UIButton *downBtn = (UIButton *)[self.view viewWithTag:btn.tag + 10];

    downBtn.selected = !downBtn.selected;


}


//可以通过tag值提前让某些灯亮,以此来设置关卡

- (void)setLevel:(NSArray *)buttonsTag{

    for (NSNumber *tag in buttonsTag) {

        UIButton *lightBtn = (UIButton *)[self.view viewWithTag:[tag integerValue]];

        [self handleButton:lightBtn];

    }

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

    if ([self isViewLoaded] && !self.view.window) {

        self.view = nil;

    }

}



@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值