您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 遊戲開發:Objective-C 版五子棋

編輯:iOS 開發綜合

效果展示

1. 繪製棋盤

利用 Quartz2D 繪製棋盤格線,先開啟圖像上下文,畫出縱橫各 16 條線,再將生成的圖片顯示到 imageView:

- (void)drawBackground:(CGSize)size {
    self.gridWidth = (size.width - 2 * kBoardSpace) / self.gridCount;
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, 0.8f);
    for (int i = 0; i <= self.gridCount; i++) {
        CGContextMoveToPoint(ctx, kBoardSpace + i * self.gridWidth, kBoardSpace);
        CGContextAddLineToPoint(ctx, kBoardSpace + i * self.gridWidth, kBoardSpace + self.gridCount * self.gridWidth);
    }
    for (int i = 0; i <= self.gridCount; i++) {
        CGContextMoveToPoint(ctx, kBoardSpace, kBoardSpace + i * self.gridWidth);
        CGContextAddLineToPoint(ctx, kBoardSpace + self.gridCount * self.gridWidth, kBoardSpace + i * self.gridWidth);
    }
    CGContextStrokePath(ctx);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self addSubview:imageView];
    UIGraphicsEndImageContext();
}

2. 點擊落子

依落子座標計算行號與列號,若該位置尚無棋子,則建立棋子並以「列-行」組成的字串為 key 存入字典,最後檢查輸贏:

- (void)tapBoard:(UITapGestureRecognizer *)tap {
    CGPoint point = [tap locationInView:tap.view];
    NSInteger col = (point.x - kBoardSpace + 0.5 * self.gridWidth) / self.gridWidth;
    NSInteger row = (point.y - kBoardSpace + 0.5 * self.gridWidth) / self.gridWidth;
    NSString *key = [NSString stringWithFormat:@"%ld-%ld", col, row];
    if (![self.chessmanDict.allKeys containsObject:key]) {
        UIView *chessman = [self chessman];
        chessman.center = CGPointMake(kBoardSpace + col * self.gridWidth, kBoardSpace + row * self.gridWidth);
        [self addSubview:chessman];
        [self.chessmanDict setValue:chessman forKey:key];
        self.lastKey = key;
        [self checkResult:col andRow:row andColor:self.isBlack];
        self.isBlack = !self.isBlack;
    }
}

3. 檢查勝負

每落一子便檢查水平、垂直與兩條斜線共四個方向,是否有一側連成五子以上同色。做法是從當前棋子向前、向後兩個方向遍歷,累加同色棋子數量,若總數達到 5 便提示勝負:

- (BOOL)checkResult:(NSInteger)col andRow:(NSInteger)row andColor:(BOOL)isBlack andDirection:(GmkDirection)direction {
    if (self.sameChessmanArray.count >= 5) {
        return YES;
    }
    UIColor *currentChessmanColor = [self.chessmanDict[[NSString stringWithFormat:@"%ld-%ld", col, row]] backgroundColor];
    [self.sameChessmanArray addObject:self.chessmanDict[self.lastKey]];
    switch (direction) {
        case GmkHorizontal: {
            // 向前遍歷
            for (NSInteger i = col - 1; i > 0; i--) {
                NSString *key = [NSString stringWithFormat:@"%ld-%ld", i, row];
                if (![self.chessmanDict.allKeys containsObject:key] || [self.chessmanDict[key] backgroundColor] != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            // 向後遍歷
            for (NSInteger i = col + 1; i < kGridCount; i++) {
                NSString *key = [NSString stringWithFormat:@"%ld-%ld", i, row];
                if (![self.chessmanDict.allKeys containsObject:key] || [self.chessmanDict[key] backgroundColor] != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            if (self.sameChessmanArray.count >= 5) { [self alertResult]; return YES; }
            [self.sameChessmanArray removeAllObjects];
        } break;
        // Vertical / ObliqueDown / ObliqueUp 方向同理,依對角座標增減遍歷
    }
    return NO;
}

對外接口

重新開始:清空所有狀態與棋子,重設輪流順序。

- (void)newGame {
    self.isOver = NO;
    self.lastKey = nil;
    [self.sameChessmanArray removeAllObjects];
    self.userInteractionEnabled = YES;
    [self.chessmanDict removeAllObjects];
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) { continue; }
        [view removeFromSuperview];
    }
    self.isBlack = NO;
}

悔棋:移除最後一手棋子並切換回上一手方;若無子可悔或已結束,則以浮層提示。

切換棋盤等級:清除畫面後重新開局,切換 isHighLevel 並重繪棋盤。

- (void)changeBoardLevel {
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    [self newGame];
    self.isHighLevel = !self.isHighLevel;
    [self drawBackground:self.bounds.size];
}

小技巧

以字典存放棋子、以「列-行」字串為 key、棋子 view 為 value,讓「判斷某行某列是否有棋子」變得非常直覺,是這個 Demo 中值得借鏡的設計。

小結

以上就是 iOS 五子棋(OC 版)的完整實作,涵蓋棋盤繪製、落子、四方向勝負判斷與重新開始、悔棋、切換棋盤等接口,希望對你的開發有所幫助,若有不足之處歡迎提出建議。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved