我有另一种方法,目前似乎正在起作用:
//如果你必须轮流进行,你可以重复使用白色磁盘循环和黑色磁盘。我使用.name来识别选择了哪个方格。
func drawBoard() {
let numRows = 8
let numCols = 8
let x = scene?.size.width
xOffset = ((x)! - ((x)! / 9) * CGFloat(numCols))
squareSize = CGSizeMake(x!/9, x!/9)
diskSize = CGSizeMake(x!/11, x!/11)
for row in 0...numRows-1 {
for col in 0...numCols-1 {
square = SKSpriteNode(texture: SKTexture(imageNamed: "square.png"), size: squareSize!)
square!.name = "square \(col)-\(row)"
square!.userInteractionEnabled = false
square!.position = CGPointMake(CGFloat(col) * squareSize!.width + xOffset, CGFloat(row) * squareSize!.height + xOffset)
self.addChild(square!)
}
}
for row in 0...numRows-1 {
for col in 0...numCols-1 {
let gamePiece = SKSpriteNode(texture: SKTexture(imageNamed: "whitedisk.png"), size: diskSize!)
gamePiece.name = "whitedisk \(col)-\(row)"
gamePiece.userInteractionEnabled = false
gamePiece.position = CGPointMake(CGFloat(col) * squareSize!.width + xOffset, CGFloat(row) * squareSize!.height + xOffset)
gamePiece.hidden = true
self.addChild(gamePiece)
}
}
}
// 磁盘变量取决于轮到谁,可能是白色磁盘或黑色磁盘
此函数确定选择了哪个方格后显示游戏棋子
func placeDisk(name: String, disk: String) {
var myName = name
let theDisk = disk
myName = myName.stringByReplacingOccurrencesOfString("square", withString: theDisk)
let node = self.childNodeWithName(myName)
node?.hidden = false
}
// 我覆盖了touchesEND函数但你也可以使用touchesBegan
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let positionInScene = touch.locationInNode(self)
let name = self.nodeAtPoint(positionInScene).name
if name != nil {
print("Touched: \(name)")
placeDisk(name!, disk: "whitedisk")
}
}
}