extension Three<Three<Player?>> {
public static let empty = Self(
.init(nil, nil, nil),
.init(nil, nil, nil),
.init(nil, nil, nil)
)
public var isFilled: Bool {
self.allSatisfy { $0.allSatisfy { $0 != nil } }
}
func hasWin(_ player: Player) -> Bool {
let winConditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [6, 4, 2], // Diagonals
]
for condition in winConditions {
let matches = condition.map { self[$0 % 3][$0 / 3] }
let matchCount = matches.filter { $0 == player }.count
if matchCount == 3 {
return true
}
}
return false
}
public var hasWinner: Bool {
hasWin(.x) || hasWin(.o)
}
}