4 Commits

Author SHA1 Message Date
Steve Barnegren 99dd6adbcd Bump version to 1.1.2 2020-10-12 20:58:50 +01:00
Steve Barnegren 59a4aba058 Fixed crash where player could access game after game has been deallocated 2020-10-12 20:53:03 +01:00
Steve Barnegren c2e7b7ccb9 Minor improvements to example app 2020-10-12 20:43:38 +01:00
Steve Barnegren 1a560c00d0 Removed unused logging 2020-10-12 20:37:55 +01:00
12 changed files with 68 additions and 80 deletions
+13 -16
View File
@@ -1,24 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="o9i-0S-2Up">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="o9i-0S-2Up">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="Aspect ratio constraints" minToolsVersion="5.1"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Navigation Controller-->
<scene sceneID="HEd-Os-R93">
<objects>
<navigationController navigationBarHidden="YES" id="o9i-0S-2Up" sceneMemberID="viewController">
<navigationController id="o9i-0S-2Up" sceneMemberID="viewController">
<nil key="simulatedStatusBarMetrics"/>
<nil key="simulatedTopBarMetrics"/>
<nil key="simulatedBottomBarMetrics"/>
<navigationBar key="navigationBar" contentMode="scaleToFill" id="e3D-Nu-dRp">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -44,21 +41,21 @@
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="KRf-s7-H9a">
<rect key="frame" x="133.5" y="264.5" width="108" height="138"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="fGu-y2-Qxm">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="fGu-y2-Qxm">
<rect key="frame" x="0.0" y="92" width="108" height="30"/>
<state key="normal" title="AI vs AI"/>
<connections>
<action selector="AIvsAIButtonPressed:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="mrX-sU-WvD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="kEX-Ea-5Xq">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="kEX-Ea-5Xq">
<rect key="frame" x="0.0" y="46" width="108" height="30"/>
<state key="normal" title="Player vs Player"/>
<connections>
<action selector="playerVsPlayerButtonPressed:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="xIZ-0U-CNW"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="gcM-Gf-hHc">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="gcM-Gf-hHc">
<rect key="frame" x="0.0" y="0.0" width="108" height="30"/>
<state key="normal" title="Player vs AI"/>
<connections>
@@ -112,28 +109,28 @@
<constraint firstAttribute="width" secondItem="NnZ-Ew-a2B" secondAttribute="height" multiplier="1:1" id="GNF-YV-5Vh"/>
</constraints>
</view>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ZZ0-mR-VXd">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ZZ0-mR-VXd">
<rect key="frame" x="8" y="116" width="44" height="30"/>
<state key="normal" title="Castle"/>
<connections>
<action selector="blackKingSideCastleButtonPressedWithSender:" destination="M5V-oM-g1K" eventType="touchUpInside" id="rLk-f9-Sot"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eZD-P8-Hr3">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eZD-P8-Hr3">
<rect key="frame" x="323" y="116" width="44" height="30"/>
<state key="normal" title="Castle"/>
<connections>
<action selector="blackQueenSideCastleButtonPressedWithSender:" destination="M5V-oM-g1K" eventType="touchUpInside" id="04c-Bn-Bkt"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Yxk-YT-5FA">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Yxk-YT-5FA">
<rect key="frame" x="8" y="521" width="44" height="30"/>
<state key="normal" title="Castle"/>
<connections>
<action selector="whiteQueenSideCastleButtonPressedWithSender:" destination="M5V-oM-g1K" eventType="touchUpInside" id="3el-xi-NUE"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="FwI-ZC-g1Z">
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="FwI-ZC-g1Z">
<rect key="frame" x="323" y="521" width="44" height="30"/>
<state key="normal" title="Castle"/>
<connections>
@@ -141,7 +138,7 @@
</connections>
</button>
<activityIndicatorView opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="JEV-Ul-qRP">
<rect key="frame" x="177" y="121" width="20" height="20"/>
<rect key="frame" x="177.5" y="121" width="20" height="20"/>
</activityIndicatorView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
-3
View File
@@ -81,10 +81,7 @@ class BoardView: UIView {
// Get touch location
let location = touches.first!.location(in: self)
print("Touch at x: \(location.x) y: \(location.y)")
let boardIndex = boardIndexForLocation(location)
print("Board index: \(boardIndex)")
delegate?.touchedSquareAtIndex(self, index: boardIndex)
+1 -7
View File
@@ -211,7 +211,6 @@ class GameViewController: UIViewController {
// MARK: - Actions
@IBAction func whiteKingSideCastleButtonPressed(sender: UIButton) {
print("White king side castle button pressed")
if let player = game.currentPlayer as? Human {
player.performCastleMove(side: .kingSide)
@@ -219,7 +218,6 @@ class GameViewController: UIViewController {
}
@IBAction func whiteQueenSideCastleButtonPressed(sender: UIButton) {
print("White queen side castle button pressed")
if let player = game.currentPlayer as? Human {
player.performCastleMove(side: .queenSide)
@@ -227,7 +225,6 @@ class GameViewController: UIViewController {
}
@IBAction func blackKingSideCastleButtonPressed(sender: UIButton) {
print("Black king side castle button pressed")
if let player = game.currentPlayer as? Human {
player.performCastleMove(side: .kingSide)
@@ -235,7 +232,6 @@ class GameViewController: UIViewController {
}
@IBAction func blackQueenSideCastleButtonPressed(sender: UIButton) {
print("Black queen side castle button pressed")
if let player = game.currentPlayer as? Human {
player.performCastleMove(side: .queenSide)
@@ -248,9 +244,7 @@ class GameViewController: UIViewController {
extension GameViewController: BoardViewDelegate {
func touchedSquareAtIndex(_ boardView: BoardView, index: Int) {
print("GVC touched square at index \(index)")
// Get the player (must be human)
guard let player = game.currentPlayer as? Human else {
return
+10 -7
View File
@@ -11,41 +11,44 @@ import SwiftChess
class MenuViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "SwiftChess"
}
// MARK: - Actions
@IBAction func playerVsAIButtonPressed(_ sender: UIButton) {
print("Player vs AI button pressed")
let whitePlayer = Human(color: .white)
let blackPlayer = AIPlayer(color: .black, configuration: AIConfiguration(difficulty: .hard))
let game = Game(firstPlayer: whitePlayer, secondPlayer: blackPlayer)
startGame(game: game)
startGame(game: game, title: "Player vs AI")
}
@IBAction func playerVsPlayerButtonPressed(_ sender: UIButton) {
print("Player vs Player button pressed")
let whitePlayer = Human(color: .white)
let blackPlayer = Human(color: .black)
let game = Game(firstPlayer: whitePlayer, secondPlayer: blackPlayer)
startGame(game: game)
startGame(game: game, title: "Player vs Player")
}
@IBAction func AIvsAIButtonPressed(_ sender: UIButton) {
print("AI vs AI button pressed")
let whitePlayer = AIPlayer(color: .white, configuration: AIConfiguration(difficulty: .hard))
let blackPlayer = AIPlayer(color: .black, configuration: AIConfiguration(difficulty: .hard))
let game = Game(firstPlayer: whitePlayer, secondPlayer: blackPlayer)
startGame(game: game)
startGame(game: game, title: "AI vs AI")
}
func startGame(game: Game) {
func startGame(game: Game, title: String) {
let gameViewController = GameViewController.gameViewController(game: game)
gameViewController.title = title
self.navigationController?.pushViewController(gameViewController, animated: true)
}
@@ -73,11 +73,7 @@ class PromotionSelectionViewController: UIViewController {
@objc func buttonPressed(sender: UIButton) {
let index = buttons.firstIndex(of: sender)!
print("Button pressed at index: \(index)")
let chosenType = possibleTypes![index]
print("Chose promotion type: \(chosenType)")
callback(chosenType)
}
+1 -1
View File
@@ -8,7 +8,7 @@
Pod::Spec.new do |s|
s.name = 'SwiftChess'
s.version = '1.1.1'
s.version = '1.1.2'
s.summary = 'Chess engine written in Swift'
# This description is used to generate tags and improve search results.
+9 -15
View File
@@ -46,8 +46,8 @@ public final class AIPlayer: Player {
public func makeMoveSync() {
//print("\n\n****** Make Move ******");
guard let game = self.game else { return }
// Check that the game is in progress
guard game.state == .inProgress else {
return
@@ -59,7 +59,6 @@ public final class AIPlayer: Player {
// Get an opening move
if let openingMove = openingMove(for: board) {
//print("Playing opening move")
move = openingMove
}
// Or, get the Highest rated move
@@ -67,6 +66,9 @@ public final class AIPlayer: Player {
move = highestRatedMove(on: board)
}
// Check that the game still exists
if self.game == nil { return }
// Make move
var operations = [BoardOperation]()
@@ -156,7 +158,6 @@ public final class AIPlayer: Player {
let move = Move(type: .singlePiece(from: sourceLocation, to: targetLocation),
rating: rating)
possibleMoves.append(move)
// print("Rating: \(rating)")
}
}
@@ -164,7 +165,7 @@ public final class AIPlayer: Player {
let castleSides: [CastleSide] = [.kingSide, .queenSide]
for side in castleSides {
guard game.board.canColorCastle(color: color, side: side) else {
guard game?.board.canColorCastle(color: color, side: side) ?? false else {
continue
}
@@ -177,12 +178,10 @@ public final class AIPlayer: Player {
let move = Move(type: .castle(color: color, side: side), rating: rating)
possibleMoves.append(move)
}
//print("Found \(possibleMoves.count) possible moves")
// If there are no possible moves, we must be in stale mate
// If there are no possible moves, we must be in stale mate. This should never happen
if possibleMoves.count == 0 {
print("There are no possible moves!!!!")
print("There are no possible moves!")
}
// Choose move with highest rating
@@ -195,8 +194,6 @@ public final class AIPlayer: Player {
highestRating = move.rating
highestRatedMove = move
}
//print("rating: \(move.rating)")
}
return highestRatedMove
@@ -220,9 +217,6 @@ public final class AIPlayer: Player {
for boardRater in boardRaters {
let result = boardRater.ratingFor(board: board, color: color)
//let className = "\(boardRater)"
//print("\t\(className): \(result)")
rating += result
}
+22 -16
View File
@@ -21,6 +21,8 @@ public final class Human: Player {
public func movePiece(from fromLocation: BoardLocation, to toLocation: BoardLocation) throws {
guard let game = self.game else { return }
// Check that the game is in progress
guard game.state == .inProgress else {
throw MoveError.gameIsNotInProgress
@@ -48,22 +50,24 @@ public final class Human: Player {
let pawnLocation = promotablePawnLocations.first!
self.game.delegate?.promotedTypeForPawn(location: pawnLocation,
player: self,
possiblePromotions: Piece.PieceType.possiblePawnPromotionResultingTypes(),
callback: {
// Change the piece
let newPiece = self.game.board.squares[pawnLocation.index].piece?.byChangingType(newType: $0)
self.game.board.setPiece(newPiece!, at: pawnLocation)
// Add a transform piece operation
let modifyOperation = BoardOperation(type: .transformPiece, piece: newPiece!, location: pawnLocation)
operations.append(modifyOperation)
// Inform the delegate that we've finished
self.delegate?.playerDidMakeMove(player: self, boardOperations: operations)
})
game.delegate?.promotedTypeForPawn(location: pawnLocation,
player: self,
possiblePromotions: Piece.PieceType.possiblePawnPromotionResultingTypes(),
callback: {
guard let game = self.game else { return }
// Change the piece
let newPiece = game.board.squares[pawnLocation.index].piece?.byChangingType(newType: $0)
game.board.setPiece(newPiece!, at: pawnLocation)
// Add a transform piece operation
let modifyOperation = BoardOperation(type: .transformPiece, piece: newPiece!, location: pawnLocation)
operations.append(modifyOperation)
// Inform the delegate that we've finished
self.delegate?.playerDidMakeMove(player: self, boardOperations: operations)
})
}
// ... Or if no pawn promotions, end move
else {
@@ -75,6 +79,8 @@ public final class Human: Player {
}
public func performCastleMove(side: CastleSide) {
guard let game = self.game else { return }
// Check that we're the current player
guard game.currentPlayer === self else {
+9 -5
View File
@@ -15,12 +15,14 @@ protocol PlayerDelegate: class {
open class Player {
public var color: Color!
weak var game: Game!
weak var game: Game?
weak var delegate: PlayerDelegate?
public func occupiesSquare(at location: BoardLocation) -> Bool {
if let piece = self.game.board.getPiece(at: location) {
guard let game = game else { return false }
if let piece = game.board.getPiece(at: location) {
if piece.color == self.color {
return true
}
@@ -46,13 +48,15 @@ open class Player {
func canMovePiece(from fromLocation: BoardLocation, to toLocation: BoardLocation) throws -> Bool {
guard let game = self.game else { return false }
// We can't move to our current location
if fromLocation == toLocation {
throw MoveError.movingToSameLocation
}
// Get the piece
guard let piece = self.game.board.getPiece(at: fromLocation) else {
guard let piece = game.board.getPiece(at: fromLocation) else {
throw MoveError.noPieceToMove
}
@@ -67,8 +71,8 @@ open class Player {
}
// Move the piece
let inCheckBeforeMove = self.game.board.isColorInCheck(color: self.color)
var board = self.game.board
let inCheckBeforeMove = game.board.isColorInCheck(color: self.color)
var board = game.board
board.movePiece(from: fromLocation, to: toLocation)
let inCheckAfterMove = board.isColorInCheck(color: self.color)
@@ -616,7 +616,7 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.1.1;
MARKETING_VERSION = 1.1.2;
PRODUCT_BUNDLE_IDENTIFIER = SteveBarnegren.SwiftChess;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -636,7 +636,7 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.1.1;
MARKETING_VERSION = 1.1.2;
PRODUCT_BUNDLE_IDENTIFIER = SteveBarnegren.SwiftChess;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -844,7 +844,6 @@ class BoardTests: XCTestCase {
}
if piece.hasMoved {
print("Has moved flag set at index \(index)")
return true
}
}
@@ -26,9 +26,7 @@ class OpeningsTests: XCTestCase {
let openings = Opening.allOpenings()
for opening in openings {
print("Testing \(opening)")
var board = Board(state: .newGame)
for (source, target) in opening.moveLocations() {