# 用Swift写围棋App－09分片算法

tags: Apps, 开发随笔

capt3a.png

capt3b.png

1.识别哪些棋是连成片的；
2.计算每一片棋的气（liberty），liberty == 0,则整片棋都死掉；

`````` func testIsConnected(){
let m1 = Move(step:"B[aa]")
let m2 = Move(step:"B[ab]")
let m3 = Move(step:"W[ba]")
assert(m1.isConnectedTo(m2),"m1 is connected to m2")
assert(!m1.isConnectedTo(m3),"m1 is not connected to m3")
}
``````

``````func isConnectedTo(another:Move)->Bool{
if (self.type != another.type) {
return false
}
let deltaX = abs(Int(self.location.x) - Int(another.location.x))
let deltaY = abs(Int(self.location.y) - Int(another.location.y))
return deltaX + deltaY == 1
}

``````

``````func testAssignedGroups(){
let kifu = "(;;B[aa];W[ab];B[ca];W[bb];B[ba])"
let game = parser.parse(kifu)
game.currentMove = 4
let groups = game.assignGroups()
assert(groups.count == 2)
assert(game.allMoves[0].groupName == "B1")
assert(game.allMoves[2].groupName == "B1")
assert(game.allMoves[1].groupName == "W2")
}
``````

``````func assignGroups() ->[MoveGroup]{
let array = currentMoves().sort({ \$0.location.distance() < \$1.location.distance() })
let count = array.count
var groups = [MoveGroup]()
var groupIndex = 0

for  move in array
{
move.groupName = ""
}

for var i = 0;i < count; i++
{
let move = array[i]
if  move.groupName.characters.count > 0
{continue}

for previous in array[0..<i]
{
if previous.groupName.characters.count > 0
&& move.isConnectedTo(previous){
move.groupName = previous.groupName;
}
}

if  move.groupName.characters.count > 0
{
continue
}
groupIndex += 1
let group = MoveGroup()
group.type = move.type
group.sequence = groupIndex
group.name = "\(group.type.rawValue)\(group.sequence)"
groups.append(group)

}
return groups;
}
``````

``````            if move.groupName.characters.count > 0 {
//CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1.0, -1.0))
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1)
let p = CGPointMake((CGFloat(move.location.x)+0.5)*stoneSize,(CGFloat(move.location.y)+0.5)*stoneSize);
(move.groupName as NSString).drawAtPoint(p, withAttributes:textFontAttributes)
}
}
``````

Simulator Screen Shot 1 Jan 2016, 3.47.50 PM.png