Swift Programming Tutorial Part 5: Making a Game (Tic Tac Toe with AI)

@SkipAllMighty
Source code: https://github.com/skipallmighty/SwiftTacToe
Algorithm details: http://en.wikipedia.org/wiki/Tic-tac-toe#Strategy
We skip forks and opposite corners of algorithm.
Assets here: http://imgur.com/a/V9xpk
Best viewed in 4k!
Covering:
Making a game of Tic Tac Toe with AI
Special Thanks to Logan @ loganwright.io

• Views:121,049 views
• Rating:
• Categories:
• Tags:

programerbob says:

Can anyone help on func rowCheck? I’m using Skip Wilson’s book “Learning Swift Programming” (which is using a much more updated version of Xcode) , but it is still not running :

func rowCheck(#value:Int) -> [String]? {
var acceptableFinds = [“011″,”110″,”101”]
var findFuncs = [checkTop,checkBottom,checkLeft,checkRight,checkMiddleAcross,checkMiddleDown,checkDiagRight,checkDiagLeft]
var algorithmResults = findFuncs[0] (value: value)

for algorithm in findFuncs{
var algorthmResults =  algorithm(value: value)
println(algorithmResults)
var findPattern = find(acceptableFinds, algorithmResults[1])
println(acceptableFinds)
if findPattern != nil{
return algorithmResults
}
}
return nil
}

The error is when you call var findPattern, it says: “cannot subscript a value of type (location: String, pattern: String)? with an index of type int”

Toy Stories, Cats, and Play says:

as a total beginner, tutorials 1-3 were great, and 4 was getting a little more difficult, but this one is impossible for a newbie to programming to follow the charts. In the other tutorials we only learned var and a little bit about “func” and then this video incorporates a million untaught termes. I’m assuming that your posting this as an example of what can be done and really only a tutorial for those familiar with code. Off to find other tutorials I go. lol

xxBIGBIRDxx says:

the tut is great but xcode is horrible i cant drag the stuf for auto code

Raglandguy says:

Can you make a video of this following MVC?

Ricardo Calderon says:

Hey skip what do i do when i qet stuck in here
if !plays [sender.tag] && !aiDeciding && !done

Zafer Celaloglu says:

Hi Skip, I checkout this repository from github but it gives 3 compiler error like below

/Users/****/Desktop/Swift Language/SwiftTacToe/TicTacToe/AppDelegate.swift:18:10: Objective-C method ‘application:didFinishLaunchingWithOptions:’ provided by method ‘application(_:didFinishLaunchingWithOptions:)’ conflicts with optional requirement method ‘application(_:didFinishLaunchingWithOptions:)’ in protocol ‘UIApplicationDelegate’

/Users/****/Desktop/Swift Language/SwiftTacToe/TicTacToe/AppDelegate.swift:67:16: Binary operator ‘!=’ cannot be applied to operands of type ‘NSPersistentStoreCoordinator’ and ‘nil’

/Users/****/Desktop/Swift Language/SwiftTacToe/TicTacToe/AppDelegate.swift:50:12: Binary operator ‘!=’ cannot be applied to operands of type ‘NSManagedObjectContext’ and ‘nil’

How can I overcome these issues?

Thanks a lot

Vrishank Mishra says:

Hi, I am using xcode 6 and I can not drag stuff as in 13:35 , can you please help?
Thanks a lot, love your tutorials. 🙂

Thank you so much! I picked up swift in under an hour! So much more helpful than any website or other youtube out there!

Jason Smith says:

I actually thought I was going to enjoy this tutorial, but error after error as the code is outdated, is really testing. I even redesigned the image assets before hand, but feel I’ve wasted a good 2-3 hours on this when I could have been doing a more up to date tutorial. I appreciate your classes and the effort you put into them, but maybe a disclaimer message at the beginning of the video to explain that the student will need Xcode version… – – would be really handy for anyone thinking of spending sometime on this project. Thanks again though. Onwards to find a more up-to-date tutorial. (PS I’m a complete newb, so maybe after some more lessons I’ll be able to come back and fix things in this tutorial.)

Khem Ist says:

get shwifty

Terry South says:

Fantastic tutorial!! One question, how did you come up with the logic for the whole game, not just the AI algorithm? Do you have a flow chart diagram you can share? My biggest issue is understanding the logic flow from one function to another, is there an easy way to visualize  the logic path (perhaps by xcode)?

Oscar Khuong says:

Excuse my basic question: I thought AI are something such as built-in Methods or Func provided by Swift ? Seems we tried to list down most cases may occurs. Is what we’re doing called AI ? I’m new to Swift, so excuse this basic question.

venkata yelchuri says:

Which configuration is needed for developing swift applications and parllel desktop.

Seungchan Oh says:

For those who got an error like “Optional type ‘Bool’ cannot be used as a boolean; test for ‘!= nil’ instead”, try this code. I’m using Xcode 6.4.

if plays[sender.tag] == nil && !aiDeciding && !done {
setImageForSpot(sender.tag, player:1)
}

Batteryman C says:

Hi, I have an issue with the @IBAction function. For some reason, i keep getting an error on the setImageForSpot and the error states that I apparently can’t assign setImageForSpot to ‘self’. Here is the lines in code in question

@IBAction func UIButtonClicked(sender:UIButton) {
label.hidden = true
if plays[sender.tag] == nil && !aiDeciding && !done {
setImageForSpot = (sender.tag, player:1)

}

checkForWin()
aiTurn()
}

אשרף עטשי says:

Please submit to the new version on Xcode (6.3)

Blonded Sports says:

HELLO SKIP! (or anybody that can help)

right on my line “”” func setImageForSpot(spot:Int,player:Int) “”””

its giving me an error stating USE OF UNRESOLVED IDENTIFIER “setImageForSpot”

why?

Fernhw says:

Great to learn the basics of the language but you could’ve done the ai algorithm with 2 arrays, and one function.

SkipGames says:

I typed if ((!plays[sender.tag] && !aiDeciding && !done)) {
setImageForSpot(sender.tag, player:1)

and i got the error Optional type ‘Bool’ cannot be used as a boolean; test for ‘!= nil’ instead.

if i try to run it says build failed, what do i do to fix?

Brunomak says:

Hello, thanks for the videos, they are excellent, but I can’t vizualize my game at iOS Simulator, it starts, apper my LouchScreen, and then just a black sreen. I can’t see any difference from what you did and what I did.
Since I’m using the Xcode 6.3, is there any change?
Thank you very much.

Kosta Stojcev says:

Hi,
I llike your toutorial but i have problem while coding by your example.
On the row:
if plays[sender.tag] && !aiDeciding && !done {

}

it says that “Optional type ‘Bool’ cannot be used as boolean; test for ‘!= nil’ instead”

any help?

Vellantis - Ambience, Spa and Relaxation Music Soundtracks www.vellantis.com says:

Hi Skip,
Concerning the TicTacToe game:
@IBOutlet var TicTacImg1: UIImageView = nil
@IBOutlet var TicTacImg2: UIImageView = nil
and so on
is now getting an error…I should use `!` or `?`

Further on
if !plays[sender.tag] && !aiDeciding && !done {
is getting errors, too…guess these issues are connected!?

Thanks

Tyler Thomas says:

So at around 32:19 I get an error message that says Expression was too complex to be solved in reasonable time. I have X code 6.2. Any thoughts…?

Dylan Warchak says:

Would be absolutely amazing if you could make an updated tutorial for Swift 2.0! Between the updated GitHub source code (last updated a year ago) I’ve been trying my best to piece this all together, but I just can’t quite get it! Or if you could link me to source code compatible with the latest Swift update that would be stellar.

George Rosescu says:

Hi, I have a little problem… If I put 2 “X” in the same square, the computer accept the command and puts 2 “O” in different squares

Arseny Ivanov says:

Hey there. First of all, thanks for this tutorial, awesome stuff, very informative.
One question thou. I managed to correct few errors that compiler spits out because of the syntax changes that happened since the time the video was captured. Nevertheless, one thing is still bugging me a lot. Looks like at the step before last the computer lacks some game logic and puts its “o” to the wrong cell instead of blocking me. Is it me or the reason is that piece that was not implemented?

Joel Cauley says:

Do programmers not flow chart their programs anymore? maybe I’m just a fossil

Ace Green says:

Hello Skip,

This line doesn’t work for me

if find(AcceptableFinds, AlgorthmResults.pattern)? {

it says:
‘Optional< (location: String, pattern: String)>‘ does not have a member named ‘pattern’

Shawn Ray says:

So, I’m not sure if it is just mine, but there is a bug if you play certain patterns. it can’t read the middle column to stop the player from winning. For example, I play 5, AI 1, Me 4, AI 6, Me 8 or 2, and AI 3. It doesn’t stop the middle rows possibility to win. Anyone else have this issue?

Bruce Elliott says:

Great tutorial. Easy to follow.

Paul Wilkinson says:

Good but from Part 4 to Part 5 you’ve jumped into all sorts of new functions and XCode GUI design concepts. you need a few Part 4.1, 4.2 videos.

Jan Reiners says:

Hey guys,

I don’t get an error on compiling, so the build succeeds. Unfortunately the Simulator the stops with the Initial screen and it jumps back to xcode again, showing the following fault:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

Raphael Almeida Avelino says:

Where I get exactly this images? The grids, X and O.

Sapientium says:

plz make the text bigger, it’s hard to see the code. Toolbar > Xcode > Preferences > Font & color > Presentation/Presentation large

Timothy Teves says:

hey skip, unresolved identifier for ‘aiTurn’ im stuck here

TechPocket says:

There is an algorithm called MiniMac which is used for zero type games where all information is known (such as chess, tic tac toe, checkers etc.). My question is, could you make a tutorial using the MiniMax algorithm to produce an unbeatable AI tic tac toe and if possible, creating some levels like easy, medium, hard, impossible?

Ironic Music Group says:
NotoriousPIG says:

I literally cannot get swift at all, so in tutorials and books etc they teach arrays, basic functions and so on. None of that is helpful because that barely ever applies to xcode, there is a massive gap from what they teach in books/tutorials to what is actually useful in xcode

Shih-Min Lee says:

MiniTekkers says:

love these tutorials, greatly appreciated!

programerbob says:

func checkForWin(){
var whoWon = [“I”:0,”You”:1]
for(key,value) in whoWon{
if((plays[7] == value && plays[8] == value && plays[9] == value) || //across the bottom
(plays[4] == value && plays[5] == value && plays[6] == value) || //across the middle
(plays[1] == value && plays[2] == value && plays[3] == value) || //across the top
(plays[1] == value && plays[4] == value && plays[7] == value) || //down the left
(plays[2] == value && plays[5] == value && plays[8] == value) || //down the middle
(plays[3] == value && plays[6] == value && plays[9] == value) || //down the right
(plays[1] == value && plays[5] == value && plays[9] == value) || //diag left to right
(plays[3] == value && plays[5] == value && plays[7] == value)){ //diag right to left
userMessage.hidden = false
userMessage.text = “Looks like (key) won!”
resetBtn.hidden = false
done = true

GIVES ERROR: “expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions”

Does anyone know how to solve this?

Nitesh Tiwari says:

Great works, thank you very much 🙂

Dapo Nuga says:

Guys I’m a bit stuck trying to figure out how to make the alphabetical icons and grid. please help 🙂 thanks

Will Green says:

I keep getting an error on line if !plays[sender.tag]…etc saying cannot invoke ‘&&’ with and argument list of type (\$T14, \$T18)

any help?

Mike Futcher says:

Hi Skip.

Your Tutorials are awesome thank you for spending the time to go through it with us!
I have a slight issue I cannot get the Code if !plays(sender.tag) && !aiDeciding && !done to work. i have tried all the below varieties… plays(sender.tag) !=Nil etc etc but none of them seem to work and constanty get errors dvsing i cannot use the && function with two Bools. i am running version Version 6.4 any help would be really appreciated.

Francesco Maria D'Aquino says:

Hi Skip. When I write !plays[sender.tag] && !aiDeciding && !done the program says that I cannot use the && for both boolean and integer. How do I solve this problem?

Юлия Веркиенко says:

Hello everybody! I can not figure out the function rowCheck. The problem with the “find” ( “use of unresolved identifier ‘find'”). How it can be fixed? (xCode v.8.3.3)

Francesco Maria D'Aquino says:

Hi Skip, why when I click start it appears only a white screen without anything ?

Yearim Kim says:

Neener-neener-neener! lol Thanks for your videos

Orange Monkey Media - says:

I like this work, and the voice of the narrator, but it seems like Xcode updates have broken this tutorial.