-
Notifications
You must be signed in to change notification settings - Fork 1
/
AIPlayer.swift
121 lines (72 loc) · 4.15 KB
/
AIPlayer.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//
// AIPlayer.swift
// Chess
//
// Created by Adnan Zahid on 8/22/16.
// Copyright © 2016 Chess. All rights reserved.
//
class AIPlayer: Player {
override init(color: Color) {
super.init(color: color)
isAI = true
}
override func generateMove() -> Move? {
let evaluationMove: EvaluationMove = firstAlphaBeta(kMaxPlies, player: self, alpha: Int.min/2, beta: Int.max/2)
return Move(fromSquare: evaluationMove.fromSquare!, toSquare: evaluationMove.toSquare!)
}
func firstAlphaBeta(_ depth: Int, player: Player, alpha: Int, beta: Int) -> EvaluationMove {
var bestMove: EvaluationMove = EvaluationMove(fromSquare: nil, toSquare: nil, evaluationValue: Int.min/2)
for piece in player.piecesList {
if piece.captured == false {
let fromSquare: Square = piece.position!
for toSquare in (piece.moveStrategy?.generateAllMoves(fromSquare))! {
if player.movePiece(Move(fromSquare: fromSquare, toSquare: toSquare), checkCurrentTurn: false) {
var localAlpha: Int = alpha
let evaluationMove: EvaluationMove = EvaluationMove(fromSquare: fromSquare, toSquare: toSquare, evaluationValue: -alphaBeta(depth - 1, player: player.opponent!, alpha: -beta, beta: -localAlpha))
Board.sharedInstance.undoMove()
if evaluationMove.evaluationValue > bestMove.evaluationValue {
bestMove = evaluationMove
}
if bestMove.evaluationValue >= beta {
break
} else if bestMove.evaluationValue > alpha {
localAlpha = bestMove.evaluationValue
}
}
}
}
}
return bestMove
}
func alphaBeta(_ depth: Int, player: Player, alpha: Int, beta: Int) -> Int {
if depth == 0 {
if player.color == Color.white {
return Board.sharedInstance.evaluationValue
} else {
return -Board.sharedInstance.evaluationValue
}
}
var bestEvaluationValue: Int = Int.min/2
for piece in player.piecesList {
if piece.captured == false {
let fromSquare: Square = piece.position!
for toSquare in (piece.moveStrategy?.generateAllMoves(fromSquare))! {
if player.movePiece(Move(fromSquare: fromSquare, toSquare: toSquare), checkCurrentTurn: false) {
var localAlpha: Int = alpha
let evaluationValue: Int = -alphaBeta(depth - 1, player: player.opponent!, alpha: -beta, beta: -localAlpha)
Board.sharedInstance.undoMove()
if evaluationValue > bestEvaluationValue {
bestEvaluationValue = evaluationValue
}
if bestEvaluationValue >= beta {
break
} else if bestEvaluationValue > alpha {
localAlpha = bestEvaluationValue
}
}
}
}
}
return bestEvaluationValue
}
}