How To Make a Letter / Word Game with UIKit and Swift: Part 3/3

How To Make a Letter / Word Game with UIKit and Swift: Part 3/3
Learn how to create a fun anagrams game!

Learn how to create a fun anagrams game!

Update note: This tutorial was updated for Swift and iOS 8 by Caroline Begbie. Original series by Tutorial Team member Marin Todorov.

Welcome to the our tutorial series about creating a letter / word game with UIKit for the iPad.

If you successfully followed through the first and second parts of this tutorial, your game should be pretty functional. But it still lacks some key game elements and could use a bit more eye candy.

This third and final part of the series will be the most fun of them all! In this part, you’re going to be adding a lot of cool and fun features:

  • Visual effects to make tile dragging more satisfying
  • Gratuitous sound effects
  • In-game help for players
  • A game menu for choosing the difficulty level
  • And yes… explosions! :]

That’s quite a lot, so let’s once again get cracking!

Enhanced Tile Dragging: Not a Drag

When you run the completed project from Part 2 of this tutorial, you have this:

Counting Points

Your players can drag tiles around on the screen just fine, but the effect is very two-dimensional. In this section you’ll see how some simple visual effects can make the dragging experience much more satisfying.

When the player begins dragging a tile, it would be nice if the tile got a little bigger and showed a drop shadow below itself. These effects will make it look like the player is actually lifting the tile from the board while moving it.

To accomplish this effect, you’ll be using some features of the 2D graphics Quartz framework. To access this, all you have to do is add the proper import statement.

Open TileView.swift and add the following import after the other imports at the top of the file:

import QuartzCore

Now add the following code at the end of init(letter:sideLength:), just after the line where you enabled user interactions:

//create the tile shadow
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOpacity = 0
self.layer.shadowOffset = CGSizeMake(10.0, 10.0)
self.layer.shadowRadius = 15.0
self.layer.masksToBounds = false
let path = UIBezierPath(rect: self.bounds)
self.layer.shadowPath = path.CGPath

Every UIView has a property called layer – this is the CALayer instance for the lower-level drawing layer used to draw the view. Luckily CALayer has a set of properties that you can use to create a drop shadow. The property names mostly speak for themselves, but a few probably need some extra explanation.

  • masksToBounds is set to true by default, which means the layer will never render anything outside its bounds. Because a drop shadow is rendered outside of the view’s bounds, you have to set this property to false to see the shadow.
  • shadowPath is a UIBezierPath that describes the shadow shape. Use this whenever possible to speed up the shadow rendering. In the code above, you use a rectangle path (same as the tile’s bounds), but you also apply rounding to the rectangle’s corners via shadowRadius, and you effectively have a shadow with the form of the tile itself. Nice!
  • Note that you’re setting the shadowOpacity to 0, which makes the shadow invisible. So you create the shadow when the tile is initialized, but you’ll later show and hide it when the player drags the tile.

Add the following code at the end of touchesBegan(_:event:):

//show the drop shadow
self.layer.shadowOpacity = 0.8

This turns on the shadow when the player starts dragging. Setting the opacity to 0.8 gives it a bit of transparency, which looks nice.

Add the following code at the end of touchesEnded(_:event:):

self.layer.shadowOpacity = 0.0

This turns off the shadow. The effect will look even better when you change the tile size, but build and run the app now and drag some tiles around to see it working:

Tile with shadows

It’s a nice subtle touch that the user will appreciate – even if subconsciously.

Now to handle resizing the tile so that it looks like it’s being lifted off the board. First add the following property to the class:

private var tempTransform: CGAffineTransform = CGAffineTransformIdentity

This will store the original transform for when the player stops dragging the tile. Remember, each tile has a small random rotation to begin with, so that’s the state you’ll be storing here.

Next, add this code to the end of touchesBegan(_:event:):

//save the current transform
tempTransform = self.transform
//enlarge the tile
self.transform = CGAffineTransformScale(self.transform, 1.2, 1.2)

This saves the current transform and then sets the size of the tile to be 120% of the current tile size.

Now find touchesEnded(_:event:) and add the following line just before the call to dragDelegate:

//restore the original transform
self.transform = tempTransform

This restores the tile’s size to its pre-drag state. While you’re at it, add the following method right after touchesEnded:

//reset the view transform in case drag is cancelled
override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) {
  self.transform = tempTransform
  self.layer.shadowOpacity = 0.0

iOS calls touchesCancelled in certain special situations, like when the app receives a low memory warning or if a notification brings up a modal alert. Your method will ensure that the tile’s display is properly restored.

Build and run and move some tiles around!

You may have already noticed this issue while developing the app, but what’s wrong with the following screenshot?

Bad Layering

As you can see, the tile the player is dragging is displayed below another tile! That really destroys the illusion of lifting the tile.

This occurs because a parent view always displays its subviews in the order that they are added to it. That means any given tile may be displayed above some tiles and below others. Not good.

To fix this, add the following code to the end of touchesBegan:


This tells the view that contains the tile (self.superview) to display the tile’s view above all other views. Dragging should feel a lot better now.

Good layering

Challenge: If you want to make tile dragging even cooler, how about if touching a tile that’s underneath other tiles animated those tiles out of the way, so it looks like the pile of tiles is disturbed by lifting the bottom tile? How would you implement that?

Adding Audio: From Mute to Cute

Tile dragging is now more realistic, but there’s only so far realism can go without audio. Sound is omnipresent and interactive in our daily lives, and your game can’t go without it.

The Xcode starter project includes some Creative Commons-licensed sound effects for your game. There are three sound files, which will correspond with the following game actions:

  • ding.mp3: Played when a tile matches a target.
  • wrong.m4a: Played when a tile is dropped on a wrong target.
  • win.mp3: Played when an anagram is solved.

For convenience, you will pre-define these file names in Config.swift. Add them after the constants you added there earlier:

// Sound effects
let SoundDing = "ding.mp3"
let SoundWrong = "wrong.m4a"
let SoundWin = "win.mp3"
let AudioEffectFiles = [SoundDing, SoundWrong, SoundWin]

You have each file name separately, to use when you want to play a single file. The array of all the sound effect file names is to use when preloading the sounds.

Now create a new Swift file in Anagrams/Classes/Controllers and call it AudioController.

Then inside AudioController.swift, add the following code:

import AVFoundation
class AudioController {
  private var audio = [String:AVAudioPlayer]()

Here you import the framework that you need to play audio or video, and set up a private dictionary audio to hold all preloaded sound effects. The dictionary will map String keys (the name of the sound effect) to AVAudioPlayer instances.

Next add the following method to preload all sound files:

func preloadAudioEffects(effectFileNames:[String]) {
  for effect in AudioEffectFiles {
    //1 get the file path URL
    let soundPath = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent(effect)
    let soundURL = NSURL.fileURLWithPath(soundPath)
    //2 load the file contents
    var loadError:NSError?
    let player = AVAudioPlayer(contentsOfURL: soundURL, error: &loadError)
    assert(loadError == nil, "Load sound failed")
    //3 prepare the play
    player.numberOfLoops = 0
    //4 add to the audio dictionary
    audio[effect] = player

Here you loop over the provided list of names from Config.swift and load the sounds. This process consist of a few steps:

  1. Get the full path to the sound file and convert it to a URL by using NSURL.fileURLWithPath().
  2. Call AVAudioPlayer(contentsOfURL:error:) to load a sound file in an audio player.
  3. Set the numberOfLoops to zero so that the sound won’t loop at all. Call prepareToPlay() to preload the audio buffer for that sound.
  4. Finally, save the player object in the audio dictionary, using the name of the file as the dictionary key.

That effectively loads all sounds, prepares them for a fast audio start and makes them accessible by their file name. Now you just need to add one method, which plays a given sound:

func playEffect(name:String) {
  if let player = audio[name] {
    if player.playing {
      player.currentTime = 0
    } else {

And voila! You have it!

This method takes in a file name, then looks it up in audio. If the sound exists, you first check if the sound is currently playing. If so, you just need to “rewind” the sound by setting its currentTime to 0; otherwise, you simply call play().

Hooray! You now have a simple audio controller for your game. Using it is extremely simple, too. First you need to preload all audio files when the game starts.

Switch to GameController.swift and add this property to the class:

private var audioController: AudioController

The audioController property stores the audio controller the GameController will use to play sounds.

Add the following lines to the end of init():

self.audioController = AudioController()

This makes a new instance of the audio controller and uses the method you just wrote to preload the sounds listed in the config file. Nice! You can now go straight to playing some awesome sound effects!

Inside tileView(_:didDragToPoint:), add the following line after the comment that reads “//more stuff to do on success here”:


Now the player will see and hear when they’ve made a valid move!

Inside the same method, add the following line after the comment that reads “//more stuff to do on failure here”:


Now the player will hear when they’ve made a mistake, too.

Build and run, and check out whether you can hear the sounds being played at the right moment by dragging tiles to the empty spaces.

As long as you’re taking care of the sound effects, you can also add the “winning” sound to the game. Just play the win.mp3 file at the end of checkForSuccess():

//the anagram is completed!


Ladies & Gentlemen – Explosions!

Gamers love explosions. Making them at least – cool gamers don’t look at explosions and just keep on playing :]

Tough luck, though, as UIKit does not have explosions – right? Guess again. If you think that, then you probably haven’t read iOS 5 by Tutorials, which includes a little chapter on particle effects with UIKit.

An abbreviated version of that chapter is also available online. Check that out for more details on particle effects since there isn’t enough room here to go into it.

Your Xcode starter project already includes a particle image file. Drill down in the file explorer to Anagrams/Assets/Particles, find particle.png and open it.

As you can see, there’s nothing fancy about the image – it’s just a white blur in fact, but that’s all it takes to create an explosion.

A particle image

You will now create two particle systems to use in the game.

Add a new Swift file in Anagrams/Classes/Views called ExplodeView.swift.

As the name hints, this system will emulate an explosion. From a given point in space, many particles will accelerate in all directions, until they disappear quite fast. Like so:

Believe it or not, this will be quite easy. To begin, inside ExplodeView.swift, add the following:

import UIKit
import QuartzCore
class ExplodeView: UIView {
  private var emitter:CAEmitterLayer!
  //3 configure the UIView to have an emitter layer
  override class func layerClass() -> AnyClass {
    return CAEmitterLayer.self
  1. Import QuartzCore to access the particle system classes.
  2. emitter is a convenience property used to give you access to the UIView‘s layer property, cast as a CAEmitterLayer.
  3. layerClass() is a class method of UIView. You override this method when you want to change the underlying layer of your view class. Here you return the CAEmitterLayer class and UIKit ensures that self.layer returns an instance of CAEmitterLayer rather than the default CALayer.

All right, you’re ready to start configuring the particle system. Create the initializers for the class:

required init(coder aDecoder:NSCoder) {
  fatalError("use init(frame:")
override init(frame:CGRect) {
  //initialize the emitter
  emitter = self.layer as CAEmitterLayer
  emitter.emitterPosition = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)
  emitter.emitterSize = self.bounds.size
  emitter.emitterMode = kCAEmitterLayerAdditive
  emitter.emitterShape = kCAEmitterLayerRectangle

The above code stores a reference to self.layer in emitter, cast to type CAEmitterLayer because you know that’s what it is. (Remember, you overrode layerClass() to make it so.) Having the correct type makes it easier to manipulate your layer later on.

Then the code sets various properties on the emitter layer. Read through the code and if in doubt about a certain CAEmitterLayer property, consult the Apple docs or our particle systems tutorial.

The settings in init(frame:) only adjust the particle emitter layer. To actually start emitting particles, you need an emitter cell. You will create and configure your object’s emitter cell at the point when the view is added into the view controller’s hierarchy – that is, as soon as you add the view to a parent view.

Add the following implementation of didMoveToSuperview(), which is the method that gets called on a UIView object when it’s added to its parent:

override func didMoveToSuperview() {
  if self.superview == nil {
  let texture:UIImage? = UIImage(named:"particle")
  assert(texture != nil, "particle image not found")
  let emitterCell = CAEmitterCell()
  emitterCell.contents = texture!.CGImage
  //5 = "cell"
  emitterCell.birthRate = 1000
  emitterCell.lifetime = 0.75
  emitterCell.blueRange = 0.33
  emitterCell.blueSpeed = -0.33
  emitterCell.velocity = 160
  emitterCell.velocityRange = 40
  emitterCell.scaleRange = 0.5
  emitterCell.scaleSpeed = -0.2
  emitterCell.emissionRange = CGFloat(M_PI*2)
  emitter.emitterCells = [emitterCell]

That’s quite a bit of code. Let’s go through it one step at a time:

  1. Call the parent class’s implementation of didMoveToSuperview() and then exit the method if there is no superview set on this object. This might happen if the object was removed from its parent.
  2. Load the particle.png image into a UIImage instance. There’s another one of those assert statements that crashes the app if it can’t find the file it’s looking for.
  3. Create a new emitter cell. Most of the rest of the function is spent configuring this object.
  4. Set the cell’s contents property to the texture you loaded. This is the image that will be used to create each of the particles that this cell will emit. The final shape and color of the particle will be determined by the other settings you make in this method.
  5. Name the cell “cell”. The name will be used later to modify the emitter layer’s properties via key-value coding. You can check out Apple’s docs if you want to learn more about key-value coding.
  6. Set the cell’s birthRate property to 1000, which tells it to create 1000 particles per second. You also set the cell’s lifetime property to 0.75, which makes each particle exist for 0.75 seconds.
  7. Here you set the cell’s color to randomly vary its blue component. Setting blueRange to 0.33 will get you particles with random colors between [1,1,1] (rgb) and [1,1,0.67] (rgb) – basically anywhere between white and orange. You also set a negative blueSpeed – this will decrease the blue component of the blending over time, decreasing the intensity of the particle’s color.
  8. The birth velocity of the particles has a base value of 160 and a range of 40, so the actual velocity will be anywhere between 120 and 200.
  9. The particles are emitted by default with a scale of 1.0. Therefore, setting a range of 0.5 will get you random particles from 0.5 to 1.5 times their original size. Finally you set a negative speed for the scale, thus continuing to shrink the particles over time. Not much shrinking will happen over a 0.75-second lifetime, but it for sure adds to the effect.
  10. Here you set a range (an angle) for the direction the emitter will emit the cells. You set it to a range of 360 degrees – that is, to randomly emit particles in all directions. Remember, this function takes its value in radians, not degrees, so 2*pi radians.
  11. Finally, you add the cell you created to the emitter layer. emitterCells is an array of CAEmitterCells for this emitter. (You can have more than one.)

Aaaaand you’re done. :]

You have now an awesome explosion view. Now add it behind a tile that has been dropped onto a proper target. Open up GameController.swift and add this code to the end of placeTile(_:targetView:):

let explode = ExplodeView(frame:CGRectMake(,, 10,10))

You make a new instance of ExplodeView, positioned at the center of the dropped tile view, and add it to the gameView. To make sure it does not cover the tile, you also call sendSubviewToBack() to make the explosion happens behind the tile.

Go! Go! Go! Build and run the project! Wowza!

Particle effect

That wasn’t that difficult, right? However, the effect looks much more like a gas leak than a single explosion. And also – it never stops!

What you would like to do now is kill the emitter after a second to make it look more like an explosion.

Go back to ExplodeView.swift and add a method to stop the emitter cell.

func disableEmitterCell() {
  emitter.setValue(0, forKeyPath: "emitterCells.cell.birthRate")

This is that key-value coding I mentioned earlier. The above string accesses the birthRate property of the object named cell that is contained in the array returned from the emitterCells property. By instructing the cell to emit 0 particles per second, you effectively turn it off. Nice.

Now add the following to the end of didMoveToSuperview():

//disable the emitter
var delay = Int64(0.1 * Double(NSEC_PER_SEC))
var delayTime = dispatch_time(DISPATCH_TIME_NOW, delay)
dispatch_after(delayTime, dispatch_get_main_queue()) {
//remove explosion view
delay = Int64(2 * Double(NSEC_PER_SEC))
delayTime = dispatch_time(DISPATCH_TIME_NOW, delay)
dispatch_after(delayTime, dispatch_get_main_queue()) {

Here you are using Grand Central Dispatch to dispatch blocks to disable the emitter and remove it from its superview. First you schedule a delay of 1/10th of a second to disable the emitter, and after a delay of 2 seconds, you make another call to remove the explosion view from its parent. Why not just remove the view? You want to let the exploded particles fly away and dissolve before killing the effect.

Build and run the game again and enjoy some nice explosions!

Note: If you want to create your own particle systems, check out original author Marin’s UIEffectDesigner app, which allows you to visually design your particle system effects and then show them onscreen with just a couple of lines of code. It’s still an early beta, but if you are interested in creating particle systems for UIKit or AppKit, give it a try.

Now you’re going to add one more effect. It’s quite similar to ExplodeView, but involves a bit of gravity, since this effect will be a long lasting emitter rather than a simple explosion.

Create a new Swift file called StardustView in Anagrams/Classes/Views.

Add to the end of StardustView.swift:

import UIKit
import QuartzCore
class StardustView:UIView {
  private var emitter:CAEmitterLayer!
  required init(coder aDecoder:NSCoder) {
    fatalError("use init(frame:")
  override init(frame:CGRect) {
    //initialize the emitter
    emitter = self.layer as CAEmitterLayer
    emitter.emitterPosition = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)
    emitter.emitterSize = self.bounds.size
    emitter.emitterMode = kCAEmitterLayerAdditive
    emitter.emitterShape = kCAEmitterLayerRectangle
  override class func layerClass() -> AnyClass {
    //configure the UIView to have emitter layer
    return CAEmitterLayer.self
  override func didMoveToSuperview() {
    if self.superview == nil {
    //load the texture image
    let texture:UIImage? = UIImage(named:"particle")
    assert(texture != nil, "particle image not found")
    //create new emitter cell
    let emitterCell = CAEmitterCell()
    emitterCell.contents = texture!.CGImage = "cell"
    emitterCell.birthRate = 200
    emitterCell.lifetime = 1.5
    emitterCell.blueRange = 0.33
    emitterCell.blueSpeed = -0.33
    emitterCell.yAcceleration = 100
    emitterCell.xAcceleration = -200
    emitterCell.velocity = 100
    emitterCell.velocityRange = 40
    emitterCell.scaleRange = 0.5
    emitterCell.scaleSpeed = -0.2
    emitterCell.emissionRange = CGFloat(M_PI*2)
    let emitter = self.layer as CAEmitterLayer
    emitter.emitterCells = [emitterCell]
  func disableEmitterCell() {
    emitter.setValue(0, forKeyPath: "emitterCells.cell.birthRate")

As you can see, the code is almost identical to ExplodeView. The only differences are a longer lifetime for the particles, and values set to xAcceleration and yAcceleration to give acceleration to the particles. This is the way to simulate gravity in your particle systems.

This new particle will emit sparkles for as long as it exists, like a lit fuse on a stick of dynamite.

You’re going to animate this effect to go through the screen behind the solved puzzle!

Switch to GameController.swift and create the animation at the end of checkForSuccess():

// win animation
let firstTarget = targets[0]
let startX:CGFloat = 0
let endX:CGFloat = ScreenWidth + 300
let startY =

This piece of code grabs the very first target on the screen and captures its y-coordinate. You also prepare two constants with the start and end x-coordinates.

Add the next bit of code right after what you just added:

let stars = StardustView(frame: CGRectMake(startX, startY, 10, 10))

This actually creates the effect and adds it to the view, behind everything else.

Add the following after that:

      animations:{ = CGPointMake(endX, startY)
      }, completion: {(value:Bool) in
        //game finished

Here you fire off a UIKit animation that moves the effect position through the screen and removes the particle effect from its parent when it’s complete. The following image shows the path it will take:

Animation Path

Build and run the project, and try solving a puzzle. When you do, you’ll see the emitter going through the screen spreading sparkles all over the place. :]

The following screenshot shows it in action, but you really need to see it moving to get the full effect:


That’s some Sparkle Motion! You can refine the effect further by making it follow different paths, zooming in and out, and so on, as you wish.

Adding a Hint Feature

By now you’ve probably already noticed that if you aren’t trained in anagrams, the game can be quite challenging. Unless, of course, you’ve been cheating and looking up the answers in the Plist! :]

It would be a good idea to implement in-game help for your player so they don’t get stuck and lose interest. What you are going to develop next is a Hint button, which will move a tile onto a correct target, thus helping the player solve the puzzle.

Begin by adjusting the HUD. In HUDView.swift, add one more property to the class:

var hintButton: UIButton!

Then add the code to create the button on the HUD. At the end of init(frame:) add:

//load the button image
let hintButtonImage = UIImage(named: "btn")!
//the help button
self.hintButton = UIButton.buttonWithType(.Custom) as UIButton
hintButton.setTitle("Hint!", forState:.Normal)
hintButton.titleLabel?.font = FontHUD
hintButton.setBackgroundImage(hintButtonImage, forState: .Normal)
hintButton.frame = CGRectMake(50, 30, hintButtonImage.size.width, hintButtonImage.size.height)
hintButton.alpha = 0.8

This should configure the button nicely! You set the title to “Hint!”, set the custom game font you use for the HUD and also position the button on the left side of the screen. In the end, you add it to the hud view.

Build and run the project, and you should see the button appear onscreen:

That was quick! Now you need to connect the button to a method so that it will do something when player needs a hint.

Inside GameController.swift, update the hud property to add a didSet property observer. Replace var hud:HUDView! with:

var hud:HUDView! {
  didSet {
    //connect the Hint button
    hud.hintButton.addTarget(self, action: Selector("actionHint"), forControlEvents:.TouchUpInside)
    hud.hintButton.enabled = false

Have a look at this observer. When a HUD instance is set to the property, the game controller can also hook up the HUD’s button to one of its own methods. It’s not the HUD’s job to give hints since it doesn’t know about the words and current state of the puzzle, so you want to do this from the game controller instead. The game controller just sets the target/selector pair of the hud.hintButton button to its own method, actionHint. Sleek! :]

Also, the Hint button starts off as disabled. You’ll turn this on and off at the right times as the game progresses.

You’ll also need to add actionHint() to the GameController class:

//the user pressed the hint button
@objc func actionHint() {

The @objc attribute is needed to make the function available to the Objective-C UIButton class. You’ll replace this code with more than just a log statement later.

Add the following inside checkForSuccess(), just before the line that reads self.stopStopwatch():

hud.hintButton.enabled = false

This disables the hint button at the end of the game, but before any effects begin to play.

Add the following at the end of dealRandomAnagram():

hud.hintButton.enabled = true

This enables the hint button when a new anagram is displayed.

And that should do it! Now when you tap the hint button, you should theoretically see “Help!” appear in the Xcode console. Build and run the project and give the button a try.


Your Hint button does not work for a reason. Remember when you added this line earlier in HUDView’s init(frame:)?

self.userInteractionEnabled = false;

Because HUDView does not handle touches, it also does not forward them to its subviews! Now you have a problem:

  • If you disable touches on the HUD, you can’t connect HUD buttons to methods.
  • If you enable touches on the HUD, the player cannot interact with game elements that are under the HUD layer.

What can you do? Remember the layer hierarchy?

You are now going to use a special technique that comes in handy on rare occasions, but it’s the way to go in this case – and its the most elegant solution as well.

UIKit lets you dynamically decide for each view whether you want to handle a touch yourself, or pass it on to the view underneath. Since HUDView is at the top of the view hierarchy, you’ll add a method there that will handle all touches and then decide what to do with it.

In HUDView.swift, find the line in init(frame:) where you disable user interaction. Change that line to:

self.userInteractionEnabled = true

Now that you will be handling touches in HUDView, you need to decide which ones you want to handle. You’ll implement a custom override of hitTest(_:event:) for the HUDView class.

hitTest(_:event:) gets called automatically from UIKit whenever a touch falls on the view, and UIKit expects as a result from this method the view that will handle the touch. If the method returns nil, then the touch is forwarded to a view under the current view, just as if userInteraction is disabled.

Add the following to HUDView.swift:

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
  //1 let touches through and only catch the ones on buttons
  let hitView = super.hitTest(point, withEvent: event)
  if hitView is UIButton {
    return hitView
  return nil

The logic behind this method is quite simple:

  1. First you call the super’s implementation to get which view would normally handle the touch.
  2. Then you check whether this view is a button (i.e. the Hint button!), and if it is, then you forward the touch to that button.
  3. If it’s not a button, you return nil, effectively forwarding the touch to the underlaying game elements layer.

With this method in place, you have a working HUD layer. Build and run the project, and you will see that the Hint button reacts to touches AND you can drag the tiles around:

Hint button

Challenge: For puzzles with small tiles, it’s actually possible to drop a tile under the button, where it will be stuck forever. How would you solve this problem?

OK, going back to GameController.swift, you can also quickly implement the hinting function. Here’s the plan: you’ll take away some of the player’s score for using the Hint feature, then you’ll find the first non-matched tile and its matching target, and then you’ll just animate the tile to the target’s position.

Replace the println() statement in actionHint() with the following:

hud.hintButton.enabled = false
data.points -= level.pointsPerTile / 2
hud.gamePoints.setValue(data.points, duration: 1.5)

This is pretty simple:

  1. You temporarily disable the button so that no hint animations overlap.
  2. Then you subtract the penalty for using a hint from the current score and tell the score label to update its display.

Now add the following to the end of the same method:

//3 find the first unmatched target and matching tile
var foundTarget:TargetView? = nil
for target in targets {
  if !target.isMatched {
    foundTarget = target
//4 find the first tile matching the target
var foundTile:TileView? = nil
for tile in tiles {
  if !tile.isMatched && tile.letter == foundTarget?.letter {
    foundTile = tile

To continue:

  1. You loop through the targets and find the first non-matched one and store it in foundTarget.
  2. You do the same looping over the tiles, and get the first tile matching the letter on the target.

To wrap up, add this code to the end of the method:

//ensure there is a matching tile and target
if let target = foundTarget {
  if let tile = foundTile {
    //5 don't want the tile sliding under other tiles
    //6 show the animation to the user
         }, completion: {
            (value:Bool) in
                //7 adjust view on spot
                self.placeTile(tile, targetView: target)
                //8 re-enable the button
                self.hud.hintButton.enabled = true
                //9 check for finished game

The above code animates the tile to the empty target:

  1. First bring the tile to the front of its parent’s view hierarchy. This ensures that it doesn’t move under any other tiles, which would look weird.
  2. Set the tile’s center to the target’s center, and do so over 1.5 seconds.
  3. Call placeTile(tileView:, targetView:) to straighten the tile and hide the target.
  4. Enable the Hint button again so the player can use more hints.
  5. Finally, call checkForSuccess() in case that was the last tile. Players will probably not use a hint for the last tile, but you still have to check.

And that’s all! You had already implemented most of the functionality, like placing tiles on a target, checking for the end of the game, etc. So you just had to add a few lines and it all came together. :]

Build and run the project and give the Hint button a try!

Finished game play

What’s On the Menu

The gameplay is complete, but the player can only play Level 1, and can’t choose to solve more difficult anagrams. So your final task for this tutorial is to add a game menu.

Add the following methods to the ViewController class in ViewController.swift:

func showLevelMenu() {
  //1 show the level selector menu
  let alertController = UIAlertController(title: "Choose Difficulty Level",
                                          message: nil,
  //2 set up the menu actions
  let easy = UIAlertAction(title: "Easy-peasy", style:.Default,
                    handler: {(alert:UIAlertAction!) in
  let hard = UIAlertAction(title: "Challenge accepted", style:.Default,
                    handler: {(alert:UIAlertAction!) in
  let hardest = UIAlertAction(title: "I'm totally hard-core", style: .Default,
                    handler: {(alert:UIAlertAction!) in
  //3 add the menu actions to the menu
  //4 show the UIAlertController
  self.presentViewController(alertController, animated: true, completion: nil)
//5 show the appropriate level selected by the player
func showLevel(levelNumber:Int) {
  controller.level = Level(levelNumber: levelNumber)

Here’s what’s going on:

  1. You create a UIAlertController with a title.
  2. Set up a UIAlertAction for each difficulty level with a title, and also define what happens when the player taps the option.
  3. Add the actions to the UIAlertController.
  4. Show the UIAlertController.
  5. When the player selects a level, the action handler calls showLevel. In this method, you create a new Level instance for the selected level, assign it to the game controller and call dealRandomAnagram() on the game controller.

You would like to show the game menu as soon as the game appears on the screen, so add the following implementation of viewDidAppear to ViewController.swift:

//show the game menu on app start
override func viewDidAppear(animated: Bool) {

This calls showLevelMenu() to display the menu to the player.

Woop, woop!

Build and run the project. You’ll see that you have things a bit mixed up – the game appears with an anagram already loaded, while the player still sees the menu:

Mixed menu

To make matters worse, if you choose an item from the menu, it displays it on top of the existing anagram!

Tiles need clearing

To fix the first problem, scroll inside ViewController.swift, find these two lines inside viewDidLoad() and delete them:

controller.level = level1

In the same method, but a bit above, also delete this line:

let level1 = Level(levelNumber: 1)

These were all test code chunks that you no longer need.

Build and run again. Now the player sees the menu first, and when they choose the difficulty level the game starts. Nice!


But now, when the game is over the player cannot go back to the menu screen!

You could make the ViewController be a delegate of GameController, so that when the game is over GameController could send a message straight to ViewController. That would be overkill for this situation, however. And since you want to know tricks for flexible game design with UIKit, why don’t you add a closure to show the game menu that gets executed upon game completion.

Open up GameController.swift and add the following to the list of properties:

var onAnagramSolved:( () -> ())!

This is how you declare a closure that does not take arguments or return a result. The idea here is that GameController will call this closure when the player solves an anagram. It’ll be up to ViewController to fill in this property with some code to show the game menu.

Add the following helper method to the GameController class that you’ll call between levels:

//clear the tiles and targets 
func clearBoard() {
  tiles.removeAll(keepCapacity: false)
  targets.removeAll(keepCapacity: false)
  for view in gameView.subviews  {

The method removes all tiles and targets from the controller and the view. You’ll use this to fix the problem you saw earlier, where new anagrams are displayed on top of old ones.

Inside checkForSuccess(), find the line stars.removeFromSuperview(). This is when the final win animation ends. Just below that line, but still inside the block where it is located, add:

//when animation is finished, show menu

Here you call clearBoard() to clean up between levels, and then you call the closure stored in onAnagramSolved.

And finally, add the end-game code closure! Switch for the last time to ViewController.swift and at the end of viewDidLoad(), add:

controller.onAnagramSolved = self.showLevelMenu

Very simple and elegant! You just set the game controller onAnagramSolved closure to call showLevelMenu().

Build and run one last time:

Your finished letter / word game with UIKit!

Congratulations, you have made a complete and polished letter / word game with UIKit!

Where to Go from Here?

Here is a link to the final source code for the tutorial.

You made it! It was a long tutorial, but you learned a ton of cool stuff, from particle effects to game logic to timers. And maybe even improved your vocabulary and anagram skill? ;]

The game is complete, but there are all sorts of ways you could expand it. Here are some ideas off the top of my head:

  • Think about how to make this game (or your own) multi-player via Game Center.
  • You could also simply implement leaderboards via Game Center.
  • Add more explosions, more levels and more anagrams.
  • Implement local high score tracking for different players. You could load and save scores from a plist or JSON file.

That’s all for today. Thanks for sticking with this tutorial, and do leave a comment in the forums below!

How To Make a Letter / Word Game with UIKit and Swift: Part 3/3 is a post from: Ray Wenderlich

The post How To Make a Letter / Word Game with UIKit and Swift: Part 3/3 appeared first on Ray Wenderlich.



Write a comment