理解"对于In"循环代码

时间:2015-01-13 00:55:03

标签: ios arrays swift

我正在按照教程学习swift,其中一个应用程序是tic tac toe。代码在数组中使用了大量的数组和数组,并且很快就变得混乱。我不想继续学习下一个教程,直到我对我理解这段代码如何工作有信心。我对此代码的疑问如下:

  • combo[]在检查获胜时如何知道它所指的空间?
  • for combo in winCombos中,什么是组合的功能?
  • winCombos如何与gameState合作判断是否有胜利者?

以下是代码:

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.
    }


}

1 个答案:

答案 0 :(得分:2)

gameState数组只是Tic Tac Toe游戏的单元格,索引如下:

 0 | 1 | 2
---+---+---
 3 | 4 | 5
---+---+---
 6 | 7 | 8

由此可以很容易地看出winCombo是什么,它是可能获胜的列表,例如0,1,2(顶行)和2,4,6(左下角到右上角)对角线)。

声明:

for combo in winCombos

只是一个循环,为combo中的每个值设置winCombos并使用它来查看是否获胜。

因此,首次时间循环,combo设置为[0,1,2],您可以检查所有这些单元格是否为非彼此相等 - 如果是这样,你就赢了。

同样适用于该循环的后续迭代,其中combo采用winCombos数组中的后续值。

假设您在最终检查2,4,6上获胜,所有值均为X(在本例中为2)。检查声明可以逐步缩小:

if(gameState[combo[0]] == gameState[combo[1]] &&
   gameState[combo[1]] == gameState[combo[2]] &&
   gameState[combo[0]] != 0)

为:

if(gameState[2] == gameState[4] && gameState[4] == gameState[6] && gameState[2] != 0)

并且,从那里:

if(2 == 2 && 2 == 2 && 2 != 0)

获得胜利者。