首先找到这8张图片,还需要一张空白的图片,自己随便剪一张吧。
定义三个属性:button可变数组,图片可变数组,正确顺序的图片数组。
@property(retain, nonatomic)NSMutableArray *buttonArray;
@property(retain, nonatomic)NSMutableArray *a;
@property(retain, nonatomic)NSArray *aa;
铺好拼图界面
//图片数组a,用来储存每个图片名称,并且用于后来的打乱
self.a = [NSMutableArray arrayWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg",@"7.jpg",@"8.jpg",@"9.jpg", nil];
//备份一个正确顺序的图片数组,用于判断游戏是否过关
self.aa = [NSArray arrayWithArray:self.a];
//重新开始按钮
UIButton *star = [[UIButton alloc] initWithFrame:CGRectMake(120, 400, 100, 40)];
[star setTitle:@"重新开始" forState:UIControlStateNormal];
[star setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
star.layer.cornerRadius = 6.6f;
star.layer.backgroundColor = [[UIColor colorWithRed:0.922 green:0.925 blue:0.929 alpha:1]CGColor];
//添加点击事件
[star addTarget:self action:@selector(kaishi) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:star];
[star release];
//铺出9个button
self.buttonArray = [NSMutableArray array];
NSInteger count = 0;
NSInteger wight = 351 / 3;
NSInteger higth = 351 / 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(j * (wight+2) + 10, i * (higth + 2) + 20, wight, higth)];
button.backgroundColor = [UIColor blackColor];
//给每个button上图片
[button setImage:[UIImage imageNamed:self.a[count]] forState:UIControlStateNormal];
[self.view addSubview:button];
//给每个button添加点击事件
[button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];
//把button放入数组
[self.buttonArray addObject:button];
button.tag = count;
[button release];
count++;
}
}
实现button的点击事件
- (void)change:(UIButton *)sender{
NSInteger flag = 0;
int p = 0;
//“9.jpg”是空白的那个,打乱后,得在图片数组里找到所在下标,用flag存在来
for (NSInteger i = 0; i < 9; i++) {
if ([self.a[i] isEqualToString:@"9.jpg"]) {
flag = i;
}
}
//如果所点击的button的上下左右其中有一个是空白图片的话,就跟空白图片交换在图片数组的位置
if (sender.tag - flag == 3 || sender.tag - flag == -3 || sender.tag - flag == 1 || sender.tag - flag == -1) {
[self.a exchangeObjectAtIndex:flag withObjectAtIndex:sender.tag];
}
//重新给每个button上图片
for (int i = 0; i < 9; i++) {
[self.buttonArray[i] setImage:[UIImage imageNamed:self.a[i]] forState:UIControlStateNormal];
}
//判断是否拼图成功,每对应了一张图片p就加一,如果p最后等于9说明游戏通关
for (int i = 0; i < 9 ; i++) {
if ([self.a[i] isEqualToString:self.aa[i]]) {
p++;
}else{
break;
}
}
if (p == 9) {
NSLog(@"%d",p);
UIAlertView *a = [[UIAlertView alloc] initWithTitle:@"恭喜!" message:@"已通关" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[a show];
[a release];
}
}
打乱所有图片
- (void)kaishi{
//产生0到8两个随机数,通过下标交换图片数组中的两张图片
for (int i = 0; i < 10; i++) {
[self.a exchangeObjectAtIndex:(arc4random() % 9)
withObjectAtIndex:(arc4random() % 9)];
}
//给每个button上图片
for (int i = 0; i < 9; i++) {
[self.buttonArray[i] setImage:[UIImage imageNamed:self.a[i]] forState:UIControlStateNormal];
}
}
。。。
完成