Tic-Tac-Toe for iPhone!

Tic-Tac-Toe for iPhone!

Here’s a nice tic-tac-toe app I wrote for ios9 in swift2. Features include single or 2 player mode.

 

Let’s start with the mainStoryboard layout. Add the board graphic, then add buttons in the nine spaces. Make sure to choose custom-

 

Screen Shot 2016-01-28 at 11.03.45 AM

 

especially if you want custom images–I have a version for my daughter with Frozen characters instead of X’s and O’s.

 

Screen Shot 2016-01-28 at 11.07.18 AM

 

Now, each button needs to be tagged 0 through 9:

Screen Shot 2016-01-28 at 11.16.27 AM

 

so your tic-tac-toe grid should have buttons tagged like this:

0 | 1 | 2

3 | 4 | 5

6 | 7 | 8

 

This will allow us to identify which buttons have been pressed, and we can then identify wins, blocks, ect.

Here are the winning combonations-3 horizontal, 3 vertical, and 2 diagnal

let winningCombos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [1, 4, 7], [0, 3, 6], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

 

Now – here’s where the real magic is–the built in A.I. for single player. I want the computer to block the win whenever needed. But even more important than blocking is what……….as Charlie Sheen would say….winning! The best defense is a good offense right, or something like that.

So, we want the A.I. to look for wins first. Here’s how:

 

Now, if no win possibilities are found, the A.I. should now look for blocks to prevent the opponent from winning:

If no wins or blocks are found–say the game just started, then the A.I. should just randomly choose any available space:

Notice after all these loops finish we check for a win.

One additional feature I added was a small delay for the A.I. move. This gives a more realistic feel to the game–like the computer needs to think a little bit about the next move. It was actually surprisingly difficult for me to get this to finally work!

First create the dispatchTime

Then use it to wrap any call to draw the circle like so:

Check out the full project on gitHub

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *