### Initialize and Display a Chessboard with SwiftUI Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This example demonstrates how to initialize a ChessboardModel with a FEN string and display it using the Chessboard SwiftUI view. It also includes an .onMove modifier to handle user interactions. ```swift import SwiftUI import ChessboardKit struct ContentView: View { @State var chessboardModel = ChessboardModel(fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") var body: some View { Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in print("Move: \(lan)") } .frame(width: 300, height: 300) } } ``` -------------------------------- ### Handle Chessboard Moves with onMove Modifier Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This example demonstrates how to use the `.onMove` modifier on the `Chessboard` view to capture and process moves made by the user. It provides details about the move, its legality, and promotion status. ```swift Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in print("Move: \(lan)") } ``` -------------------------------- ### Import ChessboardKit in Swift Files Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md After adding ChessboardKit as a dependency, import the library into your Swift files to start using its components. This is a standard import statement for Swift modules. ```swift import ChessboardKit ``` -------------------------------- ### Animate Chessboard FEN Updates Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This example shows how to animate changes to the chessboard's FEN string using SwiftUI's `withAnimation` block. This provides a smooth visual transition when moves are made or the board state changes. ```swift withAnimation { chessboardModel.setFen("New FEN string", lan: "Move LAN string") } ``` -------------------------------- ### Initialize ChessboardModel with Starting Position or Empty Board Source: https://context7.com/rohanrhu/chessboardkit/llms.txt The ChessboardModel class manages the chessboard's state, including position, turn, perspective, and interaction settings. It can be initialized with a FEN string for a specific board setup or an empty board. ```swift import SwiftUI import ChessboardKit struct ContentView: View { // Initialize with starting position @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", perspective: .white, colorScheme: .light, allowOpponentMove: false, highlightLegalMoves: true ) // Or initialize with empty board @State var emptyBoard = ChessboardModel(fen: "8/8/8/8/8/8/8/8 w - - 0 1") var body: some View { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) } } ``` -------------------------------- ### Get Current Chessboard FEN String Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code shows how to retrieve the current FEN string representation of the chessboard's state from the `chessboardModel.fen` property. ```swift let currentFen = chessboardModel.fen ``` -------------------------------- ### Install ChessboardKit using Swift Package Manager Source: https://context7.com/rohanrhu/chessboardkit/llms.txt Add ChessboardKit as a Swift Package Manager dependency to your project by including its Git URL in your Package.swift file. Ensure ChessKit is also imported if you plan to use its functionalities directly. ```swift // In Package.swift dependencies: [ .package(url: "https://github.com/rohanrhu/ChessboardKit.git", from: "1.0.0") ] // In your Swift file import ChessboardKit import ChessKit // Automatically included as dependency ``` -------------------------------- ### Validate FEN String in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Provides an example of how to validate a FEN (Forsyth-Edwards Notation) string using the `FenValidation` class in ChessboardKit. The static method `validateFen(_:)` returns `true` if the FEN string is valid and `false` otherwise. ```swift let isValid = FenValidation.validateFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") ``` -------------------------------- ### Initialize ChessboardModel with Custom Options (Swift) Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Demonstrates how to initialize a ChessboardModel with various custom parameters. This includes setting the initial board state via FEN, defining the perspective, choosing a color scheme, and controlling opponent move permissions. ```swift ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", // FEN string perspective: .white, // Board perspective colorScheme: .light, // Color scheme allowOpponentMove: false // Allow opponent moves ) ``` -------------------------------- ### Present Promotion Picker in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to programmatically present the pawn promotion picker using the `presentPromotionPicker(piece:sourceSquare:targetSquare:lan:)` method of `ChessboardModel`. This is typically used when a pawn reaches the promotion rank. ```swift // Manage the promotion picker func presentPromotionPicker(piece: Piece, sourceSquare: String, targetSquare: String, lan: String) ``` -------------------------------- ### Pawn Promotion Handling Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Describes how ChessboardKit automatically handles pawn promotion, including the display of a promotion picker and callback for promotion events. ```APIDOC ## Pawn Promotion ### Description When it is time for a pawn promotion, the `Chessboard` view will automatically show a promotion picker and handle the promotion process. When a promotion is made, the `onMove` callback will receive the promotion piece as a parameter. ``` -------------------------------- ### Initialize ChessboardModel with FEN String Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code snippet shows how to create an instance of ChessboardModel, which is essential for configuring the chessboard's initial state using a FEN (Forsyth-Edwards Notation) string. ```swift @State var chessboardModel = ChessboardModel(fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") ``` -------------------------------- ### Toggle Promotion Picker in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Demonstrates how to toggle the visibility of the pawn promotion picker using the `togglePromotionPicker()` method of `ChessboardModel`. This can be used to show or hide the picker as needed. ```swift func togglePromotionPicker() ``` -------------------------------- ### Set Chessboard Perspective for Player View Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code shows how to initialize a ChessboardModel with a specific perspective, such as `.white`, to ensure the board is oriented correctly for the current player's view. ```swift @State var chessboardModel = ChessboardModel(fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", perspective: .white) ``` -------------------------------- ### Highlight Squares Temporarily in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Demonstrates how to highlight squares on the chessboard for a specific duration using the `hint` methods with a `seconds` parameter. After the specified time, the highlighting will automatically be removed. ```swift // Highlight squares for a specific duration func hint(_ square: String, for seconds: Double) func hint(_ squares: [String], for seconds: Double) func hint(_ squares: [BoardSquare], for seconds: Double) func hint(_ square: BoardSquare, for seconds: Double) ``` -------------------------------- ### Enable Waiting State in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to indicate a waiting state on the chessboard using the `beginWaiting()` method of `ChessboardModel`. This can be used to visually communicate that the application is processing a move or waiting for input. ```swift chessboardModel.beginWaiting() ``` -------------------------------- ### Highlight Multiple Squares in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to highlight multiple squares on the chessboard simultaneously using the `hint` methods of `ChessboardModel`. You can provide an array of `BoardSquare` objects or string representations of squares. ```swift func hint(_ squares: [BoardSquare]) func hint(_ squares: [String]) ``` -------------------------------- ### Set Chessboard FEN String Programmatically Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code demonstrates how to update the chessboard's state by programmatically setting a new FEN string using the `setFen` method. This is useful for loading different board positions or game states. ```swift chessboardModel.setFen("New FEN string") ``` -------------------------------- ### Implement Move Logic with Chess Engine Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code shows how to handle a legal move within the `.onMove` callback. It updates the internal chess engine state using `chessboardModel.game.make(move:)` and then updates the FEN string for the chessboard view. ```swift .onMove { move, isLegal, from, to, lan, promotionPiece in print("Move: Fen: \(chessboardModel.fen) - Lan: \(lan)") if !isLegal { print("Illegal move: \(lan)") return } chessboardModel.game.make(move: move) chessboardModel.setFen(FenSerialization.default.serialize(position: chessboardModel.game.position), lan: lan) } ``` -------------------------------- ### Set New Board Position in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to set a new board position using a FEN string with the `setFen(_:lan:)` method of `ChessboardModel`. An optional `lan` parameter can be provided to animate the opponent's move. ```swift // Set a new FEN position with optional animation of opponent's move func setFen(_ fen: String, lan: String? = nil) ``` -------------------------------- ### Define Custom Chessboard Color Schemes (Swift) Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to implement a custom color scheme for the chessboard by conforming to the ChessboardColorScheme protocol. This allows for complete control over the appearance of board elements like squares, labels, and move indicators. ```swift public protocol ChessboardColorScheme: Sendable { var light: Color { get } var dark: Color { get } var label: Color { get } var selected: Color { get } var hinted: Color { get } var legalMove: Color { get } } public struct CustomColorScheme: ChessboardColorScheme { public var light: Color = Color.white public var dark: Color = Color.black public var label: Color = Color.gray public var selected: Color = Color.blue public var hinted: Color = Color.red public var legalMove: Color = Color(red: 0.30, green: 0.30, blue: 0.30, opacity: 0.4) } @State var chessboardModel = ChessboardModel(colorScheme: CustomColorScheme()) ``` -------------------------------- ### SwiftUI Preview for ContentView Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md A standard SwiftUI preview provider that allows developers to quickly view and iterate on the `ContentView` within Xcode's canvas. ```swift #Preview { ContentView() } ``` -------------------------------- ### Handle Pawn Promotion in SwiftUI Source: https://context7.com/rohanrhu/chessboardkit/llms.txt This Swift code showcases how ChessboardKit automatically handles pawn promotions in SwiftUI. When a pawn reaches the last rank, a promotion picker is displayed. The `onMove` callback provides the `promotionPiece` if a promotion occurs. It also includes a manual demo for toggling the promotion picker and checking promotable moves. ```swift import SwiftUI import ChessboardKit import ChessKit struct PromotionView: View { // Position with pawn ready to promote @State var chessboardModel = ChessboardModel( fen: "8/P7/8/8/8/8/8/4K2k w - - 0 1" ) var body: some View { Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in print("Move: (lan)") // promotionPiece is non-nil when pawn promotes if let promotion = promotionPiece { print("Promoted to: (promotion)") // .queen, .rook, .bishop, .knight } guard isLegal else { return } chessboardModel.game.make(move: move) chessboardModel.setFen( FenSerialization.default.serialize(position: chessboardModel.game.position) ) } .frame(width: 300, height: 300) } } // Manual promotion picker control struct ManualPromotionDemo: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ) var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) Button("Toggle Promotion Picker") { chessboardModel.togglePromotionPicker() } // Check if a pawn move would result in promotion Button("Check Promotable") { if let pawn = chessboardModel.game.position.board[48] { // a7 let isPromotable = chessboardModel.isPromotable(piece: pawn, lan: "a7a8") print("Move a7a8 promotable: (isPromotable)") } } } } } ``` -------------------------------- ### ChessboardModel API Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Documentation for the `ChessboardModel` class, the core data model for managing the chessboard state, including its properties and methods. ```APIDOC ## ChessboardModel `ChessboardModel` is the core data model that manages the state of the chessboard. It provides properties and methods to interact with the chessboard programmatically. ### Properties - `fen`: `String` - The current FEN string representation of the board position - `size`: `CGFloat` - The size of the chessboard in points - `colorScheme`: `ChessboardColorScheme` - The color scheme used for the board - `perspective`: `PieceColor` - The side of the board (white or black) that appears at the bottom - `turn`: `PieceColor` - The current player's turn (white or black) - `validateMoves`: `Bool` - Whether to validate moves according to chess rules - `allowOpponentMove`: `Bool` - Whether to allow moves for the opponent - `inWaiting`: `Bool` - Indicates if the board is in a waiting state - `selectedSquare`: `BoardSquare?` - The currently selected square on the board - `hintedSquares`: `Set` - A set of squares that are highlighted - `highlightLegalMoves`: `Bool` - Whether to highlight legal moves when a piece is selected or dragged (default: `true`) - `legalMoveSquares`: `Set` - A set of squares that represent legal move destinations - `showPromotionPicker`: `Bool` - Whether the promotion picker is currently displayed - `game`: `Game` - The underlying chess game object - `currentMove`: `Move?` and `prevMove: Move?` - Current and previous move objects - `promotionPiece`: `Piece?` - The piece being promoted when a promotion is in progress - `shouldFlipBoard`: `Bool` - Whether the board should be flipped based on perspective - `movingPiece`: `(piece: Piece, from: BoardSquare, to: BoardSquare)?` - Piece currently being animated - `onMove`: `(Move, Bool, String, String, String, PieceKind?) -> Void` - Callback for moves ### Methods `ChessboardModel` provides various methods to manipulate and interact with the chessboard. #### Board Position Management Methods to set and manage the board position: ```swift // Set a new FEN position with optional animation of opponent's move func setFen(_ fen: String, lan: String? = nil) ``` #### Square Selection Methods to manage the selected squares: ```swift // Deselect the currently selected square func deselect() ``` #### Square Highlighting Methods to highlight squares for visual feedback: ```swift // Highlight squares using various methods func hint(_ square: BoardSquare) func hint(_ square: String) func hint(row: Int, column: Int) func hint(_ squares: [BoardSquare]) func hint(_ squares: [String]) // Clear all highlighted squares func clearHint() // Highlight squares for a specific duration func hint(_ square: String, for seconds: Double) func hint(_ squares: [String], for seconds: Double) func hint(_ squares: [BoardSquare], for seconds: Double) func hint(_ square: BoardSquare, for seconds: Double) ``` #### Promotion Management Methods to handle pawn promotion: ```swift // Manage the promotion picker func presentPromotionPicker(piece: Piece, sourceSquare: String, targetSquare: String, lan: String) func absentePromotionPicker() func togglePromotionPicker() // Check if a move is a pawn promotion func isPromotable(piece: Piece, lan: String) -> Bool ``` ``` -------------------------------- ### SwiftUI Chessboard with FEN and Move Handling Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This Swift code defines a SwiftUI view for an interactive chessboard using ChessboardKit. It initializes the board with a FEN string, handles user moves, updates the FEN notation based on game state, and allows for FEN input validation. It also includes a slider for resizing the board and buttons for printing the current FEN and resetting the board. ```swift import SwiftUI import ChessboardKit import ChessKit struct ContentView: View { var body: some View { VStack { TestBoard() } .ignoresSafeArea() .preferredColorScheme(.light) } } public struct TestBoard: View { static let POSITION = "5k2/1P2bn2/8/8/8/3Q4/3K4/8 w - - 0 1" @State var showError: Bool = false @State var errorMessage: String = "" @State var size: CGFloat = 350 @Bindable var chessboardModel = ChessboardModel(fen: POSITION, perspective: .white, colorScheme: .light) @State var fen = POSITION var backgroundAnimationStartDate = Date() public var body: some View { VStack(spacing: 20) { VStack {}.frame(height: 50) Text("ChessboardKit Sample") .font(.title) .fontWeight(.bold) Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in print("Move: Fen: \(chessboardModel.fen) - Lan: \(lan)") if !isLegal { print("Illegal move: \(lan)") return } chessboardModel.game.make(move: move) chessboardModel.setFen(FenSerialization.default.serialize(position: chessboardModel.game.position), lan: lan) } .frame(width: size, height: size) .padding(5) .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.gray, lineWidth: 1)) VStack(alignment: .leading) { Text("FEN Notation:") .fontWeight(.medium) TextField("Enter FEN", text: $fen) .padding(10) .background( RoundedRectangle(cornerRadius: 8) .stroke(Color.gray, lineWidth: 1) ) .onChange(of: fen) { _, newValue in if !FenValidation.validateFen(newValue) { showError = true errorMessage = "Invalid FEN notation." return } else { showError = false errorMessage = "" } chessboardModel.setFen(newValue) } .onChange(of: chessboardModel.fen) { fen = chessboardModel.fen } if showError { Text(errorMessage) .foregroundColor(.red) .font(.caption) } } Slider(value: $size, in: 200...350, step: 10) { Text("Board Size: \(Int(chessboardModel.size))") } minimumValueLabel: { Text("200") } maximumValueLabel: { Text("350") } .padding(.horizontal) Text("Board Size: \(Int(size))") .font(.caption) HStack { Button { print(FenSerialization.default.serialize(position: chessboardModel.game.position)) } label: { Text("Print FEN") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .buttonStyle(.plain) Button { withAnimation { chessboardModel.fen = Self.POSITION } } label: { Text("Reset") .padding() .background(Color.red) .foregroundColor(.white) .cornerRadius(8) .modifier { if chessboardModel.fen == Self.POSITION { $0.opacity(0.5) } else { $0 } } } .disabled(chessboardModel.fen == Self.POSITION) Button { chessboardModel.hint("d3", for: 1) } label: { Text("Hint") .padding() .background(Color.yellow) .foregroundColor(.black) ``` -------------------------------- ### Highlight Single Square in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Demonstrates various ways to highlight a single square on the chessboard using the `hint` methods of `ChessboardModel`. Squares can be hinted using `BoardSquare` objects, string representations, or row/column integers. ```swift // Highlight squares using various methods func hint(_ square: BoardSquare) func hint(_ square: String) func hint(row: Int, column: Int) ``` -------------------------------- ### Control Board Perspective with SwiftUI Source: https://context7.com/rohanrhu/chessboardkit/llms.txt Demonstrates how to control the board's perspective (white or black at the bottom) using the `perspective` property in SwiftUI. This allows for easy switching between player views. ```swift import SwiftUI import ChessboardKit import ChessKit struct PerspectiveView: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", perspective: .white // White pieces at bottom ) var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) HStack { Button("White Perspective") { chessboardModel.perspective = .white } Button("Black Perspective") { chessboardModel.perspective = .black } Button("Toggle") { chessboardModel.perspective = chessboardModel.perspective == .white ? .black : .white } } Text("Board flipped: (chessboardModel.shouldFlipBoard ? "Yes" : "No")") } } } ``` -------------------------------- ### Control Chessboard Interaction State (Swift) Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Methods to control the waiting state of the chessboard. These functions allow you to visually indicate when the board is processing or waiting for input. ```swift func beginWaiting() func endWaiting() ``` -------------------------------- ### Highlight a Specific Square on the Chessboard Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code snippet demonstrates how to highlight a particular square on the chessboard by calling the `hint` method on the `chessboardModel` with the desired row and column. ```swift chessboardModel.hint(row: 3, column: 4) ``` -------------------------------- ### Animate Chessboard FEN Updates with Custom Animation Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This snippet demonstrates using `withAnimation` with a custom animation curve and duration to animate FEN string updates on the chessboard, providing more control over the visual transition. ```swift withAnimation(.bouncy(duration: 1.)) { chessboardModel.setFen("New FEN string", lan: "Move LAN string") } ``` -------------------------------- ### Enable Move Legality Check in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Demonstrates how to enable the `Chessboard` view to check the legality of moves according to chess rules. This is done by setting the `validateMoves` property of `ChessboardModel` to `true`. ```swift @State var chessboardModel = ChessboardModel(validateMoves: true) ``` -------------------------------- ### Check if Move is Promotable in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Shows how to determine if a given move involves a pawn promotion using the `isPromotable(piece:lan:)` method of `ChessboardModel`. This method checks if the piece is a pawn and if the move leads to the promotion rank. ```swift // Check if a move is a pawn promotion func isPromotable(piece: Piece, lan: String) -> Bool ``` -------------------------------- ### Apply Color Schemes to Chessboard Source: https://context7.com/rohanrhu/chessboardkit/llms.txt Shows how to apply built-in color schemes like `.light`, `.dark`, `.blue`, etc., or create custom color schemes by conforming to the `ChessboardColorScheme` protocol. This allows for extensive visual customization. ```swift import SwiftUI import ChessboardKit // Using built-in color schemes let lightBoard = ChessboardModel(colorScheme: .light) let darkBoard = ChessboardModel(colorScheme: .dark) let blueBoard = ChessboardModel(colorScheme: .blue) let greenBoard = ChessboardModel(colorScheme: .green) let orangeBoard = ChessboardModel(colorScheme: .orange) let redBoard = ChessboardModel(colorScheme: .red) let yellowBoard = ChessboardModel(colorScheme: .yellow) let purpleBoard = ChessboardModel(colorScheme: .purple) // Creating a custom color scheme struct WoodColorScheme: ChessboardColorScheme { var light: Color = Color(red: 0.96, green: 0.87, blue: 0.70) // Light wood var dark: Color = Color(red: 0.71, green: 0.53, blue: 0.39) // Dark wood var label: Color = Color(red: 0.20, green: 0.15, blue: 0.10) // Dark brown var selected: Color = Color(red: 0.20, green: 0.80, blue: 0.20) var hinted: Color = Color(red: 0.90, green: 0.30, blue: 0.20) var legalMove: Color = Color(red: 0.30, green: 0.30, blue: 0.30, opacity: 0.4) } struct ColorSchemeDemo: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", colorScheme: WoodColorScheme() ) var body: some View { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) } } ``` -------------------------------- ### Complete Chess Game in SwiftUI with ChessboardKit Source: https://context7.com/rohanrhu/chessboardkit/llms.txt This Swift code provides a full implementation of a playable chess game using SwiftUI and ChessboardKit. It includes features like move history, game status updates, board perspective flipping, new game initialization, and move hints. The `ChessboardModel` is configured with various options to create a rich user experience. ```swift import SwiftUI import ChessboardKit import ChessKit struct CompleteChessGame: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", perspective: .white, colorScheme: .blue, allowOpponentMove: false, highlightLegalMoves: true ) @State var moveHistory: [String] = [] @State var gameStatus = "White to move" var body: some View { VStack(spacing: 20) { Text("Chess Game") .font(.title) .fontWeight(.bold) Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in guard isLegal else { gameStatus = "Illegal move!" return } // Record move var notation = lan if let piece = promotionPiece { notation += "=\(piece)" } moveHistory.append(notation) // Execute move chessboardModel.game.make(move: move) withAnimation(.easeInOut(duration: 0.3)) { chessboardModel.setFen( FenSerialization.default.serialize(position: chessboardModel.game.position), lan: lan ) } // Update status let turn = chessboardModel.turn == .white ? "White" : "Black" gameStatus = "\(turn) to move" if chessboardModel.game.legalMoves.isEmpty { gameStatus = "Game Over!" } } .frame(width: 350, height: 350) Text(gameStatus) .font(.headline) HStack { Button("Flip Board") { chessboardModel.perspective = chessboardModel.perspective == .white ? .black : .white } Button("New Game") { chessboardModel.fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" moveHistory.removeAll() gameStatus = "White to move" } Button("Hint Best Square") { if let firstMove = chessboardModel.game.legalMoves.first { let square = "\(Character(UnicodeScalar(firstMove.to.file + 97)!))\(firstMove.to.rank + 1)" chessboardModel.hint(square, for: 2.0) } } } ScrollView { Text("Moves: \(moveHistory.joined(separator: ", "))") .font(.caption) } .frame(height: 60) } .padding() } } ``` -------------------------------- ### Legal Move Highlighting Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Controls the highlighting of legal moves on the chessboard. This feature is enabled by default and can be customized. ```APIDOC ## Legal Move Highlighting ### Description Automatically highlights legal moves when a piece is selected or dragged. This feature is enabled by default and shows dots on squares where the selected piece can legally move. ### Configuration To disable automatic legal move highlighting: ```swift @State var chessboardModel = ChessboardModel(fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", highlightLegalMoves: false) // Or set it later: chessboardModel.highlightLegalMoves = false ``` The legal move dots are displayed using the `legalMove` color from your color scheme, which can be customized (see [Color Schemes](#color-schemes)). ``` -------------------------------- ### Implement Waiting State in SwiftUI Source: https://context7.com/rohanrhu/chessboardkit/llms.txt This Swift code demonstrates how to implement a waiting state in a SwiftUI view using ChessboardKit. It disables user interaction on the chessboard while simulating an AI's thinking process. The `beginWaiting()` and `endWaiting()` methods are used to control the board's interactivity. ```swift import SwiftUI import ChessboardKit struct WaitingStateDemo: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ) @State var isThinking = false var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in guard isLegal else { return } // Execute player's move chessboardModel.game.make(move: move) chessboardModel.setFen( FenSerialization.default.serialize(position: chessboardModel.game.position) ) // Enter waiting state while "thinking" chessboardModel.beginWaiting() isThinking = true // Simulate AI thinking time Task { try? await Task.sleep(for: .seconds(2)) // End waiting state await MainActor.run { chessboardModel.endWaiting() isThinking = false } } } .frame(width: 300, height: 300) Text(isThinking ? "AI is thinking..." : "Your turn") Text("Board locked: (chessboardModel.inWaiting ? "Yes" : "No")") } } } ``` -------------------------------- ### SwiftUI Background with Animated Circles Shader Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This SwiftUI snippet implements a dynamic background using `TimelineView` and a custom shader `ShaderLibrary.circlesBackground`. It creates a visually appealing effect with animated circles, utilizing `visualEffect` for rendering. ```swift .background { GeometryReader { proxy in ZStack { TimelineView(.animation) { context in Color.white .scaledToFill() .visualEffect { content, proxy in content .colorEffect(ShaderLibrary.circlesBackground( .boundingRect, .float(backgroundAnimationStartDate.timeIntervalSinceNow), .color(Color(hue: 0.0, saturation: 0.0, brightness: 0.935)), .color(Color(hue: 0.0, saturation: 0.0, brightness: 0.890)) )) } } LinearGradient( stops: [ .init(color: .white.opacity(0.1), location: 0), .init(color: .white.opacity(0.9), location: 0.33) ], startPoint: .top, endPoint: .bottom ) } .frame(width: proxy.size.width, height: proxy.size.height) .clipped() } } ``` -------------------------------- ### Add ChessboardKit Dependency to Package.swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This snippet shows how to add ChessboardKit as a dependency in your Swift Package Manager's Package.swift file. Ensure you are using version 1.0.0 or later. ```swift .package(url: "https://github.com/rohanrhu/ChessboardKit.git", from: "1.0.0") ``` -------------------------------- ### Highlight Squares on Chessboard (Swift) Source: https://context7.com/rohanrhu/chessboardkit/llms.txt The `hint` methods in ChessboardKit enable highlighting specific squares on the chessboard. This functionality supports highlighting single squares or multiple squares simultaneously, using algebraic notation, row/column coordinates, or `BoardSquare` objects. Hints can also be timed to clear automatically. ```swift import SwiftUI import ChessboardKit struct HintDemoView: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ) var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) HStack { Button("Hint e4") { // Hint using algebraic notation chessboardModel.hint("e4") } Button("Hint Multiple") { // Hint multiple squares at once chessboardModel.hint(["e4", "d4", "c4"]) } Button("Hint by Coords") { // Hint using row/column (0-indexed) chessboardModel.hint(row: 3, column: 4) // e4 } Button("Hint with BoardSquare") { let square = BoardSquare(row: 3, column: 4) chessboardModel.hint(square) } } HStack { Button("Timed Hint (1s)") { // Hint that auto-clears after duration chessboardModel.hint("e4", for: 1.0) } Button("Clear Hints") { chessboardModel.clearHint() } } } } } ``` -------------------------------- ### Waiting State and User Interaction Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Manages the waiting state of the chessboard to prevent user interaction during animations or processing. ```APIDOC ## Waiting State and Avoiding User Interaction ### Description Indicates a waiting state on the board, which can be used to disable user interaction during animations or asynchronous operations. ### Methods To begin the waiting state: ```swift chessboardModel.beginWaiting() ``` To end the waiting state: ```swift chessboardModel.endWaiting() ``` ``` -------------------------------- ### Remove Promotion Picker in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Illustrates how to programmatically remove the pawn promotion picker from the chessboard using the `absentePromotionPicker()` method of `ChessboardModel`. This is called when the promotion process is complete or cancelled. ```swift func absentePromotionPicker() ``` -------------------------------- ### SwiftUI Button with Dynamic Background and Corner Radius Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This SwiftUI code defines a button that toggles the visibility of a promotion picker. The button's background color changes based on the picker's state (red for visible, green for hidden), and it has rounded corners. ```swift Button { chessboardModel.togglePromotionPicker() } label: { VStack { if chessboardModel.showPromotionPicker { Text("Hide Promotion Picker") } else { Text("Show Promotion Picker") } } .padding() .background(chessboardModel.showPromotionPicker ? Color.red : Color.green) .foregroundColor(.white) .cornerRadius(8) } .buttonStyle(.plain) ``` -------------------------------- ### Highlight Legal Moves in SwiftUI with ChessboardKit Source: https://context7.com/rohanrhu/chessboardkit/llms.txt This Swift code demonstrates how to enable and manage legal move highlighting on a chessboard using SwiftUI and ChessboardKit. It allows users to toggle the highlighting feature, programmatically show legal moves for a specific piece, and clear all highlights. The `highlightLegalMoves` property in `ChessboardModel` controls this functionality. ```swift import SwiftUI import ChessboardKit struct LegalMoveHighlightDemo: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", highlightLegalMoves: true // Default is true ) var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in guard isLegal else { return } chessboardModel.game.make(move: move) chessboardModel.setFen( FenSerialization.default.serialize(position: chessboardModel.game.position) ) } .frame(width: 300, height: 300) Toggle("Highlight Legal Moves", isOn: Binding( get: { chessboardModel.highlightLegalMoves }, set: { chessboardModel.highlightLegalMoves = $0 } )) // Programmatic control of legal move squares Button("Show e2 Legal Moves") { let e2Square = BoardSquare(row: 1, column: 4) chessboardModel.updateLegalMoveHighlights(for: e2Square) } Button("Clear Legal Move Highlights") { chessboardModel.clearLegalMoveHighlights() } Text("Highlighted squares: \(chessboardModel.legalMoveSquares.count)") } } } ``` -------------------------------- ### End Waiting State in Swift Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Illustrates how to end the waiting state on the chessboard by calling the `endWaiting()` method of `ChessboardModel`. This should be called after the waiting operation is complete to restore normal interaction. ```swift chessboardModel.endWaiting() ``` -------------------------------- ### Update Chessboard Position with FEN and Animation (Swift) Source: https://context7.com/rohanrhu/chessboardkit/llms.txt The `setFen` method in ChessboardKit allows updating the board's position using FEN strings. It can optionally animate piece movements when a LAN (Long Algebraic Notation) is provided, offering control over animation curves and durations. ```swift import SwiftUI import ChessboardKit import ChessKit struct FenDemoView: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ) var body: some View { VStack { Chessboard(chessboardModel: chessboardModel) .frame(width: 300, height: 300) HStack { Button("Set Position") { // Set FEN directly (no animation) chessboardModel.fen = "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4" } Button("Animated Move") { // Set FEN with animation using lan parameter withAnimation { chessboardModel.setFen( "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1", lan: "e2e4" ) } } Button("Custom Animation") { withAnimation(.bouncy(duration: 1.0)) { chessboardModel.setFen( "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq e6 0 2", lan: "e7e5" ) } } } Text("Current FEN: \(chessboardModel.fen)") .font(.caption) } } } ``` -------------------------------- ### Clear All Highlighted Squares on the Chessboard Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This code shows how to remove all square highlights from the chessboard by calling the `clearHint` method on the `chessboardModel`. ```swift chessboardModel.clearHint() ``` -------------------------------- ### Directly Set Chessboard FEN String Property Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This snippet shows an alternative way to update the chessboard's FEN string by directly assigning a new value to the `fen` property of the `ChessboardModel`. ```swift chessboardModel.fen = "New FEN string" ``` -------------------------------- ### Move Legality Check Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md Enables or disables the built-in move legality check for the `Chessboard` view. ```APIDOC ## Move Legality Check ### Description If you want the `Chessboard` view to check the legality of moves, you can enable it with the `validateMoves` state of `ChessboardModel`. ### Configuration ```swift @State var chessboardModel = ChessboardModel(validateMoves: true) ``` ``` -------------------------------- ### Render Chessboard View and Handle Moves Source: https://context7.com/rohanrhu/chessboardkit/llms.txt The Chessboard view renders an interactive chessboard that adapts to its container size. The .onMove modifier allows you to handle piece movements, validate legality using ChessKit, and update the board's FEN string. ```swift import SwiftUI import ChessboardKit import ChessKit struct ChessGameView: View { @State var chessboardModel = ChessboardModel( fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ) var body: some View { Chessboard(chessboardModel: chessboardModel) .onMove { move, isLegal, from, to, lan, promotionPiece in // Parameters: // - move: The Move object from ChessKit // - isLegal: Whether the move is legal according to chess rules // - from: Source square (e.g., "e2") // - to: Target square (e.g., "e4") // - lan: Long algebraic notation (e.g., "e2e4") // - promotionPiece: PieceKind if pawn promotion, nil otherwise if !isLegal { print("Illegal move: \(lan)") return } // Execute the move on the chess engine chessboardModel.game.make(move: move) // Update the board with new position let newFen = FenSerialization.default.serialize( position: chessboardModel.game.position ) chessboardModel.setFen(newFen, lan: lan) } .frame(width: 400, height: 400) .padding() } } ``` -------------------------------- ### Customize Chessboard Size with frame Modifier Source: https://github.com/rohanrhu/chessboardkit/blob/main/README.md This snippet illustrates how to resize the Chessboard view using the standard SwiftUI `.frame` modifier. This allows you to control the dimensions of the chessboard displayed on the screen. ```swift Chessboard(chessboardModel: chessboardModel) .frame(width: 400, height: 400) ```