I've just finished coding the connect 4 game on python and added the minimax algorithm to it but (I might be exaggerating only a bit) it took a million years. So, I added Alpha-Beta pruning to it. However, it is still loading and looking for the best move as I am writing this post 10 minutes later.
Could any help and try optimizing it more. Thanks in advance.
def minimax(self, arr, a, b, depth, maximising):
result = self.checkWin(arr)
if result:
d = {'R': +1, 'B': -1, 'Tie': 0}
return d[result]
if maximising is True:
bestScore = -math.inf
for i, j in self.getPossible(self.board):
if arr[i][j] == '':
arr[i][j] = 'R'
score = self.minimax(arr, a, b, depth - 1, False)
arr[i][j] = ''
bestScore = max((score, bestScore))
a = max((a, score))
if b <= a:
break
return bestScore
else:
bestScore = math.inf
for i, j in self.getPossible(self.board):
if arr[i][j] == '':
arr[i][j] = 'B'
score = self.minimax(arr, a, b, depth - 1, True)
arr[i][j] = ''
bestScore = min((score, bestScore))
b = min((b, score))
if b <= a:
break
return bestScore
This is the evaluating function and i think i go all the way to the end of the minimax tree if i am not supposed to, then could someone tell me what value i should assign to non-terminal states of the tree.
There are in general 3 things you can do to speed up your AI:
First of all you need to find your bottleneck. How much time is spent finding all moves and how much is spent evaluating the position?
As of point 3 you have already implemented alpha-beta which makes it faster and also giving you the same result as without alpha-beta.
Another thing you can try is transposition tables. To simplify, you will in the table store information about the position as well as the evaluation for the position. So if you encounter the same position in the tree again you don't have to search the node and evaluate it, you just take the value from the transposition table.
You could look at chessprogramming.org for inspiration on what other pruning techniques you could apply for connect 4.