【发布时间】:2016-04-20 07:41:37
【问题描述】:
我正在尝试重置井字游戏的棋盘,但如果我在 for 循环中将 i 更改为 1,一切正常。我还将标签、按钮和视图的标签从 0 更改为20 但我仍然收到此错误。这是代码
var activePlayer = 1
var gameActive = true
var gameState = [0,0,0,0,0,0,0,0,0] // board is empty
var winningCombinations = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
@IBOutlet var playAgainButton: UIButton!
@IBOutlet var gameOverLabel: UILabel!
@IBAction func playAgainPressed(sender: AnyObject) {
activePlayer = 1
gameActive = true
gameState = [0,0,0,0,0,0,0,0,0]
var button : UIButton
//resetting the image of the button
for var i = 0; i < 9; i++ {
button = view.viewWithTag(i) as! UIButton
button.setImage(nil, forState: .Normal)
}
gameOverLabel.hidden = true
playAgainButton.hidden = true
gameOverLabel.center = CGPointMake(gameOverLabel.center.x - 400, gameOverLabel.center.y)
playAgainButton.center = CGPointMake(playAgainButton.center.x - 400, playAgainButton.center.y)
}
@IBOutlet var button: UIButton!
@IBAction func buttonPressed(sender: AnyObject) {
if gameState[sender.tag] == 0 && gameActive == true{
var image = UIImage()
// updating board
gameState[sender.tag] = activePlayer
if activePlayer == 1 {
image = UIImage(named: "nought.png")!
activePlayer = 2
} else {
image = UIImage(named: "cross.png")!
activePlayer = 1
}
// to access the tag of the image pressed use sender.tag
sender.setImage(image, forState: .Normal)
for combination in winningCombinations {
if gameState[combination[0]] != 0 && gameState[combination[0]] == gameState[combination[1]] && gameState[combination[1]] == gameState[combination[2]]{
var labelText = "Noughts have won!"
if gameState[combination[0]] == 2{
labelText = "Crosses have won"
}
gameOverLabel.text = labelText
gameOverLabel.hidden = false
playAgainButton.hidden = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.gameOverLabel.center = CGPointMake(self.gameOverLabel.center.x + 400, self.gameOverLabel.center.y)
self.playAgainButton.center = CGPointMake(self.playAgainButton.center.x + 400, self.playAgainButton.center.y)
})
gameActive = false
}
}
}
}
【问题讨论】: