-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcomputer.py
More file actions
76 lines (70 loc) · 2.15 KB
/
computer.py
File metadata and controls
76 lines (70 loc) · 2.15 KB
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
import random
pieceScore = {"K": 0, "Q": 9, "R": 5, "B": 3, "N": 3, "p": 1}
CHECKMATE = 1000
STALEMATE = 0
DEPTH = 0
def findRandomMove(validMoves):
return random.choice(validMoves)
def findBestMoveAlphaBeta(gs, validMoves, AIDepth=0):
global nextMove
global DEPTH
DEPTH= AIDepth
nextMove = None
random.shuffle(validMoves)
alphaBeta(gs, validMoves, AIDepth, -CHECKMATE, CHECKMATE, 1 if gs.whiteToMove else -1)
return nextMove
def alphaBeta(gs, validMoves, depth, alpha, beta, turnMultiplier):
global nextMove
global DEPTH
if depth == 0:
return scoreBoard(gs)
if turnMultiplier == 1:
maxScore = -CHECKMATE
for move in validMoves:
gs.makeMove(move)
nextMoves = gs.getValidMoves()
score = alphaBeta(gs, nextMoves, depth - 1, alpha, beta, -turnMultiplier)
if score > maxScore:
maxScore = score
if depth == DEPTH:
nextMove = move
gs.undoMove()
alpha = max(alpha, maxScore)
if alpha >= beta:
break
return maxScore
else:
minScore = CHECKMATE
for move in validMoves:
gs.makeMove(move)
nextMoves = gs.getValidMoves()
score = alphaBeta(gs, nextMoves, depth - 1, alpha, beta, -turnMultiplier)
if score < minScore:
minScore = score
if depth == DEPTH:
nextMove = move
gs.undoMove()
beta = min(beta, minScore)
if alpha >= beta:
break
return minScore
def scoreBoard(gs):
if gs.checkmate:
if gs.whiteToMove:
return -CHECKMATE
else:
return CHECKMATE
elif gs.stalemate:
return STALEMATE
score = scoreMaterial(gs.board)
return score
# Score the board based on material
def scoreMaterial(board):
score = 0
for row in board:
for square in row:
if square[0] == 'w':
score += pieceScore[square[1]]
elif square[0] == 'b':
score -= pieceScore[square[1]]
return score