Analytics Vidhya
Published in

Analytics Vidhya

Five Steps to Create a Chess App 3/5

Step 3: drawing the chess board

Step 1 created the app and step 2 put a view on screen. Now let’s draw the 8x8 chess board. We need to create a file to put our code in.

Click “Chess” folder on the left navigation panel and it turns blue. Right click to show the menu.

right click the blue row with “Chess”

Select “New File…” to create a new file.

click “New File…”

Select “Cocoa Touch Class” under “iOS”. Then click “Next” button to continue.

click “Next” button to create a new class

Name our new class “BoardView”. Make sure it is the subclass of UIView.

Subclass of: UIView

Accept the default location and click “Create” button.

click “Create” button to create our new class file

The new class file is BoardView.swift. Now we need to set the class of our canvas, the white view in Main.storyboard, to BoardView. Click “Main.storyboard” on the left navigation panel.

click “Main.storyboard” on the left navigation panel to show Main.storyboard

With our white view selected, find the credit card like icon near the top right corner. Click it so we can change Class from UIView to our own BoardView.

from the drop down menu select “BoardView”

And we can see on the left pane that “View” becomes “Board View”. Click the 3rd icon from right on the top bar to show the left navigation panel in case it was hidden.

click the icon near top right to show navigation panel

Go back to BoarView.swift to input source code shown below. The execution entry point is the Xcode provided function “draw”. We created 3 functions to do the job of drawing 64 squares. Sorry for the hardcoded value 80, which is the side of each square. Remember we set the board size 640x640 on purpose when we added the white canvas view onto the big yellow view?

the complete code of BoardView.swift

Launch the app to view our gorgeous board view.

chess board with 8x8 squares

And here is the text version of BoardView, for your convenience.

import UIKitclass BoardView: UIView {    override func draw(_ rect: CGRect) {
func drawBoard() {
drawTwoRowsAt(y: 0 * 80)
drawTwoRowsAt(y: 2 * 80)
drawTwoRowsAt(y: 4 * 80)
drawTwoRowsAt(y: 6 * 80)

func drawTwoRowsAt(y: CGFloat) {
drawSquareAt(x: 1 * 80, y: y)
drawSquareAt(x: 3 * 80, y: y)
drawSquareAt(x: 5 * 80, y: y)
drawSquareAt(x: 7 * 80, y: y)

drawSquareAt(x: 0 * 80, y: y + 80)
drawSquareAt(x: 2 * 80, y: y + 80)
drawSquareAt(x: 4 * 80, y: y + 80)
drawSquareAt(x: 6 * 80, y: y + 80)

func drawSquareAt(x: CGFloat, y: CGFloat) {
let path = UIBezierPath(rect: CGRect(x: x, y: y, width: 80, height: 80))



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