A swift game of Chess, part I

Like many of the readers here, I watched the WWDC 2017 session on the new drag & drop methods available within iOS 11.x with interest quietly reflecting as I did on what sort of simple app could I build to get some hands-on experience of these new methods.

It was while playing chess with my son that I had a eureka moment. I know I thought I write a simple online game of chess, an app that would require me to drag images around the screen, chess pieces in this case. So on Sunday afternoon I put this together and thought I would share the story you in the process.

Let’s start with an image, this was my goal; and will be the end result if you manage to follow this short tutorial too.

Image for post
Image for post

It is a little rough around the edges, but it’s the concept/code that counts. Of course, not evident from this image, but you can drag and drop the chess pieces around the board.

To build this you need first create a single view application and get some images. One of my favorite websites for this sort of thing is https://thenounproject.com where they claim to have “Icons for everything.” I foundand download a chess set made by jhonythomasang@gmail.com and went from there, it is his chess pieces you see in the image above.

I copied the images into the Assets.xcassets and create a simple loop within my viewDidLoad to build a board and place the pieces within it. The code looks like this.

var image2M: UIImageView!
var image2A:[UIImageView] = []

var sourceIndex: Int!
var objectIndex: Int!
let cpieces = [0:”wCastle”,1:”wKnight”,2:”wBishop”,3:”wQueen”,4:”wKing”,5:”wBishop”,6:”wKnight”,7:”wCastle”,8:”wPawn”,9:”wPawn”,10:”wPawn”,11:”wPawn”,12:”wPawn”,13:”wPawn”,14:”wPawn”,15:”wPawn”,48:”bPawn”,49:”bPawn”,50:”bPawn”,51:”bPawn”,52:”bPawn”,53:”bPawn”,54:”bPawn”,55:”bPawn”,56:”bCastle”,57:”bKnight”,58:”bBishop”,59:”bQueen”,60:”bKing”,61:”bBishop”,62:”bKnight”,63:”bCastle”]

var imageIndex = 0
let midX = self.view.bounds.midX — (8 * 64) / 2
let midY = self.view.bounds.midY — (8 * 64) / 2
for Xloop in 0..<8 {
for Yloop in 0..<8 {
let image2D = UIImageView(frame: CGRect(x: Int(midX + CGFloat(Xloop) * 64), y: Int(midY + CGFloat(Yloop) * 64), width: 64, height: 64))
image2D.layer.borderColor = UIColor.black.cgColor
image2D.layer.borderWidth = 1
image2D.isUserInteractionEnabled = true
image2D.tag = imageIndex
if cpieces[imageIndex] != nil {
image2D.image = UIImage(named: cpieces[imageIndex]!)
}

imageIndex = imageIndex + 1
self.view.addSubview(image2D)
image2A.append(image2D)
}
}

I want the board smack in the center of the screen the hence the view.bounds lines and I wanted to create the board as quickly and easily as I could so I simply add 64 UIImageViews to it with borders. A dictionary worked well as a means to help me place the chess pieces. The requirement for the array and the tag will be more evident as we move ahead.

On to the interesting part, if you copy and paste this code into your ViewController you’ll have nothing more than a static chess board. To make it interactive I needed to add both UIDropInteractionDelegate and UIDragInteractionDelegate to the VC.

That done you need to add these four lines in the image2D loop shown above.

let dragInteraction = UIDragInteraction(delegate: self)
image2D.addInteraction(dragInteraction)
let dropInteraction = UIDropInteraction(delegate: self)
image2D.addInteraction(dropInteraction)

And then you add your drag and drop methods.

func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
image2M = interaction.view as? UIImageView
sourceIndex = image2M.tag
let image = image2M.image
let provider = NSItemProvider(object: image!)
let item = UIDragItem(itemProvider: provider)
item.localObject = image
print(“sourceIndex \(sourceIndex)”)
return [item]
}

This captures the image being selected as well the square it is sitting on right now, with the tag for the imageView holding the index of the UIImageArray it is within.

We also need to add two more methods to capture the drop action too.

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: UIImage.self) { imageItems in
let images = imageItems as! [UIImage]
let dropLocation:CGPoint = session.location(in: self.view)
for image2X in self.image2A {
if (image2X.frame.contains(dropLocation) ) {
image2X.image = images.first
self.objectIndex = image2X.tag
print(“objectIndex \(self.objectIndex)”)
self.image2M.image = nil
}
}
}
}

This gets the image you dragged to and the dropLocation on which you need to place it. It then uses its array of squares to find the reference to the one your dropping your image onto before placing there and noting again the image index number you moved too.

func dropInteraction(_ interaction: UIDropInteraction,
sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .move)
}

Which brings us to the end… if you copy and paste this code into a new project, you should end up with a very simple chess game. Check out part II if you liked this post.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store