SwiftChess
SwiftChess 是用 Swift 编写的棋引擎。
特性
- 走法验证
- 具有三个难度级别的 AI
- 将兵吃王、将死和mkdir提将的回调
- 支持长将
- 支持终极通过
- 支持兵的升变
- 异步 AI 移动计算
SwiftChess 不提供任何 UI,只包含创建棋局所需的所有逻辑。示例项目包含一个完全的 UIKit UI,带有触摸处理,如果你喜欢,可以从这里开始。
示例
示例应用程序包含对 SwiftChess 的完整实现。
运行 Example/Example.xcodeproj
基本用法
开始游戏
// Make a human player
let whitePlayer = Human(color: .white)
// ... or an AI Player
let blackPlayer = AIPlayer(color: .black, configuration: AIConfiguration(difficulty: .hard))
// Create a game
let game = Game(firstPlayer: whitePlayer, secondPlayer: blackPlayer)
走一步棋
if let player = game.currentPlayer as? Human {
let currentLocation = BoardLocation(x: 4, y: 1)
let newLocation = BoardLocation(x: 4, y: 2)
try! player.movePiece(from: currentLocation,
to: newLocation)
}
指示AI走一步棋
if let player = game.currentPlayer as? AIPlayer {
player.makeMoveAsync()
}
然后只需等待回调!
extension GameViewController: GameDelegate {
func gameDidMovePiece(game: Game, piece: Piece, toLocation: BoardLocation) {
// Move piece on board
}
func gameDidRemovePiece(game: Game, piece: Piece, location: BoardLocation) {
// Remove piece from board
}
func gameDidTransformPiece(game: Game, piece: Piece, location: BoardLocation) {
// A pawn was promoted!
}
func gameWonByPlayer(game: Game, player: Player) {
ShowAlert("Checkmate!")
}
func gameEndedInStaleMate(game: Game) {
ShowAlert("Stalemate!")
}
func gameDidChangeCurrentPlayer(game: Game) {
// Make another move
}
}
坚持不懈
将整个 SwiftChess 游戏状态可以转换为从 字典
初始化。
获取当前状态的快照
let dictionary: [String: Any] = game.dictionaryRepresentation
使用先前快照初始化游戏
let game = Game(dictionary: dictionary)
返回的字典存储了创建“保存游戏”功能所需的所有信息。玩家颜色、AI难度、棋子位置等。
您可以将此序列化为JSON,将其保存到磁盘,通过网络发送等。
其他内容
进行王车易位
if game.board.canColorCastle(color: .white, side: .kingSide) {
player.performCastleMove(side: .kingSide)
}
支持兵的升变
func promotedTypeForPawn(location: BoardLocation,
player: Human,
possiblePromotions: [Piece.PieceType],
callback: @escaping (Piece.PieceType) -> Void) {
// Show UI for the user to select one of the possible promotion types
// then call the handler
// ...or some games just promote to a queen
callback(.queen)
}
作者
在twitter上关注我 @SteveBarnegren
许可
SwiftChess可在MIT许可下使用。请查阅LICENSE文件以获取更多信息。