使用UICollectionView實(shí)現(xiàn)簡(jiǎn)單的拼圖游戲,思路就是使用有圖的cell與空白的cell進(jìn)行交換

初始化截圖

游戲勝利截圖
首先定義model類(lèi)并實(shí)現(xiàn)相應(yīng)的方法
//初始化
- (instancetype)initWithSerie:(NSInteger)serie;
//一二維轉(zhuǎn)換
- (NSInteger)indexWithPoint:(CGPoint)point;
- (CGPoint)pointWithIndex:(NSInteger)index;
//設(shè)置勝利數(shù)組
- (void)setWinArr;
//設(shè)置游戲數(shù)組
- (void)setPlayArr;
//設(shè)置空白位置
//- (void)removeNumber:(NSInteger)num;
- (BOOL)isWin;
//交換位置
- (void)changeLocation:(CGPoint)cPoint :(CGPoint)wPoint;
//返回基點(diǎn)
- (CGPoint)upPoint;
- (CGPoint)downPoint;
- (CGPoint)leftPoint;
- (CGPoint)rightPoint;
//判斷是否越界
- (BOOL)isUpOut:(CGPoint)point;
- (BOOL)isDownOut:(CGPoint)point;
- (BOOL)isLeftOut:(CGPoint)point;
- (BOOL)isRightOut:(CGPoint)point;
//控制器
- (void)up;
- (void)down;
- (void)left;
- (void)right;
- (void)Key;
Controller代碼
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.TextField.text integerValue]*[self.TextField.text integerValue];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UIImageView *image = (UIImageView *)[cell viewWithTag:1];
NSString *str = [NSString stringWithFormat:@"%@", _puz.playArr[indexPath.row]];
image.image = [UIImage imageNamed:str];
return cell;
}
- (IBAction)TextDidEndOnExit:(id)sender
{
self.puz = [[puzzle alloc] initWithSerie:[self.TextField.text integerValue]];
[self.CollectionView reloadData];
}
- (IBAction)UpButton:(id)sender
{
[self.puz up];
[self.CollectionView reloadData];
}
- (IBAction)DownButton:(id)sender
{
[self.puz down];
if ([_puz isWin]) {
alert(@"恭喜你通關(guān)了!", @"ok")
}
[self.CollectionView reloadData];
}
- (IBAction)LeftButton:(id)sender
{
[self.puz left];
[self.CollectionView reloadData];
}
- (IBAction)RightButton:(id)sender
{
[self.puz right];
if ([_puz isWin]) {
alert(@"恭喜你通關(guān)了!", @"ok")
}
[self.CollectionView reloadData];
}
- (IBAction)KeyButton:(id)sender
{
[self.puz Key];
[self.CollectionView reloadData];
if ([_puz isWin]) {
alert(@"恭喜你通關(guān)了!", @"ok")
}
}