Skip to content

Commit be42d85

Browse files
thomasmarshThomas Marshstephencelis
authored
Tic-tac-toe minor updates: win condition and fix to placeholder copy (#28)
* Simplify the tic-tac-toe win condition check * Fix copy for placeholder in tic-tac-toe example * Update Examples/TicTacToe/Sources/Core/GameCore.swift Co-authored-by: Thomas Marsh <[email protected]> Co-authored-by: Stephen Celis <[email protected]>
1 parent 5ae5dd4 commit be42d85

File tree

2 files changed

+22
-21
lines changed

2 files changed

+22
-21
lines changed

Examples/TicTacToe/Sources/Core/GameCore.swift

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -85,26 +85,27 @@ extension Array where Element == [Player?] {
8585
self.allSatisfy { row in row.allSatisfy { $0 != nil } }
8686
}
8787

88-
public var hasWinner: Bool {
89-
// First row
90-
if self[0][0] != nil && self[0][0] == self[0][1] && self[0][1] == self[0][2] { return true }
91-
// Second row
92-
if self[1][0] != nil && self[1][0] == self[1][1] && self[1][1] == self[1][2] { return true }
93-
// Third row
94-
if self[2][0] != nil && self[2][0] == self[2][1] && self[2][1] == self[2][2] { return true }
95-
96-
// First column
97-
if self[0][0] != nil && self[0][0] == self[1][0] && self[1][0] == self[2][0] { return true }
98-
// Second column
99-
if self[0][1] != nil && self[0][1] == self[1][1] && self[1][1] == self[2][1] { return true }
100-
// Third column
101-
if self[0][2] != nil && self[0][2] == self[1][2] && self[1][2] == self[2][2] { return true }
102-
103-
// First diagonal
104-
if self[0][0] != nil && self[0][0] == self[1][1] && self[1][1] == self[2][2] { return true }
105-
// Second diagonal
106-
if self[2][0] != nil && self[2][0] == self[1][1] && self[1][1] == self[0][2] { return true }
107-
88+
func hasWin(_ player: Player) -> Bool {
89+
let winConditions = [
90+
[0,1,2], [3,4,5], [6,7,8],
91+
[0,3,6], [1,4,7], [2,5,8],
92+
[0,4,8], [6,4,2]
93+
]
94+
95+
for condition in winConditions {
96+
let matchCount = condition
97+
.map { self[$0%3][$0/3] }
98+
.filter { $0 == player }
99+
.count
100+
101+
if matchCount == 3 {
102+
return true
103+
}
104+
}
108105
return false
109106
}
107+
108+
public var hasWinner: Bool {
109+
hasWin(.x) || hasWin(.o)
110+
}
110111
}

Examples/TicTacToe/Sources/Views-UIKit/NewGameViewController.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ class NewGameViewController: UIViewController {
6969

7070
let playerOTextField = UITextField()
7171
playerOTextField.borderStyle = .roundedRect
72-
playerOTextField.placeholder = "Blob Sr."
72+
playerOTextField.placeholder = "Blob Jr."
7373
playerOTextField.setContentCompressionResistancePriority(.required, for: .horizontal)
7474
playerOTextField.addTarget(
7575
self, action: #selector(playerOTextChanged(sender:)), for: .editingChanged)

0 commit comments

Comments
 (0)