I'm following a tutorial to learn swift and one of the apps is tic tac toe. The code uses lots of arrays and arrays within arrays, and it became confusing pretty quickly. I don't want to move on to the next tutorial until I'm confident in my understand of how this code is working. My questions about this code are as follows:
- How does
combo[]know which space it is referring to when checking for a win? - In
for combo in winCombos, what is combo's function? - How does
winComboswork withgameStateto tell if there is a winner?
Here is the code:
import UIKit
class ViewController: UIViewController {
var turnNumber = 1
var winner = 0
@IBOutlet weak var button0: UIButton!
var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
let winCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
@IBAction func buttonPressed(sender: AnyObject) {
if(gameState[sender.tag] == 0) {
var oImage = UIImage(named: "Tic Tac Toe O.png")
var xImage = UIImage(named: "Tic Tac Toe X.png")
if(turnNumber%2 == 0) {
sender.setImage(oImage, forState: .Normal)
gameState[sender.tag] = 1
}else{
sender.setImage(xImage, forState: .Normal)
gameState[sender.tag] = 2
}
for combo in winCombos {
if(gameState[combo[0]] == gameState[combo[1]] && gameState[combo[1]] == gameState[combo[2]] && gameState[combo[0]] != 0) {
println(combo[0])
println(combo[1])
println(combo[2])
winner = gameState[combo[0]]
}
}
if( winner != 0){
println("Winner!")
}
turnNumber++
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}