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?
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...
Any thoughts?
If anyone could answer at least one point/part in the above question, it would be greatly appreciated! Big thank you in advanced!
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)
}
}
This method draws the chessboard.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With