我想添加tie功能,然後再次播放按鈕會出現。 我是Swift中的新人。Swift - 在井字遊戲中添加Tie和playagain功能
我困在領帶功能,並保持它的工作正常。
import UIKit
class ViewController: UIViewController {
@IBOutlet var winnerLable: UILabel!
@IBOutlet var playAgainButton: UIButton!
@IBAction func playAgain(_ sender: Any) {
activeGame = true
activePlayer = 1
gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var _: UIButton
for i in 1..<10 {
if let button = view.viewWithTag(i) as? UIButton {
button.setImage(nil, for: [])
}
winnerLable.isHidden = true
playAgainButton.isHidden = true
winnerLable.center = CGPoint(x: winnerLable.center.x - 500, y: winnerLable.center.y)
playAgainButton.center = CGPoint(x: playAgainButton.center.x - 500, y: playAgainButton.center.y)
}
}
// 1 is nought and 2 is cross
var turnCount = 0
var activeGame = true
var activePlayer = 1
var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0] //0 is empty
var winnerCombination = [[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) {
let activePosition = sender.tag - 1
if gameState[activePosition] == 0 && activeGame {
gameState[activePosition] = activePlayer
if activePlayer == 1 {
sender.setImage(UIImage(named: "nought.png"), for: [])
activePlayer = 2
} else {
sender.setImage(UIImage(named: "cross.png"), for: [])
activePlayer = 1
}
for combination in winnerCombination {
if gameState[combination[0]] != 0 && gameState[combination[0]] == gameState[combination[1]] && gameState[combination[1]] == gameState[combination[2]] {
// we have a winner
activeGame = false
winnerLable.isHidden = false
playAgainButton.isHidden = false
if gameState[combination[0]] == 1{
winnerLable.text = "Nought has won"
} else {
winnerLable.text = "crosses has won"
}
}
UIView.animate(withDuration: 1, animations: {
self.winnerLable.center = CGPoint(x: self.winnerLable.center.x + 500, y: self.winnerLable.center.y)
self.playAgainButton.center = CGPoint(x: self.playAgainButton.center.x + 500, y: self.playAgainButton.center.y)
})
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
winnerLable.isHidden = true
playAgainButton.isHidden = true
winnerLable.center = CGPoint(x: winnerLable.center.x - 500, y: winnerLable.center.y)
playAgainButton.center = CGPoint(x: playAgainButton.center.x - 500, y: playAgainButton.center.y)
}
}
喔不會發生肯定的我的錯誤下次這個.. –
你好鄧肯,我不能這樣做,請給我一些示例代碼,以便我可以看到並在我的code.pls幫助我爲此 –
不,我不會給你「示例代碼」。只需創建一個返回Bool的函數boardIsFull即可。讓它遍歷遊戲數組,如果任何單元格爲零,則返回false;否則,如果數組中的每個條目都不爲零,則返回TRUE。每次移動後,如果您沒有發現贏家,請檢查boardIsFull()== true。如果它**是**,你有一個領帶,否則繼續玩。 –