How To Make a Letter / Word Game with UIKit and Swift: Part 1/3
This 3-part tutorial series will guide you through the process of building a board game for the iPad in Swift, where you create words with letters. You’ll also learn about best practices for creating solid, modular iOS apps. And as a bonus, you’ll get a crash course in audio-visual effects with UIKit! By Caroline Begbie.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
How To Make a Letter / Word Game with UIKit and Swift: Part 1/3
35 mins
- Getting Started: Introducing Anagrams
- The Starter Project
- 1) Load the Level Config File
- 2) Create a Game Controller Class
- 3) Create an Onscreen View
- 4) Create a Tile View
- 5) Dealing the Tiles on the Screen
- 6) Add the Letters
- 7) Slightly Rotate the Letters Randomly
- 8) Add the Targets
- Where to Go from Here?
7) Slightly Rotate the Letters Randomly
Randomization is one of the keys to building a successful computer game. You want to randomize your game as much as possible. For example, no player enjoys enemies that all do the same thing every time the game runs.
In the case of the Anagrams game, you can randomize the placement of each tile so that they look more natural on the game board, as if a human put them down without trying too hard to align them properly:
In order to accomplish this randomization, add the following method to the TileView class in TileView.swift:
func randomize() {
//1
//set random rotation of the tile
//anywhere between -0.2 and 0.3 radians
let rotation = CGFloat(randomNumber(minX:0, maxX:50)) / 100.0 - 0.2
self.transform = CGAffineTransformMakeRotation(rotation)
//2
//move randomly upwards
let yOffset = CGFloat(randomNumber(minX: 0, maxX: 10) - 10)
self.center = CGPointMake(self.center.x, self.center.y + yOffset)
}
This code does two things:
- It generates a random angle between -0.2 and 0.3 radians (using the helper function
randomNumber
defined in Config.swift). Then it callsCGAffineTransformMakeRotation()
to create a new transform for the tile view that will rotate it around its center by that random angle. - It generates a random value between -10 and 0 and moves the tile up by that offset.
Note: You might want to replace all of these numbers with constants you define in Config.swift so you can fine-tune the tile appearance more easily.
Note: You might want to replace all of these numbers with constants you define in Config.swift so you can fine-tune the tile appearance more easily.
Now you just need to call this method. Inside GameController.swift, edit dealRandomAnagram()
by adding the following line of code just after the line that begins with tile.center = ...
:
tile.randomize()
And that’s all it takes! Hit run again to see the randomized tiles on the board:
Using what you’ve already achieved, you can also quickly add the targets to the game board. Let’s do that before wrapping up this part of the tutorial.
8) Add the Targets
The target views are pretty similar to the tile views. They also subclass UIImageView
and show a default image, and they also are assigned a letter. The difference is that they don’t show a label with that letter and can’t be dragged around. This means the code you need for the targets is similar to what you did before – but simpler!
Inside the file group Anagram/Classes/Views, create a new Swift file called TargetView
. Add the following to TargetView.swift:
import UIKit
class TargetView: UIImageView {
var letter: Character
var isMatched:Bool = false
//this should never be called
required init(coder aDecoder:NSCoder) {
fatalError("use init(letter:, sideLength:")
}
init(letter:Character, sideLength:CGFloat) {
self.letter = letter
let image = UIImage(named: "slot")!
super.init(image:image)
let scale = sideLength / image.size.width
self.frame = CGRectMake(0, 0, image.size.width * scale, image.size.height * scale)
}
}
Yes, this uses exactly the same properties and function (aside from changing the image) as for the TileView
! You resize the image according to the provided side length and assign the letter – that’s all.
Now to display the targets on the screen. Open up GameController.swift and add the following property to the class:
private var targets = [TargetView]()
Then add the following code inside dealRandomAnagram()
, just before the comment that reads “//1 initialize tile list”:
//initialize target list
targets = []
//create targets
for (index, letter) in enumerate(anagram2) {
if letter != " " {
let target = TargetView(letter: letter, sideLength: tileSide)
target.center = CGPointMake(xOffset + CGFloat(index)*(tileSide + TileMargin), ScreenHeight/4)
gameView.addSubview(target)
targets.append(target)
}
}
This is almost the same code you used to deal the tiles on the board, except this time you grab the letters from the phrase stored in anagram2
and you don’t randomize their position. You want the target views to look nice and neat, after all!
Why does the target initialization have to come before the tile initialization? Subviews are drawn in the order they are added to their parent view, so adding the target views first ensures that they will appear behind, or below, the tiles.
If you did want to add the target views after the tile views, there are other ways to get them behind the tiles, such as UIView
‘s sendSubviewToBack(view:)
method. But adding them first is the most efficient solution.
Build and run again to see that your board is already close to being finished!
Remember, the anagrams consist of two phrases which have the same letters but might have different spacing. So everything is working as expected if you see something like the screenshot above with three tiles followed by four tiles, while the targets at the top are four tiles followed by three tiles.
Where to Go from Here?
Click here to download the full source code for the project up to this point.
Congrats, you’ve achieved a lot today! Let’s see what you’ve done so far:
- You’ve created a model to load the level configuration.
- You’ve connected the game controller, game view and model.
- You have two custom views, one for tiles and one for targets.
- You’ve finished the initial board setup.
You now have a sound foundation on which to build. Stay tuned for Part 2 of the series, where you’ll begin interacting with the player and building up the gameplay.
In the meantime, if you have any questions or comments about what you’ve done so far, drop by the forums to contribute your two tiles’ worth. :]