关灯闭灯游戏

来源:互联网 发布:现货白银行情分析软件 编辑:程序博客网 时间:2024/05/16 06:58

开灯闭灯: 创建几乘几的按钮(灯), 通过点击任意的按钮实现本身和其所对应的上下左右的按钮状态发生改变(关灯, 闭灯).

1.创建几乘几的按钮(灯), 给每个button一个tag值

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

// 设置行列的按钮的个数
#define o 11
#define q 11

NSInteger count = 100;
for (int i = 0; i < q; i++) {
for (int j = 0; j < o; j++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag = count;
button.frame = CGRectMake(WIDTH / o * j, WIDTH / o * i + 100, WIDTH / o - 3, WIDTH / o - 3);
button.backgroundColor = [UIColor greenColor];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[_window addSubview:button];
count += 100;
}
}



2.判断所点击的按钮. (可以用其坐标或其中心点来获取其对应上下左右的按钮, 这里利用tag进行判断,所以还要注意按钮组成方阵的按钮组, 最上一排所对应的上面没有按钮, 同样其最左面, 右面, 下面没有相应的按钮).

- (void)buttonAction:(UIButton *)sender{
NSUInteger buttonTag = sender.tag;
if (buttonTag > o * 100) {
UIButton *upButton = (UIButton *)[_window viewWithTag:buttonTag - o * 100];
[self upButtonBackgroundColorForSelectedButton:upButton];
}

if (buttonTag > 100 && buttonTag % (o * 100) != 100) {
UIButton *leftButton = (UIButton *)[_window viewWithTag:buttonTag - 100];
[self leftButtonBackgroundColorForSelectedButton:leftButton];
}

UIButton *downButton = (UIButton *)[_window viewWithTag:buttonTag + o * 100];
if (buttonTag % (o * 100) != 0) {
UIButton *rightButton = (UIButton *)[_window viewWithTag:buttonTag + 100];
[self rightButtonBackgroundColorForSelectedButton:rightButton];
}

[self clickButtonBackgroundColorForSelectedButton:sender];
[self downButtonBackgroundColorForSelectedButton:downButton];
}



3.改变点击按钮后, 对需要改变的按钮进行改变颜色(关灯闭灯的状态) 

- (void)clickButtonBackgroundColorForSelectedButton:(UIButton *)button{
if (button.backgroundColor == [UIColor greenColor]) {
button.backgroundColor = [UIColor redColor];
}else{
button.backgroundColor = [UIColor greenColor];
}
}
- (void)upButtonBackgroundColorForSelectedButton:(UIButton *)upButton{
if (upButton.backgroundColor == [UIColor greenColor]) {
upButton.backgroundColor = [UIColor redColor];
}else{
upButton.backgroundColor = [UIColor greenColor];
}
}

- (void)downButtonBackgroundColorForSelectedButton:(UIButton *)downButton{
if (downButton.backgroundColor == [UIColor greenColor]) {
downButton.backgroundColor = [UIColor redColor];
}else{
downButton.backgroundColor = [UIColor greenColor];
}
}

- (void)leftButtonBackgroundColorForSelectedButton:(UIButton *)leftButton{
if (leftButton.backgroundColor == [UIColor greenColor]) {
leftButton.backgroundColor = [UIColor redColor];
}else{
leftButton.backgroundColor = [UIColor greenColor];
}
}

- (void)rightButtonBackgroundColorForSelectedButton:(UIButton *)rightButton{
if (rightButton.backgroundColor == [UIColor greenColor]) {
rightButton.backgroundColor = [UIColor redColor];
}else{
rightButton.backgroundColor = [UIColor greenColor];
}
}



0 0
原创粉丝点击