gpt4 book ai didi

swift - 井字游戏赢了?

转载 作者:行者123 更新时间:2023-11-28 13:10:02 25 4
gpt4 key购买 nike

我正在用 Swift 为 2 位玩家制作井字游戏。现在我知道我可以通过为 9 个按钮制作 socket 然后为所有 3 行案例编写来找到赢家,但我想知道是否有更好的方法来做到这一点?有没有更好的方法来编写我的 switch 语句?

@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
@IBOutlet weak var button5: UIButton!
@IBOutlet weak var button6: UIButton!
@IBOutlet weak var button7: UIButton!
@IBOutlet weak var button8: UIButton!
@IBOutlet weak var button9: UIButton!
var player = 1

@IBAction func playersTurn(sender: UIButton){

switch player{
case 1: sender.setTitle("X", forState: UIControlState.Normal); player = 2;break;
case 2: sender.setTitle("O", forState: UIControlState.Normal); player = 1;break;
default:exit(0); break
}
}

最佳答案

我会使用值 0-9 按从上到下、从左到右的顺序设置按钮上的 tag 属性,如下所示:

[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
[ 6 ][ 7 ][ 8 ]

然后创建一个模型来表示每个方 block 并赋予它相应的索引值,以及对拥有它的玩家的引用。然后,您可以使用这些模型处理游戏逻辑,并通过使用 viewForTag(_:) 获取对按钮的引用来更新 UI。这是我的版本:

class Square {
var owningPlayer: Player?

let index: Int
init( index: Int ) {
self.index = index
}
}

class Player {
let symbol: String

init( symbol: String ) {
self.symbol = symbol
}
}

class ViewController: UIViewController {

var squares = [Square]()
var players = [Player]()

var currentPlayer: Player?

override func viewDidLoad() {
super.viewDidLoad()

self.players = [ Player(symbol: "X"), Player(symbol: "O") ]
self.currentPlayer = self.players[0]

// Create squares
for i in 0..<9 {
self.squares.append( Square(index: i) )
}
}

@IBAction func buttonPressed( button: UIButton ) {
guard let player = self.currentPlayer else {
fatalError( "Don't have a current player!" )
}

if let square = self.squares.filter({ $0.index == button.tag }).first {

// Update model
square.owningPlayer = player

// Update UI
button.setTitle( player.symbol, forState: .Normal )

}

if self.checkWin() {
print( "\(player.symbol) wins!" )
}
else {
self.currentPlayer = self.players.filter({ $0 !== player }).first
}
}

func checkWin() -> Bool {
guard let player = self.currentPlayer else {
fatalError( "Don't have a current player!" )
}

let winningSequences = [
// Horizontal rows
[ 0, 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8 ],
// Diagonals
[ 0, 4, 8 ],
[ 2, 4, 6 ],
// Vertical rows
[ 0, 3, 6 ],
[ 1, 4, 7 ],
[ 2, 5, 8 ],
]

// Get indexes owned by this player
let selectedIndexes = self.squares.filter({ $0.owningPlayer === player }).map { $0.index }

// Change the sequence arrays into sets for accurate comparison using `contains(_:)`
if winningSequences.map({ Set<Int>($0) }).contains( Set<Int>(selectedIndexes) ) {
return true
}

return false
}
}

关于swift - 井字游戏赢了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31689156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com