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.

Leave a rating/review
Save for later
Share

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

Update 04/10/15: Updated for Xcode 6.3 and Swift 1.2

Are you a seasoned iOS developer who is thinking of creating an iOS game, but have no experience programming games? Maybe learning OpenGL ES makes you uncomfortable, or maybe you’ve just never crossed paths with Cocos2d for iPhone?

Well, good news! UIKit is a power tool for game developers. Its high-end frameworks provide you with the means to create all of your game logic, from creating animations (including frame-animation) to playing audio and video.

This 3-part tutorial series will guide you through the process of building a board game for iPad, 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!

This tutorial series is designed for readers who are already somewhat familiar with Swift, and thus won’t go over details like primitive types or syntax. If your knowledge of Swift is lacking, I recommend checking out our Swift Video Series.

Click through to get your game on!

Getting Started: Introducing Anagrams

The letter / word game with UIKit you will be making in this tutorial is about anagrams.

An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, the word cinema can be rearranged into the word iceman. Your game will challenge the player to create anagrams from words and phrases you provide.

The finished game will look something like this:

Final Game

As you can see, in the screenshot above there is a row of letter tiles at the bottom of the screen that makes up the initial phrase. In this example it is the word admirer, minus the M tile, which the player has dragged to the upper row.

The player’s job is to drag the letters from admirer to form a different word, using the same letters.

Can you guess what it is? I’ve already given you a hint… it starts with an M!

[spoiler title=”Answer”]

The correct answer is married. Did you figure it out? If so, give yourself a high-five!

[/spoiler]

So anyway, this is the game you will be making. As you build this game, you will learn about the following foundational topics:

  • Proper model-view-controller (MVC) game structure.
  • Loading levels from configuration files.
  • Organizing your game controller logic.
  • Writing a simple audio controller for UIKit with AV Foundation.
  • Using QuartzCore for static visual effects.
  • Using UIAnimation to smooth in-game movements.
  • Using UIKit particles to add visual effects.
  • Building separate layers for the heads-up display (HUD) and the gameplay.
  • Using custom fonts to improve the look and polish.
  • Upgrading default UIKit components to game-like components.
  • Also included: discussion of the software tools I use along the way when I’m creating a game. :]

Oh, and there will be explosions. :] Let’s dig in!

The Starter Project

To get you straight to the good stuff – using UIKit to build an iOS game – this tutorial provides a ZIP file that includes a starter XCode project and all game assets (images, fonts, audio and config files).

Download the Anagrams Part 1 Starter, unzip it and open it up in Xcode.

Have a look at what’s bundled in the starter project. The project file browser on the left should look something like this:

Starter Files

Here’s a quick summary of what you see:

  • Config.swift: Basic top-level configuration.
  • Levels: Folder containing three .plist files to define the game’s three difficulty levels.
  • Classes/Models: Folder for your data models.
  • Classes/Views: Folder for your custom view classes.
  • Classes/Controllers: Folder for your controllers.
  • Assets/Images: Images you’ll use to create the game.
  • Assets/Audio: Creative Commons-licensed audio files.
  • Assets/Particles: Contains a single PNG file to use for particle effects.
  • Assets/Fonts: A custom TTF font for the game HUD.
  • Main.storyboard: Open up the storyboard and you’ll see there’s only one screen with the background set to a faint woodgrain image, which is included in the project assets.
  • Credits.txt: Includes links to the sources of all the assets used in the project.

Poke around, play the sounds and browse the images. Then run the project.

First Run

It’s much better than an empty app window, isn’t it?

In this first part of the series, your goal is to display the initial anagram and target boxes on the screen. In the next parts of this series, you’ll add the ability to drag the tiles and the gameplay logic.

There’s a lot involved to get this first part working. But don’t worry, you’ll break down this epic task into 8 small steps:

  1. Load the level config file.
  2. Create a game controller class.
  3. Create an onscreen view.
  4. Create a tile view.
  5. Deal the tiles on the screen.
  6. Add the letters.
  7. Slightly rotate the letters randomly.
  8. Add the targets.

Let’s go over these one step at a time.

1) Load the Level Config File

Select the level1.plist file in the project file browser. Have a look what’s inside:

Level Config

There are three top-level keys:

  • pointsPerTile: the number of points awarded for each correctly-placed tile.
  • timeToSolve: The number of seconds the player will have to solve the puzzle.
  • anagrams: A list of anagrams. Each anagram contains two items: an initial and a final phrase.

Don’t bother for the moment with the first two and focus on anagrams. It’s an array of array-elements and each element has two string elements. You’re now going to build a data model to load this configuration in Swift.

Right-click (or control-click) on the Anagrams/Classes/Models folder in the project and select New File… to create a new file. Select the iOS\Source\Swift File template and click Next. Name the file Level.swift and click Create.

Open up Level.swift and add the following struct definition:

struct Level {
	let pointsPerTile: Int
	let timeToSolve: Int
	let anagrams: [NSArray]
}

The properties match the structure of the .plist file, so you are simply going to load the data and populate the properties.

Next, add the code to initialize the Level data model inside the struct definition:

init(levelNumber: Int) {
  //1 find .plist file for this level
  let fileName = "level\(levelNumber).plist"
  let levelPath = "\(NSBundle.mainBundle().resourcePath!)/\(fileName)"
    
  //2 load .plist file
  let levelDictionary: NSDictionary? = NSDictionary(contentsOfFile: levelPath)
    
  //3 validation
  assert(levelDictionary != nil, "Level configuration file not found")
    
  //4 initialize the object from the dictionary
  self.pointsPerTile = levelDictionary!["pointsPerTile"] as! Int
  self.timeToSolve = levelDictionary!["timeToSolve"] as! Int
  self.anagrams = levelDictionary!["anagrams"] as! [NSArray]
}

Given a difficulty level ranging from 1 to 3, the initializer will set up the struct and its properties. There are four small sections in the initializer body:

  1. Determine the path to the appropriate level config file (level1.plist, level2.plist, etc), based on the levelNumber value passed into the method and the bundle path.
  2. Load the file’s contents into an NSDictionary, explicitly defined as optional since the file may not exist if you pass in an invalid level number. Fortunately, the NSDictionary class knows how to parse .plist files!
  3. Validate that there’s something loaded in levelDictionary. I use assert often for errors that should never happen in a shipped app; if they EVER happen during development I want the app to stop and crash, so I can fix it before doing anything else.
  4. Copy the values from the NSDictionary to the Level instance’s properties.

Open up ViewController.swift and at the end of viewDidLoad(), add:

let level1 = Level(levelNumber: 1)
println("anagrams: \(level1.anagrams)")

Build and run, and in the Xcode console you will see the list of anagrams for Level 1. Nice!

Print Anagrams

Now you can remove the println() line from viewDidLoad() to keep the console tidy.

That’s one task knocked down. Ready to move ahead to the next one?

Contributors

Over 300 content creators. Join our team.