導讀
五子棋是程式猿比較熟悉的一款小遊戲,相信很多人大學時期就用多種語言寫過五子棋小遊戲.筆者工作閒暇之餘,試著用OC實現了一下,在這裡給大家分享一下.有不足之處,歡迎大家提供建議和指點!!!GitHub原始碼連結https://github.com/HelloYeah/Gomoku-Game
先上效果圖
- 功能展示
- 初高階棋盤切換效果
實現思路及主要程式碼詳解
1.繪製棋盤
利用Quartz2D繪製棋盤.程式碼如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
- (void)drawBackground:(CGSize)size{ self.gridWidth = (size.width - 2 * kBoardSpace) / self.gridCount; //1.開啟影象上下文 UIGraphicsBeginImageContext(size); //2.獲取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(ctx, 0.8f); //3.1 畫16條豎線 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); } //3.1 畫16條橫線 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); //4.獲取生成的圖片 UIImage *image=UIGraphicsGetImageFromCurrentImageContext(); //5.顯示生成的圖片到imageview UIImageView * imageView = [[UIImageView alloc]initWithImage:image]; [self addSubview:imageView]; UIGraphicsEndImageContext(); } |
2.點選棋盤落子
1.根據落子位置求出該棋子的行號與列號.
2.判斷落子位置是否已經有棋子,有則不能下.如果沒有,將棋子儲存在字典中,以列號和行號組合起來的字串為key值.
程式碼如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//點選棋盤,下棋 - (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個同色的棋子連成一線,有則提示遊戲輸贏結果,無則遊戲繼續.演算法為,從當前棋子位置向前遍歷,直到遇到與自己不同色的棋子,累加同色棋子的個數,再往後遍歷,直到遇到與自己不同色的棋子,累加同色棋子的個數.得到該方向相連同色棋子的總個數
程式碼如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
//判斷是否大於等於五個同色相連 - (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 = 5) { [self alertResult]; return YES; } [self.sameChessmanArray removeAllObjects]; } break; case GmkVertical:{ //向前遍歷 for (NSInteger i = row - 1; i > 0; i --) { NSString * key = [NSString stringWithFormat:@"%ld-%ld",col,i]; if (![self.chessmanDict.allKeys containsObject:key] || [self.chessmanDict[key] backgroundColor] != currentChessmanColor) break; [self.sameChessmanArray addObject:self.chessmanDict[key]]; } //向後遍歷 for (NSInteger i = row + 1; i = 5) { [self alertResult]; return YES; } [self.sameChessmanArray removeAllObjects]; } break; case GmkObliqueDown:{ //向前遍歷 NSInteger j = col - 1; for (NSInteger i = row - 1; i >= 0; i--,j--) { NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i]; if (![self.chessmanDict.allKeys containsObject:key] || [self.chessmanDict[key] backgroundColor] != currentChessmanColor || j kGridCount) break; [self.sameChessmanArray addObject:self.chessmanDict[key]]; } if (self.sameChessmanArray.count >= 5) { [self alertResult]; return YES; } [self.sameChessmanArray removeAllObjects]; } break; case GmkObliqueUp:{ //向前遍歷 NSInteger j = col + 1; for (NSInteger i = row - 1; i >= 0; i--,j++) { NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i]; if (![self.chessmanDict.allKeys containsObject:key] || [self.chessmanDict[key] backgroundColor] != currentChessmanColor || j > kGridCount) break; [self.sameChessmanArray addObject:self.chessmanDict[key]]; } //向後遍歷 j = col - 1; for (NSInteger i = row + 1 ; i = 5) { [self alertResult]; return YES; } [self.sameChessmanArray removeAllObjects]; } break; } return NO; } |
4.對外提供,重新開始,悔棋,切換初高階棋盤的三個介面
重新開始
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- (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; } |
悔棋
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//撤回至上一步棋 - (void)backOneStep:(UIButton *)sender{ if(self.isOver) return; if (self.lastKey == nil) { sender.enabled = NO; CGFloat width = SCREEN_WIDTH * 0.4 * SCREEN_WIDTH_RATIO; UIView * tip = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 0.6 * width)]; tip.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8]; tip.layer.cornerRadius = 8.0f; [self addSubview:tip]; tip.center = CGPointMake(self.width * 0.5, self.height * 0.5); UILabel * label = [[UILabel alloc]init]; label.text = self.chessmanDict.count > 0 ? @"只能悔一步棋!!!" : @"請先落子!!!"; label.font = [UIFont systemFontOfSize:15]; [label sizeToFit]; label.center = CGPointMake(tip.width * 0.5, tip.height * 0.5); [tip addSubview:label]; self.userInteractionEnabled = NO; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.userInteractionEnabled = YES; sender.enabled = YES; [tip removeFromSuperview]; }); return; } [self.chessmanDict removeObjectForKey:self.lastKey]; [self.subviews.lastObject removeFromSuperview]; self.isBlack = !self.isBlack; self.lastKey = nil; } |
切換初高階鍵盤
1 2 3 4 5 6 7 8 9 10 |
//改變鍵盤級別 - (void)changeBoardLevel{ for (UIView * view in self.subviews) { [view removeFromSuperview]; } [self newGame]; self.isHighLevel = !self.isHighLevel; [self drawBackground:self.bounds.size]; } |
Demo中的一個小技巧
用字典存放棋子,以棋子的列號和行號組合起來的字串為key值,value值為棋子view.這樣處理,在判斷某行某列是否有棋子就非常簡單了.
GitHub原始碼地址https://github.com/HelloYeah/Gomoku-Game