You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB

//
// File.swift
//
//
// Created by Louis DUFOUR on 15/01/2024.
//
import Foundation
public struct Board : Hashable, Equatable {
public let nbRows: Int
public let nbColumns: Int
public private(set) var grid: [[Cell]]
public init?(withGrid grid: [[Cell]]) {
guard let firstRowLength = grid.first?.count, grid.allSatisfy({ $0.count == firstRowLength }) else {
return nil
}
self.nbRows = grid.count
self.nbColumns = firstRowLength
self.grid=grid
}
public func getCell(atRow row: Int, atColumn column: Int) -> Cell? {
guard row >= 0, row < nbRows, column >= 0, column < nbColumns else {
return nil
}
return grid[row][column]
}
public func countPieces(of owner: Owner) -> Int {
return grid.flatMap({ $0 }).filter({ $0.piece?.owner == owner }).count
}
public func countPieces() -> (player1: Int, player2: Int) {
let player1Count = countPieces(of: .player1)
let player2Count = countPieces(of: .player2)
return (player1Count, player2Count)
}
public mutating func insert(piece: Piece, atRow row: Int, andColumn column: Int) -> BoardResult {
guard row >= 0, row < nbRows, column >= 0, column < nbColumns else {
return .failed(reason: .outOfBounds)
}
if grid[row][column].piece == nil {
grid[row][column].piece = piece
return .ok
} else {
return .failed(reason: .cellNotEmpty)
}
}
public mutating func removePiece(atRow row: Int, andColumn column: Int) -> BoardResult {
guard row >= 0, row < nbRows, column >= 0, column < nbColumns else {
return .failed(reason: .outOfBounds)
}
if grid[row][column].piece != nil {
grid[row][column].piece = nil
return .ok
} else {
return .failed(reason: .cellEmpty)
}
}
}