-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwiftToeGame.swift
70 lines (62 loc) · 2.34 KB
/
SwiftToeGame.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import SwiftUI
import AVFoundation
class SwiftToeGame: ObservableObject {
@Published var board: [[String]] = Array(repeating: Array(repeating: "", count: 3), count: 3)
@Published var scoreX: Int = 0
@Published var scoreO: Int = 0
@Published var message: String = ""
@Published var showAlert: Bool = false
@Published var pressedTile: (x: Int, y: Int)? = nil
var currentPlayer: String = "X"
var audioPlayer: AVAudioPlayer?
func newGame() {
board = Array(repeating: Array(repeating: "", count: 3), count: 3)
scoreX = 0
scoreO = 0
currentPlayer = "X"
message = ""
}
func presentEndOfGameAlert() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.showAlert = true
}
}
func reset() {
board = Array(repeating: Array(repeating: "", count: 3), count: 3)
currentPlayer = "X"
message = ""
}
func makeMove(x: Int, y: Int) {
if board[x][y] == "" {
pressedTile = (x, y)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
self.board[x][y] = self.currentPlayer
self.checkForWinner()
self.currentPlayer = self.currentPlayer == "X" ? "O" : "X"
self.pressedTile = nil
}
}
}
private func checkForWinner() {
for i in 0..<3 {
if board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer ||
board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer {
currentPlayer == "X" ? (scoreX += 1) : (scoreO += 1)
message = "\(currentPlayer) Wins!"
presentEndOfGameAlert()
return
}
}
if board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer ||
board[2][0] == currentPlayer && board[1][1] == currentPlayer && board[0][2] == currentPlayer {
currentPlayer == "X" ? (scoreX += 1) : (scoreO += 1)
message = "\(currentPlayer) Wins!"
presentEndOfGameAlert()
return
}
if !board.joined().contains("") {
message = "Draw"
presentEndOfGameAlert()
}
}
}