ios - 了解 "For In"循环代码

标签 ios arrays swift

我正在学习 swift 教程,其中一个应用程序是井字游戏。该代码使用了很多数组和数组中的数组,很快就变得困惑了。在我有信心理解这段代码的工作原理之前,我不想继续学习下一个教程。我对这段代码的问题如下:

  • combo[] 在检查获胜时如何知道它指的是哪个空间?
  • combo in winCombos中,combo的作用是什么?
  • 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.
    }


}

最佳答案

gameState 数组就是井字游戏的单元格,索引如下:

 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)

赢得胜利。

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

相关文章:

android - 套接字上的 fragment 图像字节数组

ios - 无法使用 Swift 工作 GLKView

ios - 使用 Swift 生成 PDF

ios - FB.AppRequest崩溃

ios - UIButton 子类 @IBAction 不起作用

javascript - 如何通过数组进行此循环?

mysql - 是否可以从 MySQL 表返回数组?

swift - 在 macOS 10.14 上键入文本时,NSTextView 光标不出现

ios - 如何在没有代码访问的情况下使用 GPX 文件在 IOS 真实设备上设置虚假 GPS 位置?

ios - ScrollView 中的 Refreshcontrol 无法快速工作