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.
99 lines
3.3 KiB
99 lines
3.3 KiB
//
|
|
// Connect4Rules.swift
|
|
//
|
|
//
|
|
// Created by Adam BONAFOS on 14/01/2025.
|
|
//
|
|
|
|
import Foundation
|
|
public struct Connect4Rules : Rules {
|
|
|
|
let piecesToAlign: Int
|
|
|
|
init(piecesToAlign: Int) {
|
|
self.piecesToAlign = piecesToAlign
|
|
}
|
|
|
|
func add(board: inout Board, position pos: (row: Int, column: Int), token: Token) -> Bool {
|
|
var currentRowNb = 0;
|
|
for var row in board.grid {
|
|
if row[pos.column] != Token.empty && currentRowNb != 0 {
|
|
row[currentRowNb - 1] = token
|
|
return true
|
|
}
|
|
currentRowNb += 1
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isGameOver(board: Board) -> (result: Bool, winner: Token) {
|
|
// Vérification générale avec le nombre de pièces à aligner
|
|
let maxRow = board.rowNb
|
|
let maxCol = board.columnNb
|
|
|
|
// Vérification horizontale
|
|
for row in 0..<maxRow {
|
|
for col in 0..<(maxCol - piecesToAlign + 1) {
|
|
if checkLine(board: board, start: (row, col), direction: (0, 1)) {
|
|
return (true, board[row, col])
|
|
}
|
|
}
|
|
}
|
|
|
|
// Vérification verticale
|
|
for col in 0..<maxCol {
|
|
for row in 0..<(maxRow - piecesToAlign + 1) {
|
|
if checkLine(board: board, start: (row, col), direction: (1, 0)) {
|
|
return (true, board[row, col])
|
|
}
|
|
}
|
|
}
|
|
|
|
// Vérification diagonale ascendante (\)
|
|
for row in (piecesToAlign - 1)..<maxRow {
|
|
for col in 0..<(maxCol - piecesToAlign + 1) {
|
|
if checkLine(board: board, start: (row, col), direction: (-1, 1)) {
|
|
return (true, board[row, col])
|
|
}
|
|
}
|
|
}
|
|
|
|
// Vérification diagonale descendante (/)
|
|
for row in 0..<(maxRow - piecesToAlign + 1) {
|
|
for col in 0..<(maxCol - piecesToAlign + 1) {
|
|
if checkLine(board: board, start: (row, col), direction: (1, 1)) {
|
|
return (true, board[row, col])
|
|
}
|
|
}
|
|
}
|
|
|
|
// Vérification du match nul (plateau plein)
|
|
for row in 0..<maxRow {
|
|
for col in 0..<maxCol {
|
|
if board[row, col] == .empty {
|
|
return (false, Token.empty)
|
|
}
|
|
}
|
|
}
|
|
|
|
return (true, Token.empty) // Match nul si toutes les cases sont pleines
|
|
}
|
|
|
|
private func checkLine(board: Board, start: (Int, Int), direction: (Int, Int)) -> Bool {
|
|
var currentPos = start
|
|
let player = board[start.0, start.1]
|
|
guard player != .empty else { return false }
|
|
|
|
for _ in 1..<piecesToAlign {
|
|
currentPos = (currentPos.0 + direction.0, currentPos.1 + direction.1)
|
|
if currentPos.0 < 0 || currentPos.0 >= board.rowNb ||
|
|
currentPos.1 < 0 || currentPos.1 >= board.columnNb ||
|
|
board[currentPos.0, currentPos.1] != player {
|
|
return false
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
}
|