Skip to content

Commit

Permalink
Hooked up Board2 across the board
Browse files Browse the repository at this point in the history
  • Loading branch information
richy486 committed Feb 3, 2025
1 parent 900f483 commit bc7ebc6
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 68 deletions.
10 changes: 5 additions & 5 deletions Shared/Business/Interactors/PositioningInteractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import Foundation
}

// Is there a piece at this grid position?
guard let piece = appState.gameState.board[fromGridPosition.row][fromGridPosition.column] else {
guard let piece = appState.gameState.board[fromGridPosition.column, fromGridPosition.row] else {
return
}
// Is this the right player's piece?
Expand Down Expand Up @@ -110,14 +110,14 @@ import Foundation
}

private func movePiece(from: GridCoordinate, to: GridCoordinate) {
let piece = appState.gameState.board[from.row][from.column]
appState.gameState.board[to.row][to.column] = piece
appState.gameState.board[from.row][from.column] = nil
let piece = appState.gameState.board[from.column, from.row]
appState.gameState.board[to.column, to.row] = piece
appState.gameState.board[from.column, from.row] = nil
}

private func checkWinState() {
let originalPlayCondition = appState.gameState.playCondition
let pieces = appState.gameState.board.flatMap { $0 }.compactMap { $0 }
let pieces = appState.gameState.board.grid.compactMap { $0 }

// TODO: Check for checkmate.

Expand Down
19 changes: 7 additions & 12 deletions Shared/Business/State/GameState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,17 @@ import Foundation

// This data structure is (row, column), most of the other code is (column, row) because that is
// (x, y).
var board: Board = [[]]
private let initialBoard: Board
var board: Board2<GamePiece?>
private let initialBoard: Board2<GamePiece?>
private var currentTurnIndex: Int = 0
var playCondition: PlayCondition = .playing
var players: [Player]
// TODO: Add move history to store late in a `GameHistory`.
// TODO: Add game start time to store late in a `GameHistory`.

var rowCount: Int { return board.count }

// calculate columns from minimum grid positions in the rows so there are no positions without an
// array value.
var columnCount: Int {
return board.reduce(999, { partialResult, row in
return min(partialResult, row.count)
})
}
// Probably can call the board values directly.
var rowCount: Int { board.rows }
var columnCount: Int { board.columns }

var currentTurn: Player {
get {
Expand All @@ -53,7 +47,7 @@ import Foundation
}

var uniquePieces: [Character: GamePiece] {
let allBoard = initialBoard.joined().compactMap { $0 }
let allBoard = initialBoard.grid.compactMap { $0 }
var uniquePieces: [Character: GamePiece] = [:]
for piece in allBoard {
uniquePieces[piece.pieceBase.icon] = piece
Expand All @@ -68,6 +62,7 @@ import Foundation
]
self.players = players
initialBoard = BoardFactory.fiveByFive.makeBoard(players: players)
board = initialBoard

for piece in uniquePieces {
print("\(piece.key) \(piece.value.description)")
Expand Down
2 changes: 1 addition & 1 deletion Shared/Business/State/HistoryState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import Foundation
}

struct GameHistory {
let board: Board
let board: Board2<GamePiece?>
let playCondition: PlayCondition
let players: [Player]

Expand Down
8 changes: 6 additions & 2 deletions Shared/Data Structures/Board2.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Matrix.swift
// Board2.swift
// MoreChess
//
// Created by Richard Adem on 26/01/2025.
Expand All @@ -20,7 +20,11 @@ struct Board2<T> {
let rows: Int
var grid: [T]


init() {
self.columns = 0
self.rows = 0
self.grid = []
}

init(columns: Int, rows: Int, defaultValue: T) {
self.columns = columns
Expand Down
35 changes: 15 additions & 20 deletions Shared/DataAccess/GameRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,28 @@ class GameRepository {

func fetchBoard(currentPlayer: Player,
opponent: Player,
currentBoard board: Board,
currentBoard board: Board2<GamePiece?>,
columnCount: Int,
rowCount: Int) async -> Board {
rowCount: Int) async -> Board2<GamePiece?> {
// Debug sleep
try? await Task.sleep(nanoseconds: UInt64(2 * Double(NSEC_PER_SEC)))
// try? await Task.sleep(nanoseconds: UInt64(2 * Double(NSEC_PER_SEC)))

// Get all current piece positions
let allPositions: [GridCoordinate] = board.enumerated().reduce([], { partialResult, value in
let rowIndex = value.offset
let row = value.element
let rowPositions: [GridCoordinate] = Array(row.enumerated()).compactMap { (columnIndex, piece) in
guard let piece else {
return nil
}
guard piece.player == currentPlayer else {
return nil
}
return GridCoordinate(column: columnIndex, row: rowIndex)
let allPositions: [GridCoordinate] = board.reduce([], { partialResult, value in
guard let piece = value.2 else {
return partialResult
}
return partialResult + rowPositions
guard piece.player == currentPlayer else {
return partialResult
}
return partialResult + [GridCoordinate(column: value.0, row: value.1)]
})

// Get a random piece
guard let randomPiecePosition = allPositions.randomElement() else {
fatalError("Can't get random piece positions")
}
guard let piece = board[randomPiecePosition.row][randomPiecePosition.column] else {
guard let piece = board[randomPiecePosition.column, randomPiecePosition.row] else {
fatalError("Can't get random piece")
}

Expand Down Expand Up @@ -83,9 +78,9 @@ class GameRepository {

// Update board
var updatedBoard = board
updatedBoard[targetPosition.row][targetPosition.column] = piece
updatedBoard[randomPiecePosition.row][randomPiecePosition.column] = nil
updatedBoard[targetPosition.column, targetPosition.row] = piece
updatedBoard[randomPiecePosition.column, randomPiecePosition.row] = nil

return updatedBoard
}
}
Expand Down
2 changes: 1 addition & 1 deletion Shared/DataAccess/LobbyRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct LobbyRepository {
]
}
func opponentJoined(gameId: String) async -> Bool {
try? await Task.sleep(nanoseconds: UInt64(1 * Double(NSEC_PER_SEC)))
// try? await Task.sleep(nanoseconds: UInt64(1 * Double(NSEC_PER_SEC)))

// DEBUG
LobbyRepository.checks += 1
Expand Down
10 changes: 5 additions & 5 deletions Shared/Models/Game/BoardFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ enum BoardFactory {
case fiveByFive
case chess

func makeBoard(players: [Player]) -> Board {
func makeBoard(players: [Player]) -> Board2<GamePiece?> {

var horizontalSize: Int = 0
var verticalSize: Int = 0
Expand All @@ -22,18 +22,18 @@ enum BoardFactory {
case .fiveByFive:
horizontalSize = 5
verticalSize = 5
return [
return try! Board2<GamePiece?>(nestedArray: [
[r(1), r(1), r(1), r(1), r(1)],
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil],
p(0, 🏰, 🐴, 🤴, 👸) + [r(0)],
]
])

case .chess:
horizontalSize = 8
verticalSize = 8
return [
return try! Board2<GamePiece?>(nestedArray: [
p(1, 🏰, 🐴, 🥷, 👸, 🤴, 🥷, 🐴, 🏰),
[nil, nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil, nil],
Expand All @@ -42,7 +42,7 @@ enum BoardFactory {
[nil, nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil, nil],
p(0, 🏰, 🐴, 🥷, 👸, 🤴, 🥷, 🐴, 🏰)
]
])
}
}
}
17 changes: 11 additions & 6 deletions Shared/Presentation/Elements/SimpleBoardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,25 @@ import SwiftUI

/// Like `BoardView` but with no interaction, just to display something.
struct SimpleBoardView: View, BoardViewProtocol {
let board: Board
let board: Board2<GamePiece?>

init(board: Board2<GamePiece?>) {
self.board = board
}

var body: some View {
Grid(horizontalSpacing: 0, verticalSpacing: 0) {
ForEach(Array(board.enumerated()), id: \.offset) { rowIndex, row in
ForEach(0...(board.rows-1), id: \.self) { y in
GridRow {
ForEach(Array(row.enumerated()), id:\.offset) { columnIndex, piece in
ForEach(0...(board.columns-1), id: \.self) { x in
Color.clear
.frame(width: PresentationConstants.Layout.elementDiameter,
height: PresentationConstants.Layout.elementDiameter)
.background(
background(isTarget: false,
rowIndex: rowIndex,
columnIndex: columnIndex,
rowCount: board.count)
rowIndex: y,
columnIndex: x,
rowCount: board.rows)
)
}
}
Expand Down
24 changes: 13 additions & 11 deletions Shared/Presentation/Game/BoardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@ struct BoardView: View, BoardViewProtocol {

var body: some View {
Grid(horizontalSpacing: 0, verticalSpacing: 0) {
ForEach(Array(appState.gameState.board.enumerated()), id: \.offset) { rowIndex, row in
ForEach(0...(appState.gameState.board.rows-1), id: \.self) { y in
GridRow {
ForEach(Array(row.enumerated()), id:\.offset) { columnIndex, piece in
let isTarget = appState.positioningState.targetGrid?.column == columnIndex
&& appState.positioningState.targetGrid?.row == rowIndex
let gridPosition = GridCoordinate(column: columnIndex, row: rowIndex)
let isSelected = appState.positioningState.selectedGridPosition?.column == columnIndex
&& appState.positioningState.selectedGridPosition?.row == rowIndex
ForEach(0...(appState.gameState.board.columns-1), id: \.self) { x in
let piece = appState.gameState.board[x, y]
let isTarget = appState.positioningState.targetGrid?.column == x
&& appState.positioningState.targetGrid?.row == y
let gridPosition = GridCoordinate(column: x, row: y)
let isSelected = appState.positioningState.selectedGridPosition?.column == x
&& appState.positioningState.selectedGridPosition?.row == y
let offset = appState.positioningState.pieceOffset(gridPosition)
Group {
if let piece {
let offset = appState.positioningState.pieceOffset(gridPosition)
PieceView(piece: piece)
.accessibility(label: Text("\(piece.description) piece"))
.frame(width: PresentationConstants.Layout.elementDiameter,
Expand All @@ -35,7 +36,7 @@ struct BoardView: View, BoardViewProtocol {
.onChanged { gesture in
positioningInteractor
.update(dragOffset: gesture.translation,
from: GridCoordinate(column: columnIndex, row: rowIndex))
from: GridCoordinate(column: x, row: y))
}
.onEnded { _ in
positioningInteractor.endDrag()
Expand All @@ -44,15 +45,16 @@ struct BoardView: View, BoardViewProtocol {
.zIndex(Double(isSelected
? PresentationConstants.ZIndex.selected.rawValue
: PresentationConstants.ZIndex.normal.rawValue))

} else {
Color.clear
.frame(width: PresentationConstants.Layout.elementDiameter,
height: PresentationConstants.Layout.elementDiameter)
}
} // Group
.background(background(isTarget: isTarget,
rowIndex: rowIndex,
columnIndex: columnIndex,
rowIndex: y,
columnIndex: x,
rowCount: appState.gameState.rowCount))
}
}
Expand Down
2 changes: 1 addition & 1 deletion Shared/Presentation/Game/GameView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ struct GameView: View {
VStack {
// Debug
Text("offset: \(appState.positioningState.dragOffset.width) \(appState.positioningState.dragOffset.height)")
if let selectedGridPosition = appState.positioningState.selectedGridPosition, let piece = appState.gameState.board[selectedGridPosition.row][selectedGridPosition.column] {
if let selectedGridPosition = appState.positioningState.selectedGridPosition, let piece = appState.gameState.board[selectedGridPosition.column, selectedGridPosition.row] {
Text("selected: col: \(selectedGridPosition.column) row: \(selectedGridPosition.row) \(piece.pieceBase.icon)")
} else {
Text("selected:")
Expand Down
2 changes: 1 addition & 1 deletion Shared/Presentation/Game/InfoView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ struct InfoView: View {
if width <= 0 && height <= 0 {
Text("can make board with \(width) x \(height)")
} else {
let board: Board = Array(repeating: Array(repeating: nil, count: width), count: height)
let board = Board2<GamePiece?>(columns: width, rows: height, defaultValue: nil)

VStack {
Text("\(minColumn) x \(maxColumn) -> \(width)")
Expand Down
6 changes: 3 additions & 3 deletions Shared/Utils/MoveValidator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ struct MoveValidator {
/// - Returns: A `GridCoordinate` of a valid move if valid, nil is invalid.
static func validTargetPosition(startingCoordinate: GridCoordinate?,
toGridOffset gridOffset: GridCoordinate,
board: Board,
board: Board2<GamePiece?>,
columnCount: Int,
rowCount: Int) -> GridCoordinate? {
guard let startingCoordinate,
let currentPlayerPiece = board[startingCoordinate.row][startingCoordinate.column] else {
let currentPlayerPiece = board[startingCoordinate.column, startingCoordinate.row] else {
return nil
}

Expand Down Expand Up @@ -66,7 +66,7 @@ struct MoveValidator {
}

// If there is a piece in the target position, it has to be the opponent.
if let targetPiece = board[targetPosition.row][targetPosition.column] {
if let targetPiece = board[targetPosition.column, targetPosition.row] {
guard targetPiece.player != currentPlayerPiece.player else {
return nil
}
Expand Down

0 comments on commit bc7ebc6

Please sign in to comment.