先上效果图
- 功能展示

- 初高级棋盘切换效果

实现思路及主要代码详解
1.绘制棋盘
利用Quartz2D绘制棋盘.代码如下
- (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值.
代码如下:
//点击棋盘,下棋
- (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;
}
}










