我正在跟随一个学习swift的教程,其中一个应用程序是tic tac toe。代码在数组中使用了很多数组和数组,很快就变得混乱起来。我不想继续下一个教程,直到我有信心了解这段代码是如何工作的。关于此代码,我的问题如下:
如何知道它在检查获胜时所指的空间?
combo[]中,combo的功能是什么?
如何与for combo in winCombos一起判断是否有赢家?
代码如下:

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


}

最佳答案

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(本例中为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)

为了得到你的赢家。

关于ios - 了解“For In”循环代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27913367/

10-10 14:45