导读
五子棋是程序猿比较熟悉的一款小游戏,相信很多人大学时期就用多种语言写过五子棋小游戏.笔者工作闲暇之余,试着用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.isBlackref="https://github.com/HelloYeah/Gomoku-Game" target="_blank">https://github.com/HelloYeah/Gomoku-Game
先上效果图
实现思路及主要代码详解1.绘制棋盘利用Quartz2D绘制棋盘.代码如下
2.点击棋盘落子1.根据落子位置求出该棋子的行号与列号.
|