Skip to content

Commit

Permalink
Improve undo logic
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Jul 12, 2024
1 parent 09e5607 commit 2b9d7dc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
8 changes: 3 additions & 5 deletions Chess/Game.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,15 @@ extension Game {
}
}

// MARK: Settings
// MARK: Game logic

var playerIsHuman: Bool {
switch turn {
func playerIsHuman(_ color: Color? = nil) -> Bool {
switch color ?? turn {
case .white: return whiteIsHuman
case .black: return blackIsHuman
}
}

// MARK: Game logic

func canSelectPiece(at position: Position) -> Bool {
board.piece(at: position)?.color == turn
}
Expand Down
8 changes: 4 additions & 4 deletions Chess/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class ViewController: UIViewController {
self.updateUI()
}, completion: { [weak self] _ in
guard let self = self else { return }
if !game.inProgress || self.game.playerIsHuman {
if self.game.playerIsHuman() || !self.game.playerIsHuman(game.turn.other) {
self.update()
} else {
self.undo()
Expand Down Expand Up @@ -136,7 +136,7 @@ extension ViewController: BoardViewDelegate {

private extension ViewController {
var canUndo: Bool {
(game.playerIsHuman || game.state == .checkMate) && game.inProgress
game.inProgress && (game.playerIsHuman() || game.playerIsHuman(game.turn.other))
}

func updateUI() {
Expand Down Expand Up @@ -189,7 +189,7 @@ private extension ViewController {
}

func makeComputerMove() {
if !game.playerIsHuman, let move = game.nextMove(for: game.turn) {
if !game.playerIsHuman(), let move = game.nextMove(for: game.turn) {
makeMove(move)
} else {
updateUI()
Expand All @@ -206,7 +206,7 @@ private extension ViewController {
let kingPosition = game.kingPosition(for: oldGame.turn)
let wasInCheck = game.pieceIsThreatened(at: kingPosition)
let wasPromoted = !wasInCheck && game.canPromotePiece(at: move.to)
let wasHuman = oldGame.playerIsHuman
let wasHuman = oldGame.playerIsHuman()
if wasInCheck {
game = oldGame
}
Expand Down

0 comments on commit 2b9d7dc

Please sign in to comment.