Go to the second part of the article

What time is it now? I tell you what: it’s time to make your first application for iOS! So get your Macbook, put an Xcode sticker on it, and don’t forget to put your awesome Swift t-shirt on. Yes, the one that you bought in the last year’s iOSCon. OK, now we’re ready to start. And let this clear and friendly Xcode game tutorial guide you through!

What else is needed? Ah, just a small number of things: Xcode software itself, and an iPhone device to test your brand new application. Also please don’t forget that your Xcode version should be no less than Xcode 8. Well, that’s pretty it… Did you check everything? If everything’s fine, then we can start learning amazing things about variables, options, inputs, and outputs. And all these things will help us to create our first iOS game.

xcode game tutorial

How to Make a Game with Xcode

It would be better to start gaining your first developer experience with a small but fun game. Remember what your teachers said back in the day? Math is fun! So why not use it for your first iOS game? Math games are quite easy to build, but at the same time, they are challenging enough to become a good start of your developer career.

The game which creation will be described below is called “N+1”. Game’s logic is quite simple, as well as the gameplay: you see 3-digit number on a screen, and the goal is to add +1 to each of the digits to get a new number. For example, you’ve got 145, and thus you must enter 256 number (1+1 = 2, 4+1 = 5, 5+1 = 6) within a brief timeframe. Easy and playable, right? Such types of games are a perfect choice for a newbie, and since the gameplay has become clear, let’s dive into development process! And remember that this game’s development requires no special skills, expertise or experience. You’re a newbie – and this Xcode game tutorial for beginners is a right place to start.

Step 1: Downloading Assets

There are quite many documents that can be considered as Xcode game development tutorials. But not many of them outline the important fact of preparing for your first app development.

So, since we’re done with choosing the game for development, it’s time to download some needful things. For example, valuable Xcode assets and the Xcode project itself. These are available for free access via the following links:

When archives are downloaded, please unzip, and then save them locally.

Also, there are additional assets, such as fonts and graphics that should be downloaded. Get them via these links:

Step 2: How to Make a Game with Xcode: Creating a Project

Okay, here we go! Time to code. Please follow these steps of our Xcode game development tutorial for iOS to dive into development:

  1. Run Xcode
  2. Add a new project via File -> New -> Project… or Command-Shift-N.
  3. Select Single-View Application
  4. Enter N Plus One for Product Name
  5. Enter MyFirstApp for Organization Name
  6. Organization Identifier: com.learnappmaking
  7. Language: Swift, Devices: Universal or iPhone
  8. OK, now choose project location and click Create

Step 3: Create a View Controller

The first thing that you should do within Xcode is called “controller creation.” More specifically, you should create a new view controller element. This element is a component part of Xcode, and it’s responsible for wrapping the screen with an interface. Some of Xcode game tutorials outline the fact that View controller element is basically a Swift class. Which is correct, but the full answer would be a Swift class equipped with XIB file.

To start the creation of MainViewController, please follow these steps:

  1. Open Project Navigator and find your project file icon in the upper navigation menu.
  2. Right-click on the icon, select New File.
  3. Select Cocoa Touch Class, enter MainViewController for Class
  4. Double check that MainViewController is a subclass of UIViewController.
  5. Tick Also create XIB file checkbox.
  6. Choose the default directory for location.

OK, now enter file MainViewController.xib from the Project Navigator. This will enable interface building product called Interface Builder. Within it, you will create standard setup for your app. Remember that  Interface Builder is not responsible for building functional frames of your app, it just helps with interfaces creation. Actually you can do all of these with a pure code, but visual tools are made to empower developer with a better vision and productivity.

Step 4: Building the UI

Take a look at the left sidebar of Interface Builder. Here you will add and manage visual elements, such as buttons, sliders, checkboxes and many other. Property of the elements can be changed with inspectors, they’re placed on the right.

OK, now let’s check Document Outline feature. This feature enables screen elements hierarchy within your app. There are also two items called File’s Owner and First Responder.

After expecting all features of the Builder, let’s try to develop our first UI frame:

  1. Background Image View

    – Full Size, Aspect Fill

  2. Score Image

    Top Left, 149×50

  3. Score Label

    – On Score Image, “1234”, Font: 22, Regular, HVD Comic Serif Pro

  4. Time Image

    – Top Right, 149×50

  5. Time Label

    – On Time Image, “01:00”, Font: 22, Regular, HVD Comic Serif Pro

  6. Number Image

    – Top Center, 302×129

  7. Number Label

    – Center at Number Image, “1234”, Font: 70, Regular, HVD Comic Serif Pro, Alignment Center

  8. Text Field

    – Center Below Number, input Background, Font: 70, Regular, HVD Comic Serif Pro, Border Style “None”, Keyboard Type “Number Pad”, Alignment Center

  9. Colors

    – White

    – Brown (RGB): 135, 79, 33

    – Blue (RGB): 105, 168, 255

  10. Explanation Label:

    – Center Bottom, Font: 70, Regular, HVD Comic Serif Pro, 2 Lines, explanation text: “Hey! Just add one number to each of the digits. And 2345 becomes 3456″

Step 5: Creating a Starting Point

When your game runs, application(_:didFinishLaunchingWithOptions:) function is called. It is responsible for giving a first interface starting point.
OK, now please place the instance variable inside AppDelegate class:

var mainVC:MainViewController?

Then, replace the code inside the function application(_:didFinishLaunchingWithOptions:) , with the following:

mainVC = MainViewController(nibName: “MainViewController”, bundle:nil)

let frame = UIScreen.main.bounds
window = UIWindow(frame: frame)

window!.rootViewController = mainVC

return true

This is what our code does:

  1. Variable mainVC should be initialized by calling constructor method MainViewController with 2 parameters: “MainViewController” for the nibName and nil for the bundle.
  2. Add a constant frame with UIScreen.main.bounds value. We store the screen resolution of the app inside a constant frame.
  3. Initialize the variable window by calling constructor method UIWindow on it. This method takes one parameter: frame, the constant we set up earlier. It’s a named parameter, because you write frame: frame.
  4. Set mainVC to be the rootViewController of window. We use the exclamation mark to force unwrap the variable window.
  5. Call a method makeKeyAndVisible() on the force unwrapped instance variable window.
  6. After it we should return true.

Step 6: First Look on Your Game

Yeah! It’s time to check what we’ve done. To do that, please hit the Play button in the top-left corner of Xcode, then press Command-R.

Is there something? If there isn’t, don’t worry. You probably made a few mistakes along the way, so go back and review your code. If there is, then congratulations! You can check your awesome interface. It’s kind of static right now, but we will equip your game with functionality a bit later.

Stay tuned and subscribe to our newsletter to get a notification when the Second Part will be live!

Step 7: MainViewController

Please make a change to MainViewController.swift. Pay attention to the file structure. As you can see, there is a statement called import. This statement is responsible for communicating with a compiler in order to tell it to use UIKit code. Okay, no let’s check a class declaration. Class declaration says to the compiler: here is the created class, and there is a need to extend UIViewController.

The MainViewController class holds the interface code. It’s linked with .xib file. And the class extends UIViewController. What does it mean? Well, it means that you will use Apple code which was written for UIViewController. Moreover, you will be able to add your very own code to it. So, your code + UIViewController superclass + MainViewController.xib = the single interface of your Xcode game. OK, if this is clear, let’s move forward. Inside the brackets, you should add the class contents. After that, you can see that you have viewDidLoad() method inside the class. It is called after your file called MainViewController.xib is loaded into memory. It should be used to set up the view.

Step 8: Time to Create Your First Method!

So, your first method will be called generateRandomNumber. What does it do? Nothing too special: this method returns a 4 digit number. Of course, it’s a random number. Seems like this is exactly what we need for a game, am I right?

OK, check the full code of this method:

func generateRandomNumber() -> String
var result:String = “”
for _ in 1…4
var digit:Int = Int(arc4random_uniform(8) + 1)
result += “(digit)”
return result

First thing you do is writing func, then adding generateRandomNumber, then (), and then -> String. You write func to make a declaration of your method. After that you should set its title up to generateRandomNumber. When we add () we declare that method has no parameters. To set up the return value, you add single arrow -> and the String return type. This will ensure a String return.

Okay, it’s time to declare a new variable. This variable is called result with String and value “”. After that you should add a loop. The game needs 4-time loop from 1 to 4. Te underscore _ means that we don’t want to keep track of how many times this loop has run, inside the loop. With brackets { and } you set up the loop contents, declaring digit of type Int variable with value of Int(arc4random_uniform(8) + 1). The function arc4random returns a random value from 0 to 7. After adding 1 to it you will have a value from 1 to 8. Well, now you can append the value of a digit string to result. You are not allowed to equip the string with the integer. After all, you will be able to return result.

Step 9: Code + UI: How to Do It?

Remember your Interface Builder inside the MainViewController.xib file? We created it in order to get option to use interface elements. Now it’s time to connect controller class file and the XIB. Please do the following in order to achieve the goal:

@IBOutlet weak var numbersLabel:UILabel?
@IBOutlet weak var scoreLabel:UILabel?
@IBOutlet weak var inputField:UITextField?

As you can see, we add @IBOutlet first. IBOutlet is a declaration statement to indicate that the created property is an outlet. OK, now let’s talk about to weak var. “Weak” means that whenever your controller class is removed from memory, the property can be removed as well. After that you add the name of the property and its type, like numbersLabel of type UILabel. To say that the property is an optional, thus it can be nil, we write the question mark ? at the end.

Step 10: Outlet + Interface Builder: How to Do It?

Open MainViewController.xib in Interface Builder. Click the first UILabel, then hold the Control-key. Drag-and-drop File’s Owner, which is under Placeholders, to your UILabel. Release the mouse when at the label, and a black gizmo will appear. Then choose the numbersLabel outlet.

Repeat the same for the score and the text field. Now you’ve made a connection between the code and the interface, for specific elements and properties.

And One More Thing! No, Actually Two More Things…

OK, we’re almost done! As you may remember, this manual is the easiest Xcode game development tutorial for iOS, so don’t give up.
Switch back to the MainViewController.swift class file and add two methods above the generateRandomNumber method:

func updateScoreLabel()
scoreLabel?.text = “(score)”
func setRandomNumberLabel()
numbersLabel?.text = generateRandomNumber()

What does it mean? Well…

updateScoreLabel is checking the property scoreLabel connection to the outlet for the label with the score. Since it’s an optional property it could be empty. When scoreLabel is nil, any code behind the question mark isn’t executed. Then, it sets the textproperty of the label to “Score: (score)”, which is another string interpolation of the scoreinstance variable. setRandomNumberLabel sets the numbersLabel with a random number, by first checking whether numbersLabel is not nil (using optional chaining) and then setting numbersLabel!.text to the return value of method generateRandomNumber().

Instance Variable

OK, now you should create a brand new instance variable below the outlets. Something like var score:Int = 0 It’s just a variable that’s declared in the scope of the class, and not in the scope of a method.

viewDidLoad() set up

OK, after that please fill the viewDidLoad method with a code. The viewDidLoad method is overridden with the override statement, just before the func statement. That means that the superclass UIViewController of MainViewController has the same name method, but you’re equipping it with new functionality. Whenever this method is called in the game, your method is called, not the superclass method.
Here you can see the code for viewDidLoad method:


inputField?.addTarget(self, action: #selector(textFieldDidChange(textField:)), for:UIControlEvents.editingChanged)

What does it mean? Well, it’s pretty easy. Step #1 is calling super.viewDidLoad(). Step #2 is calling setRandomNumberLabel() and updateScoreLabel(). It sets the label in the interface to a random number, and updates the score with the initial value of 0. Then, you check if inputField not is nil using optional chaining. inputField is connected to the outlet of the big text field in the middle of the screen. MainViewController, is indicated by self. It’s self-explanatory: self means the current context. The action that’s called is denoted by #selector(textFieldDidChange(textField:)). It’s the name of the method that should be called when the event UIControlEvents.editingChanged happens.

For each character you type, it triggers an event, and so it executes the method you just gave it.

Textual Input

Check this out:

func textFieldDidChange(textField:UITextField)
if inputField?.text?.characters.count ?? 0 < 4
if let numbers_text = numbersLabel?.text,
let input_text = inputField?.text,
let numbers = Int(numbers_text),
let input = Int(input_text)
print(“Comparing: (input_text) minus (numbers_text) == (input – numbers)”)
if(input – numbers == 1111)
score += 1
score -= 1

Seems pretty unclear, but we will figure it out. Okay, the first thing you do is clarifying if the characters number in inputField is less than 4. If yes, you return the method: execution halts, so the code below return is not executed when the if-statement is true.

Then, you check whether the inputField.text and numbersLabel.text are nil using optional binding with if let, because they’re optional. Each statement is executed consecutively, and when one of them fails (i.e. the variable involved is nil), execution of the if-statement is stopped and the code continues below the end of the statement. Once the text inside the text field is checked, the code attempts to convert these String variables to Int.

Inside the if-statement, you compare random / input values. As you may already forget (just joking), end-user of your game must add one to each of the digits. Since you don’t include digits 0 and 9, you can easily figure out that the exercise is correct when the difference between numbers and input is 1111.

If input is valid, up the score one point by writing score += 1, which means “add 1 to score“. If it’s not, delete one point via score -= 1. After all, you should update the random number with a new value, update the score label, and empty the text field value.

Run, Game, Run!

Oh yeah! You’ve got it! Your first programming brainchild, your math game is here to make you and everyone else happy. So why should you wait? Press Command+R and check if everything’s fine. There might be some errors, just don’t worry about it too much. Coding is a difficult thing, and maybe there were some mistakes, which is absolutely normal. Just go and check the whole article step-by-step. Maybe some details were not mirrored in the code…

After that please run the app. Your iOS game must do the following: save 4-digit input code, check validity, allow no more than 4 digits to the input.

So, we’re almost here, girls and guys. Access the third part to ensure the last things adding. And we will celebrate!