使用Swift在Sprite Kit中构建棋盘游戏? [英] Building a chess board game in Sprite Kit using Swift?
问题描述
在使用Swift的Sprite Kit中,我正在尝试构建一个棋盘(实际上,它是一个象棋棋盘/瓦片网格)。所以一般来说,我应该如何创建一个方形网格板?
In Sprite Kit using Swift, I am trying to build a chess board (in actuality, a chess-like board / tile grid). So in general, how should I go about creating a square grid board?
我做了很多研究并研究了国际象棋高级概念的一些例子类似于多维数组的板,但它仍然没有真正解释如何在Sprite Kit中快速表示它,更重要的是,如何将可视化表示映射到多维数组中的字母+数字表示...
I have done a lot of research and have studied some examples of the high-level concept of chess-like boards through multi-dimensional arrays but it still doesn't really explain how to VISUALLY represent it in Sprite Kit and more importantly, how to map the visual representation to the letter+number representation in a multi-dimensional array...
有什么想法吗?
如果有人能回答上述问题中的至少一点/部分,我们将不胜感激!非常感谢您提前!
If anyone could answer at least one point/part in the above question, it would be greatly appreciated! Big thank you in advanced!
推荐答案
在SpriteKit中绘制棋盘的一种方法是在此处添加交替的白色和黑色精灵节点。适当的地点。这是一个如何做到这一点的例子。
One way to draw a chessboard in SpriteKit is to add alternating white and black sprite nodes at the appropriate locations. Here's an example of how to do that.
override func didMoveToView(view: SKView) {
self.scaleMode = .ResizeFill
// Draw the board
drawBoard()
// Add a game piece to the board
if let square = squareWithName("b7") {
let gamePiece = SKSpriteNode(imageNamed: "Spaceship")
gamePiece.size = CGSizeMake(24, 24)
square.addChild(gamePiece)
}
if let square = squareWithName("e3") {
let gamePiece = SKSpriteNode(imageNamed: "Spaceship")
gamePiece.size = CGSizeMake(24, 24)
square.addChild(gamePiece)
}
}
此方法绘制棋盘。
func drawBoard() {
// Board parameters
let numRows = 8
let numCols = 8
let squareSize = CGSizeMake(32, 32)
let xOffset:CGFloat = 50
let yOffset:CGFloat = 50
// Column characters
let alphas:String = "abcdefgh"
// Used to alternate between white and black squares
var toggle:Bool = false
for row in 0...numRows-1 {
for col in 0...numCols-1 {
// Letter for this column
let colChar = Array(alphas)[col]
// Determine the color of square
let color = toggle ? SKColor.whiteColor() : SKColor.blackColor()
let square = SKSpriteNode(color: color, size: squareSize)
square.position = CGPointMake(CGFloat(col) * squareSize.width + xOffset,
CGFloat(row) * squareSize.height + yOffset)
// Set sprite's name (e.g., a8, c5, d1)
square.name = "\(colChar)\(8-row)"
self.addChild(square)
toggle = !toggle
}
toggle = !toggle
}
}
此方法返回具有指定名称的方形节点
This method returns the square node with the specified name
func squareWithName(name:String) -> SKSpriteNode? {
let square:SKSpriteNode? = self.childNodeWithName(name) as SKSpriteNode?
return square
}
这篇关于使用Swift在Sprite Kit中构建棋盘游戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!