-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.swift
More file actions
96 lines (81 loc) · 2.94 KB
/
Board.swift
File metadata and controls
96 lines (81 loc) · 2.94 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Board.swift(修正済み v2)
import SwiftUI
import Combine
struct Stone {
enum Color: String {
case black = "Black"
case white = "White"
var opposite: Color {
self == .black ? .white : .black
}
}
let color: Color
}
struct AssistInfo {
let color: Color
let description: String
}
class Board: ObservableObject {
static let size = 15
@Published var stones: [[Stone?]] = Array(repeating: Array(repeating: nil, count: Board.size), count: Board.size)
@Published var assistInfo: [[AssistInfo?]] = Array(repeating: Array(repeating: nil, count: Board.size), count: Board.size)
@Published var gameStatus: String = "Game in progress"
var currentPlayer: Stone.Color = .black
func reset() {
stones = Array(repeating: Array(repeating: nil, count: Board.size), count: Board.size)
assistInfo = Array(repeating: Array(repeating: nil, count: Board.size), count: Board.size)
gameStatus = "Game in progress"
currentPlayer = .black
analyzeBoard()
}
func placeStone(at position: (Int, Int), color: Stone.Color) {
guard stones[position.0][position.1] == nil else { return }
let stone = Stone(color: color)
stones[position.0][position.1] = stone
if checkForWin(at: position) {
gameStatus = "\(color.rawValue) wins!"
analyzeBoard()
return
}
currentPlayer = color.opposite
analyzeBoard()
}
private func checkForWin(at position: (Int, Int)) -> Bool {
let directions = [
(0, 1), (1, 0), (1, 1), (1, -1)
]
for direction in directions {
if hasConsecutiveStones(count: 5, from: position, inDirection: direction) {
highlightWinningLine(at: position, inDirection: direction)
return true
}
}
return false
}
private func highlightWinningLine(at start: (Int, Int), inDirection direction: (Int, Int)) {
var current = start
for _ in 0..<5 {
if isValid(row: current.0, col: current.1) {
assistInfo[current.0][current.1] = AssistInfo(color: .yellow, description: "Winning line")
}
current.0 += direction.0
current.1 += direction.1
}
}
private func hasConsecutiveStones(count: Int, from start: (Int, Int), inDirection direction: (Int, Int)) -> Bool {
var current = start
for _ in 0..<count {
guard isValid(row: current.0, col: current.1),
let stone = stones[current.0][current.1],
stone.color == stones[start.0][start.1]?.color else {
return false
}
current.0 += direction.0
current.1 += direction.1
}
return true
}
func isValid(row: Int, col: Int) -> Bool {
return row >= 0 && row < Board.size && col >= 0 && col < Board.size
}
}