iOS 拼圖游戲

使用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")
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容