//
// ViewController.m
// 10-拼图
//
// Created by mac on 15-5-9.
// Copyright (c) 2015年 itcast. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
/**
* 判断tag位置的button是否有图片
*
*/
-(Boolean)isKong:(int)tag
{
if(tag <= 9 && tag >= 1)
{
// - (UIView *)viewWithTag:(NSInteger)tag;
// @property(nonatomic,readonly,retain) UIImage *currentBackgroundImage;
//取tag位置的button
UIButton *mybutton = (UIButton *)[self.view viewWithTag:tag];
//取button的背景图片
UIImage *myImage = mybutton.currentBackgroundImage;
//如果背景图片为空,则可以把周围的图片移动过去
if (myImage == nil) {
return YES;
}
return NO;
}
return NO;
}
/**
* 移动
*/
-(void)remove:(int)tag toTag:(int)tag2
{
//取要移动到的位置button
UIButton *mybutton = (UIButton *)[self.view viewWithTag:tag2];
//取点击的button
UIButton *mybutton1 = (UIButton *)[self.view viewWithTag:tag];
//点击button的图片
UIImage *myImage = mybutton1.currentBackgroundImage;
//把图片赋值给空的button
[mybutton setBackgroundImage:myImage forState:normal];
//原先有图片的button背景图片赋值为空
[mybutton1 setBackgroundImage:nil forState:normal];
}
/**
* 判断是否拼图成功
*/
-(void)success
{
int count = 0;
for (int i = 0; i < 8; i ++)
{
//取当前按钮的背景图片
UIButton *mybutton1 = (UIButton *)[self.view viewWithTag:i + 1];
UIImage *myImage = mybutton1.currentBackgroundImage;
//定义成功时该位置的图片
NSString *name = [NSString stringWithFormat:@"icon_%02d",i];
UIImage *image = [UIImage imageNamed:name];
if ([image isEqual:myImage])
{
count ++;
}
}
if (count == 8) {//r如果count 为8说明拼图成功
UILabel *myLabel = (UILabel *)[self.view viewWithTag:22];
myLabel.alpha = 1;
//拼图成功后,所有按钮不可点
for (int j = 0; j < 9; j ++)
{
UIButton *mybutton1 = (UIButton *)[self.view viewWithTag:j + 1];
[mybutton1 setEnabled:NO];
}
}
}
- (IBAction)btn:(id)sender
{
//获取tag标记
int tag = (int)[sender tag];
//判断上面有没有图片
Boolean isUP =[self isKong:tag-3];
//判断下面有没有图片
Boolean isDown =[self isKong:tag+3];
//判断左面有没有图片
Boolean isLeft =[self isKong:tag-1];
//判断右面有没有图片
Boolean isRight =[self isKong:tag+1];
//移动
if (isUP)
{
[self remove:tag toTag:(tag - 3)];
}
else if (isDown)
{
[self remove:tag toTag:(tag + 3)];
}
else if(isLeft)
{
if (tag%3 == 1) {
return;
}
[self remove:tag toTag:(tag - 1)];
}
else if(isRight)
{
if (tag%3 == 0) {
return;
}
[self remove:tag toTag:(tag + 1)];
}
[self success];
}
@end