我正在学习 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/