Introduction: How to Make a Tic Tac Toe Game Using Swift With Xcode
In this Swift tutorial I will show you how to create a Tic Tac Toe App. This app is extremely simple and is great project for any beginner. I will break up the tutorial into three steps:
1. Creating the objects
2. Linking objects into the code
3. The code
Step 1: Creating the Objects
This step consists of adding all the images, labels, and buttons. You can get the images that I used here: https://imgur.com/a/DiqiTa0
Add the grid to your storyboard as a UIImage. Add the circle and cross as a button. Next, add another label and another button to the top of the screen. You can customize these however you would like. We will use these for the 'Play Again Button' and the scoreboard label.
Step 2: Linking the Objects to Our Code
Copy and paste the cross nine times. Move each of the crosses into each of the grid squares. Next, add the first cross into the view controller as a function. Add the 8 remaining crosses into that function. Finally, add a tag to each of the crosses. The first cross having the tag '1', and the last cross having the tag '9'. If you're confused, the code on the next step should help you out.
Step 3: Variables and Establishing the Active Player
This first portion of code focuses on establishing the main variables. It establishes all the winning combinations under the variable 'winningCombinations'. It also uses the 'action' function to determine who the active player is.
Step 4: Determining the Winner
This piece of uses a logic statement to determine who has won the game. It then uses an 'if else' statement to print the name of the winner on the scoreboard. After it determines the winner, the code reveals a 'Play Again' button.
Step 5: Reseting the Game Board
This final piece of code resets the game board after you press the 'Play Again' button. It clears up all previous values and pieces so that way you can play a completely new game.