forked from ChieBKAI/minimax-chess-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChessMain.py
237 lines (212 loc) · 9.08 KB
/
ChessMain.py
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import math
import pygame as p
import ChessEngine
import ChienKoNgu
WIDTH = HEIGHT = 512
MOVE_LOG_PANEL_WIDTH = 290
MOVE_LOG_PANEL_HEIGHT = HEIGHT
DIMENSION = 8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 240
IMAGES = {}
def load_images():
pieces = ["wp", "wR", "wN", "wB", "wQ", "wK", "bp", "bR", "bN", "bB", "bQ", "bK"]
for piece in pieces:
IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQ_SIZE, SQ_SIZE))
def main():
p.init()
screen = p.display.set_mode((WIDTH + MOVE_LOG_PANEL_WIDTH, HEIGHT))
clock = p.time.Clock()
screen.fill(p.Color("white"))
gs = ChessEngine.GameState()
validMoves = gs.getValidMoves()
moveMade = False
animate = False
gameOver = False
playerOne = True
playerTwo = False
load_images()
sqSelected = ()
playerClicks = []
running = True
while running:
humanTurn = (gs.whiteToMove and playerOne) or (not gs.whiteToMove and playerTwo)
for e in p.event.get():
if e.type == p.QUIT:
running = False
elif e.type == p.MOUSEBUTTONDOWN:
if not gameOver and humanTurn:
location = p.mouse.get_pos()
col = location[0]//SQ_SIZE
row = location[1]//SQ_SIZE
if sqSelected == (row, col) or col >= 8:
sqSelected = ()
playerClicks = []
else:
sqSelected = (row, col)
playerClicks.append(sqSelected)
if len(playerClicks) == 2:
move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
if move in validMoves:
move = validMoves[validMoves.index(move)]
gs.makeMove(move)
moveMade = True
animate = True
sqSelected = ()
playerClicks = []
print(move.getChessNotation())
else:
playerClicks = [sqSelected]
elif e.type == p.KEYDOWN:
if e.key == p.K_z:
gs.undoMove()
moveMade = True
animate = False
gameOver = False
playerOne = True
playerTwo = True
elif e.key == p.K_r:
gs = ChessEngine.GameState()
validMoves = gs.getValidMoves()
moveMade = False
animate = False
gameOver = False
playerOne = True
playerTwo = True
sqSelected = ()
playerClicks = []
elif e.key == p.K_q:
playerOne = False
playerTwo = True
elif e.key == p.K_e:
playerOne = True
playerTwo = False
if moveMade:
if animate:
animateMove(gs.moveLog[-1], screen, gs.board, clock)
validMoves = gs.getValidMoves()
moveMade = False
animate = False
''' AI move finder '''
if not gameOver and not humanTurn:
AIMove = ChienKoNgu.findBestMoveMinimax(gs, validMoves)
#AIMove = ChienKoNgu.findRandomMove(validMoves)
if AIMove is None: #when begin the game
AIMove = ChienKoNgu.findRandomMove(validMoves)
gs.makeMove(AIMove)
moveMade = True
animate = True
print(AIMove.getChessNotation())
drawGameState(screen, gs, validMoves, sqSelected)
if gs.checkMate or gs.staleMate:
gameOver = True
if gs.staleMate:
gameOver = True
drawEndGameText(screen, "DRAW")
else:
if gs.whiteToMove:
drawEndGameText(screen, "BLACK WIN")
else:
drawEndGameText(screen, "WHITE WIN")
clock.tick(MAX_FPS)
p.display.flip()
def highlightMove(screen, gs, validMoves, sqSelected):
sq = p.Surface((SQ_SIZE, SQ_SIZE))
sq.set_alpha(100)
if sqSelected != ():
r, c = sqSelected
if gs.board[r][c][0] == ('w' if gs.whiteToMove else 'b'): #sqSelected is a piece that can be moved
#highlight selected square
sq.fill(p.Color("blue"))
screen.blit(sq, (c * SQ_SIZE, r * SQ_SIZE))
#highlight validmoves
sq.fill(p.Color("cyan"))
for move in validMoves:
if move.startRow == r and move.startCol == c:
screen.blit(sq, (move.endCol * SQ_SIZE, move.endRow * SQ_SIZE))
if gs.inCheck:
if gs.whiteToMove:
sq.fill(p.Color("red"))
screen.blit(sq, (gs.whiteKingLocate[1] * SQ_SIZE, gs.whiteKingLocate[0] * SQ_SIZE))
else:
sq.fill(p.Color("red"))
screen.blit(sq, (gs.blackKingLocate[1] * SQ_SIZE, gs.blackKingLocate[0] * SQ_SIZE))
if len(gs.moveLog) != 0:
sq.fill(p.Color("yellow"))
screen.blit(sq, (gs.moveLog[-1].startCol * SQ_SIZE, gs.moveLog[-1].startRow * SQ_SIZE))
screen.blit(sq, (gs.moveLog[-1].endCol * SQ_SIZE, gs.moveLog[-1].endRow * SQ_SIZE))
def animateMove(move, screen, board, clock):
colors = [p.Color("white"), p.Color("grey")]
dR = move.endRow - move.startRow
dC = move.endCol - move.startCol
sqDistance = math.sqrt(abs(move.endRow - move.startRow)*abs(move.endRow - move.startRow) +
abs(move.endCol - move.startCol)*abs(move.endCol - move.startCol))
sqDistance = int(sqDistance)
framesPerSquare = 12 // sqDistance
frameCount = (abs(dR) + abs(dC)) * framesPerSquare
for frame in range(frameCount + 1):
r, c = (move.startRow + dR*frame/frameCount, move.startCol + dC*frame/frameCount)
drawBoard(screen)
drawPieces(screen, board)
color = colors[(move.endRow + move.endCol) % 2]
endSquare = p.Rect(move.endCol*SQ_SIZE, move.endRow*SQ_SIZE, SQ_SIZE, SQ_SIZE)
p.draw.rect(screen, color, endSquare)
if move.pieceCaptured != "--":
if move.isEnpassantMove:
enPassantRow = (move.endRow + 1) if move.pieceCaptured[0] == 'b' else (move.endRow - 1)
endSquare = p.Rect(move.endCol*SQ_SIZE, enPassantRow*SQ_SIZE, SQ_SIZE, SQ_SIZE)
screen.blit(IMAGES[move.pieceCaptured], endSquare)
if move.pieceMoved != "--":
screen.blit(IMAGES[move.pieceMoved], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))
p.display.flip()
clock.tick(144)
def drawGameState(screen, gs, validMoves, sqSelected):
drawBoard(screen)
highlightMove(screen, gs, validMoves, sqSelected)
drawPieces(screen, gs.board)
drawMoveLog(screen, gs)
def drawBoard(screen):
colors = [p.Color("white"), p.Color("grey")]
for r in range(DIMENSION):
for c in range(DIMENSION):
color = colors[((r + c) % 2)]
p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))
def drawPieces(screen, board):
for row in range(DIMENSION):
for col in range(DIMENSION):
piece = board[row][col]
if piece != "--":
screen.blit(IMAGES[piece], p.Rect(col*SQ_SIZE, row*SQ_SIZE, SQ_SIZE, SQ_SIZE))
def drawEndGameText(screen, text):
font = p.font.SysFont("Verdana", 32, True, False)
textObject = font.render(text, False, p.Color("black"))
textLocation = p.Rect(0, 0, WIDTH, HEIGHT).move(WIDTH/2 - textObject.get_width()/2, HEIGHT/2 - textObject.get_height()/2)
screen.blit(textObject, textLocation)
textObject = font.render(text, False, p.Color("red"))
screen.blit(textObject, textLocation.move(2, 2))
def drawMoveLog(screen, gs):
moveLogRect = p.Rect(WIDTH, 0, MOVE_LOG_PANEL_WIDTH, MOVE_LOG_PANEL_HEIGHT)
p.draw.rect(screen, p.Color("black"), moveLogRect)
moveLog = gs.moveLog
moveTexts = []
for i in range(0, len(moveLog), 2):
moveString = str(i//2 + 1) + ". " + str(moveLog[i]) + " "
if i+1 < len(moveLog):
moveString += str(moveLog[i+1]) + " "
moveTexts.append(moveString)
padding = 5
movesPerRow = 3
lineSpacing = 2
textY = padding
for i in range(0, len(moveTexts), movesPerRow):
text = ""
font = p.font.SysFont("Verdana", 13, True, False)
for j in range(movesPerRow):
if i+j < len(moveTexts):
text += moveTexts[i+j]
textObject = font.render(text, False, p.Color("white"))
textLocation = moveLogRect.move(padding, textY)
screen.blit(textObject, textLocation)
textY += textObject.get_height() + lineSpacing
if __name__ == "__main__":
main()