chessboard.html


001| '''Chessboard -- simulation of board, pieces, and moves.
001| 
001| Data:
001|     ROWS (8), COLS (8), WHITE (0), BLACK (16)
001|     KING (0), QUEEN (1), BISHOP (2), KNIGHT (4), ROOK (6), PAWN (8)
001| 
001|     ChessPieceType          - cross-reference of piece codes/piece values
001|     FileColumnMap           - maps piece indexes to columns
001|     ColumnFileMap           - maps columns to piece indexes
001|     ChessPieceName          - labels for each piece (by piece index)
001|     ChessPieceStartMap      - (row,col) start locations for each piece (by piece index)
001| 
001| Classes:
001|     ChessMove               - Recursive Descent Chess Move Parser
001|     Chessboard              - Chessboard class (w/ move parser)
001|     ChessSet                - Graphic image chessboard and pieces
001| 
001|     ChessboardTransmissionProtocol
001| 
001| Functions:
001|     location_2_square(sq_file, sq_rank, turn)
001| 
001| terminology:
001|     "file"      - chessboard column
001|     "rank"      - chessboard row
001| 
001| The board looks like this:
001| 
001|                      ~~White~~
001| #|  0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |#
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 0| wKR | wKN | wKB | wK  | wQ  | wQB | wQN | wQR |0
001|  |white|black|white|black|white|black|white|black| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 1| wKRP| wKNP| wKBP| wKP | wQP | wQBP| wQNP| wQRP|1
001|  |black|white|black|white|black|white|black|white| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 2|     |     |     |     |     |     |     |     |2
001|  |white|black|white|black|white|black|white|black| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 3|     |     |     |     |     |     |     |     |3
001|  |black|white|black|white|black|white|black|white| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 4|     |     |     |     |     |     |     |     |4
001|  |white|black|white|black|white|black|white|black| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 5|     |     |     |     |     |     |     |     |5
001|  |black|white|black|white|black|white|black|white| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 6| bKRP| bKNP| bKBP| bKP | bQP | bQBP| bQNP| bQRP|6
001|  |white|black|white|black|white|black|white|black| 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| 7| bKR | bKN | bKB | bK  | bQ  | bQB | bQN | bQR |7
001|  |black|white|black|white|black|white|black|white| <- lower right! 
001| -+-----+-----+-----+-----+-----+-----+-----+-----+-
001| #|  0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |#
001|                      ~~Black~~
001| 
001| '''

002| ####################################################################################################
003| from sys import stdout
004| from os import path
005| from PIL import Image, ImageDraw
006| from logger import logger
007| ####################################################################################################
008| Log = logger('chessbrd')
009| 
010| ROWS   = 8
011| COLS   = 8
012| 
013| WHITE  = 0
014| BLACK  = 16
015| 
016| KING   = 0
017| QUEEN  = 1
018| BISHOP = 2
019| KNIGHT = 4
020| ROOK   = 6
021| PAWN   = 8
022| 
023| ChessPieceType = {
024|     'K':KING, 'Q':QUEEN, 'B':BISHOP, 'N':KNIGHT, 'R':ROOK, 'P':PAWN,
025|     KING:'K', QUEEN:'Q', BISHOP:'B', KNIGHT:'N', ROOK:'R', PAWN:'P'
026| }
027| FileColumnMap = [3, 4, 2, 5, 1, 6, 0, 7]
028| ColumnFileMap = [6, 4, 2, 0, 1, 3, 5, 7]
029| 
030| # List of chess piece names...
031| ChessPieceName = [
032|     'wK' , 'wQ' , 'wKB' , 'wQB' , 'wKN' , 'wQN' , 'wKR' , 'wQR' ,
033|     'wKP', 'wQP', 'wKBP', 'wQBP', 'wKNP', 'wQNP', 'wKRP', 'wQRP',
034|     'bK' , 'bQ' , 'bKB' , 'bQB' , 'bKN' , 'bQN' , 'bKR' , 'bQR' ,
035|     'bKP', 'bQP', 'bKBP', 'bQBP', 'bKNP', 'bQNP', 'bKRP', 'bQRP'
036| ]
037| # Initial (row,col) positions of pieces...
038| ChessPieceStartMap = [
039|     (0,4), (0,3), (0,2), (0,5), (0,1), (0,6), (0,0), (0,7),
040|     (1,4), (1,3), (1,2), (1,5), (1,1), (1,6), (1,0), (1,7),
041|     (7,4), (7,3), (7,2), (7,5), (7,1), (7,6), (7,0), (7,7),
042|     (6,4), (6,3), (6,2), (6,5), (6,1), (6,6), (6,0), (6,7)
043| ]
044| 
045| 
046| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
047| class ChessMove:
048|     '''Recursive Descent Chess Move Parser.
048| 
048| Piece BNF:
048|     (K|Q)(P)*
048|     (K|Q)(B|N|R)(P)*
048|     <?>(B|N|R)(P)*
048|     <?><?>(P)
048| 
048| Location BNF:
048|     (K|Q)(#)
048|     (K|Q)(B|N|R)(#)
048|     <?>(B|N|R)(#)
048| 
048| properties:
048|     .move_type          * "" or "move" or "capture"
048|     .src_gender         * -1 or KING, QUEEN
048|     .src_type           * -1 or KING, QUEEN, BISHOP, KNIGHT, ROOK
048|     .src_pawn           *  0 or PAWN
048|     .dst_gender         * -1 or KING, QUEEN
048|     .dst_type           * -1 or KING, QUEEN, BISHOP, KNIGHT, ROOK
048|     .dst_pawn           *  0 or PAWN
048|     .dst_rank           * -1 or 1-8
048| 
048| usage:
048|     mv = ChessMove()
048|     mv.parse('P-K4')
048| 
048| '''

049|     def __init__ (self):
050|         self.reset()
051| 
052|     def parse (self, s='P-K4'):
053|         self.reset()
054|         self.instr = s.strip().upper()
055|         self.clist = list(self.instr)
056|         self.clist.reverse()
057|         self._getch()
058|         self.src_king_or_queen()
059|         return self
060| 
061|     def reset (self):
062|         self.instr = ''
063|         self.clist = None
064|         self.cbuff = None
065|         self.move_type  = ''
066|         self.src_gender = -1
067|         self.src_type   = -1
068|         self.src_pawn   =  0
069|         self.dst_gender = -1
070|         self.dst_type   = -1
071|         self.dst_rank   = -1
072|         self.dst_pawn   =  0
073| 
074|     def __str__ (self):
075|         s1a = {KING:'K', QUEEN:'Q', -1:'?'}[self.src_gender]
076|         s1b = {KING:'', QUEEN:'', BISHOP:'B', KNIGHT:'N', ROOK:'R', -1:'?'}[self.src_type]
077|         s1c = 'P' if self.src_pawn else ''
078|         s2 = 'takes' if self.move_type == 'capture' else 'to'
079|         s3a = {KING:'K', QUEEN:'Q', -1:'?'}[self.dst_gender]
080|         s3b = {KING:'', QUEEN:'', BISHOP:'B', KNIGHT:'N', ROOK:'R', -1:'?'}[self.dst_type]
081|         s3c = 'P' if self.dst_pawn else ''
082|         s3d = '' if self.dst_rank < 0 else str(self.dst_rank)
083|         s = '%s: %s%s%s %s %s%s%s%s'
084|         t = (self.move_type, s1a,s1b,s1c, s2, s3a,s3b,s3c,s3d)
085|         return s % t
086| 
087|     def __repr__ (self):
088|         s = '{type:%s, src.gender:%d, src.type:%d, src.pawn:%d, dst.gender:%d, dst.type:%d, dst.rank:%d, dst.pawn:%d}'
089|         t = (self.move_type,self.src_gender,self.src_type,self.src_pawn,self.dst_gender,self.dst_type,self.dst_rank,self.dst_pawn)
090|         return s % t
091| 
092|     def _getch (self):
093|         if len(self.clist) == 0:
094|             self.cbuff = ''
095|             return
096|         self.cbuff = self.clist.pop()
097|         while (self.cbuff == ' ') and (0 < len(self.clist)):
098|             self.cbuff = self.clist.pop()
099| 
100|     def src_king_or_queen (self):
101|         if not self.cbuff:
102|             return
103|         if self.cbuff == 'K':
104|             self.src_gender = KING
105|             self.src_type = KING
106|             self._getch()
107|         elif self.cbuff == 'Q':
108|             self.src_gender = QUEEN
109|             self.src_type = QUEEN
110|             self._getch()
111|         self.src_piece_type()
112| 
113|     def src_piece_type (self):
114|         if not self.cbuff:
115|             return
116|         if self.cbuff == 'B':
117|             self.src_type = BISHOP
118|             self._getch()
119|         elif self.cbuff == 'N':
120|             self.src_type = KNIGHT
121|             self._getch()
122|         elif self.cbuff == 'R':
123|             self.src_type = ROOK
124|             self._getch()
125|         self.src_piece_pawn()
126| 
127|     def src_piece_pawn (self):
128|         if not self.cbuff:
129|             return
130|         if self.cbuff == 'P':
131|             self.src_pawn = PAWN
132|             self._getch()
133|         # Must be: (K|Q)(B|N|R)(P)*, (K|Q){?}(P)*, {?}(B|N|R)(P)*, {?}{?}(P)
134|         if (self.src_gender < 0) and (self.src_type < 0) and not self.src_pawn:
135|             raise SyntaxError('Parse Error; Incomplete Source Specification: "%s"' % self.instr)
136|         self.move_or_capture()
137| 
138|     def move_or_capture (self):
139|         if not self.cbuff:
140|             return
141|         if self.cbuff == '-':
142|             self.move_type = 'move'
143|             self._getch()
144|             self.dst_king_or_queen()
145|         elif self.cbuff == 'X':
146|             self.move_type = 'capture'
147|             self._getch()
148|             self.cap_king_or_queen()
149|         else:
150|             raise SyntaxError('Parse Error; Unknown Command Type! "%s"' % self.instr)
151| 
152|     def dst_king_or_queen (self):
153|         if not self.cbuff:
154|             return
155|         if self.cbuff == 'K':
156|             self.dst_gender = KING
157|             self.dst_type = KING
158|             self._getch()
159|         elif self.cbuff == 'Q':
160|             self.dst_gender = QUEEN
161|             self.dst_type = QUEEN
162|             self._getch()
163|         self.dst_square_file()
164| 
165|     def dst_square_file (self):
166|         if not self.cbuff:
167|             return
168|         if self.cbuff == 'B':
169|             self.dst_type = BISHOP
170|             self._getch()
171|         elif self.cbuff == 'N':
172|             self.dst_type = KNIGHT
173|             self._getch()
174|         elif self.cbuff == 'R':
175|             self.dst_type = ROOK
176|             self._getch()
177|         self.dst_square_rank()
178| 
179|     def dst_square_rank (self):
180|         if not self.cbuff:
181|             raise SyntaxError('Parse Error; No Target Rank! "%s"' % self.instr)
182|         if self.cbuff.isdigit():
183|             self.dst_rank = int(self.cbuff)
184|             self._getch()
185|         else:
186|             raise SyntaxError('Parse Error! "%s"' % self.instr)
187| 
188|     def cap_king_or_queen (self):
189|         if not self.cbuff:
190|             return
191|         if self.cbuff == 'K':
192|             self.dst_gender = KING
193|             self.dst_type = KING
194|             self._getch()
195|         elif self.cbuff == 'Q':
196|             self.dst_gender = QUEEN
197|             self.dst_type = QUEEN
198|             self._getch()
199|         self.cap_piece_type()
200| 
201|     def cap_piece_type (self):
202|         if not self.cbuff:
203|             return
204|         if self.cbuff == 'B':
205|             self.dst_type = BISHOP
206|             self._getch()
207|         elif self.cbuff == 'N':
208|             self.dst_type = KNIGHT
209|             self._getch()
210|         elif self.cbuff == 'R':
211|             self.dst_type = ROOK
212|             self._getch()
213|         self.cap_piece_pawn()
214| 
215|     def cap_piece_pawn (self):
216|         if not self.cbuff:
217|             return
218|         if self.cbuff == 'P':
219|             self.dst_pawn = PAWN
220|             self._getch()
221|         else:
222|             raise SyntaxError('Parse Error! "%s"' % self.instr)
223|         # Must be: (K|Q)(B|N|R)(P)*, (K|Q){?}(P)*, {?}(B|N|R)(P)*, {?}{?}(P)
224|         if (self.dst_gender < 0) and (self.dst_type < 0) and not self.dst_pawn:
225|             raise SyntaxError('Parse Error; Incomplete Capture Piece Specification: "%s"', self.instr)
226| 
227| 
228| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
229| class ChessboardTransmissionProtocol:
230| 
231|     B1 = ord('A')
232|     B2 = ord('0')
233| 
234|     @property
235|     def pc2row (self): return lambda pc: chr(self.B1+pc[0])
236|     @property
237|     def pc2col (self): return lambda pc: chr(self.B2+pc[1])
238|     @property
239|     def lc2row (self): return lambda lc: (ord(lc[0])-self.B1)
240|     @property
241|     def lc2col (self): return lambda lc: (ord(lc[1])-self.B2)
242| 
243|     def brd2str (self, pcs):
244|         '''Board Data to Protocol String.'''
245|         flds = ['%s%s' % (self.pc2row(p), self.pc2col(p)) for p in pcs]
246|         return ''.join(flds)
247| 
248|     def str2brd (self, txt):
249|         '''Protocol String to Board Data.'''
250|         def chunks ():
251|             for ix in range(0, len(txt), 2):
252|                 yield txt[ix:ix+2]
253| 
254|         return [(self.lc2row(f), self.lc2col(f)) for f in chunks()]
255| 
256| 
257| ##================================================================================================##
258| def location_2_square (sq_file, sq_rank, turn):
259|     c = FileColumnMap[sq_file]
260|     r = (sq_rank - 1) if turn == WHITE else (ROWS - sq_rank)
261|     return (r,c)
262| 
263| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
264| class Chessboard:
265|     '''Chessboard Class.
265| 
265| properties:
265|     .turn           - BLACK or WHITE
265|     .board[][]      - list of board rows
265|     .pieces[]       - list of piece tuples (flag, (row,col))
265|     .moves[]        - list of parsed moves
265|     .parser         - ChessMove parser instance
265|     .ctp            - ChessboardTransmissionProtocol instance
265| 
265| methods:
265|     .reset          - reset board to starting positions
265|     .clear          - clear board of all pieces
265|     .validate       - rebuild pieces list from board
265| 
265|     .parse          - convert "P-K4" to a move
265|     .next_turn      - toggle the turn state (must call after a move)
265|     .move_piece     - manually move piece from one square to another
265| 
265|     .list_board     - list of board
265|     .list_pieces    - list of pieces
265|     .list_captured  - list of captured pieces
265|     .list_moves     - list of parsed moves
265| 
265|     str(obj)        - return simple board text image
265|     repr(obj)       - JSON-like string
265| 
265|     ._get_piece_list(ptype)
265|     ._get_pawn_list(gender, ptype)
265|     ._test_path(start_sq, end_sq)
265|     ._test_move(px, square)
265| 
265| '''

266|     def __init__ (self):
267|         ''' Create a new Chessboard instance. '''
268|         self.reset()
269|         self.parser = ChessMove()
270|         self.ctp = ChessboardTransmissionProtocol()
271| 
272|     def parse (self, mv_text):
273|         ''' Parse an old-fashioned Chess move! '''
274|         self.moves.append(mv_text)
275|         if (mv_text == 'PRINT') or (mv_text == 'PR'):
276|             Log.debug(self)
277|             return
278|         if (mv_text == 'SHOW') or (mv_text == 'SH'):
279|             self.print_board()
280|             return
281|         if mv_text == '.RESET':
282|             self.reset()
283|             self.print_board()
284|             return
285|         # PARSE MOVE...
286|         mv = self.parser.parse(mv_text)
287|         Log.info('> "%s"' % mv.instr)
288|         Log.info('= "%s"' % mv)
289|         # Make Move...
290|         if mv.move_type == 'move':
291|             pcs = []
292|             sqs = []
293|             # Resolve piece...
294|             if mv.src_pawn:
295|                 if (mv.src_gender < 0) or (mv.src_type < 0):
296|                     # Ambiguous Pawn (??P or ?RP)...
297|                     pcs.extend(self._get_pawn_list(mv.src_gender, mv.src_type))
298|                 else:
299|                     # Unambiguous Pawn...
300|                     px = mv.src_type + mv.src_pawn + (mv.src_gender if mv.src_gender != mv.src_type else 0)
301|                     pcs.append(px)
302|             else:
303|                 if mv.src_gender < 0:
304|                     # Ambiguous Piece (?B)...
305|                     pcs.extend(self._get_piece_list(mv.src_type))
306|                 else:
307|                     # Unambiguous Piece...
308|                     px = mv.src_type + mv.src_pawn + (mv.src_gender if mv.src_gender != mv.src_type else 0)
309|                     pcs.append(px)
310|             # Resolve destination...
311|             if mv.dst_gender < 0:
312|                 # King side...
313|                 sq_file = mv.dst_type + KING
314|                 Log.info('loc2sq: "%s", "%s", "%s"' % (sq_file, mv.dst_rank, self.turn))
315|                 sqs.append(location_2_square(sq_file, mv.dst_rank, self.turn))
316|                 # Queen side...
317|                 sq_file = mv.dst_type + QUEEN
318|                 Log.info('loc2sq: "%s", "%s", "%s"' % (sq_file, mv.dst_rank, self.turn))
319|                 sqs.append(location_2_square(sq_file, mv.dst_rank, self.turn))
320|             else:
321|                 # Unambiguous Square...
322|                 sq_file = mv.dst_type + (mv.dst_gender if mv.dst_gender != mv.dst_type else 0)
323|                 Log.info('loc2sq: "%s", "%s", "%s"' % (sq_file, mv.dst_rank, self.turn))
324|                 sqs.append(location_2_square(sq_file, mv.dst_rank, self.turn))
325|             # Test Result...
326|             if len(pcs) == 0:
327|                 raise Exception('No Piece Matches Move: "%s"' % str(mv))
328|             if len(sqs) == 0:
329|                 raise Exception('No Square Matches Move: "%s"' % str(mv))
330|             if len(pcs) == 1:
331|                 Log.info('One Piece Found: %s [%s]' % (ChessPieceName[pcs[0]], self.pieces[pcs[0]]))
332|                 if len(sqs) == 1:
333|                     Log.info('One Square Found: "%s"' % str(sqs[0]))
334|                 else:
335|                     Log.info('Multiple Squares Found: "%s"' % str(mv))
336|                     sqs = [sq for sq in sqs if self._test_move(pcs[0], sq)]
337|                     if len(sqs) != 1:
338|                         raise Exception('Unabled to disambiguate Squares!')
339|             else:
340|                 Log.info('Multiple Pieces Found: "%s"' % str(mv))
341|                 if len(sqs) == 1:
342|                     Log.info('One Square Found: "%s"' % str(sqs[0]))
343|                     pcs = [px for px in pcs if self._test_move(px, sqs[0])]
344|                     if len(pcs) != 1:
345|                         raise Exception('Unabled to disambiguate Pieces!')
346|                 else:
347|                     Log.info('Multiple Squares Found: "%s"' % str(mv))
348|                     tries = []
349|                     for px in pcs:
350|                         for sq in sqs:
351|                             tries.append((px, sq))
352|                     good = []
353|                     for (px,sq) in tries:
354|                         if self._test_move(px, sq):
355|                             good.append((px,sq))
356|                     if len(good) != 1:
357|                         raise Exception('Unabled to disambiguate Move!')
358|                     pcs = [good[0][0]]
359|                     sqs = [good[1][1]]
360|             if not (len(pcs) == 1) and (len(sqs) == 1):
361|                 raise Exception('Could not parse move: "%s"' % str(mv))
362|             # Make Move...
363|             Log.info('MOVE: %s, %s' % (pcs[0], sqs[0]))
364|             Log.info()
365|             self.move_piece(self.pieces[pcs[0]][1], sqs[0])
366|             return
367|         # Make Capture...
368|         if mv.move_type == 'capture':
369|             Log.info('CAPTURE: %s' % str(mv))
370|             return
371|         # Not a move and not a capture...
372|         Log.info('Unknown Input Type: %s' % str(mv))
373| 
374|     def _test_move (self, px, square):
375|         ''' Test move. For now assume inputs are valid and sensible. '''
376|         pr = self.pieces[px][1][0]
377|         pc = self.pieces[px][1][1]
378|         sr = square[0]
379|         sc = square[1]
380|         if self.board[sr][sc][0]:
381|             Log.info('TestMove: Square is occupied.')
382|             return False
383|         rdiff = abs(pr - sr)
384|         cdiff = abs(pc - sc)
385|         if (rdiff + cdiff) == 0:
386|             Log.info('TestMove: Piece already on square.')
387|             return True
388|         Log.info('TestMove: "%s %s" "%s" [%s]' % (ChessPieceName[px], self.pieces[px], square, (rdiff,cdiff)))
389|         if (px==WHITE+KING)or(px==BLACK+KING):
390|             a = (rdiff < 2) and (cdiff < 2)
391|             Log.info('TestKing: '+str(a))
392|             return a
393|         if (px==WHITE+QUEEN)or(px==BLACK+QUEEN):
394|             a = ((rdiff == 0) or (rdiff == cdiff) or (cdiff == 0)) and self._test_path((pr,pc), square)
395|             Log.info('TestQueen: '+str(a))
396|             return a
397|         if (px==WHITE+KING+BISHOP)or(px==WHITE+QUEEN+BISHOP)or(px==BLACK+KING+BISHOP)or(px==BLACK+QUEEN+BISHOP):
398|             a = (rdiff == cdiff) and self._test_path((pr,pc), square)
399|             Log.info('TestBishop: '+str(a))
400|             return a
401|         if (px==WHITE+KING+KNIGHT)or(px==WHITE+QUEEN+KNIGHT)or(px==BLACK+KING+KNIGHT)or(px==BLACK+QUEEN+KNIGHT):
402|             a = ((rdiff == 1) and (cdiff == 2)) or ((rdiff == 2) and (cdiff == 1))
403|             Log.info('TestKnight: '+str(a))
404|             return a
405|         if (px==WHITE+KING+ROOK)or(px==WHITE+QUEEN+ROOK)or(px==BLACK+KING+ROOK)or(px==BLACK+QUEEN+ROOK):
406|             a = ((rdiff == 0) or (cdiff == 0)) and self._test_path((pr,pc), square)
407|             Log.info('TestRook: '+str(a))
408|             return a
409|         if ((WHITE+PAWN <= px)and(px < BLACK))or((BLACK+PAWN <= px)and(px < len(ChessPieceName))):
410|             a = (cdiff == 0) and (rdiff in (1,2))
411|             Log.info('TestPawn: '+str(a))
412|             return a
413|         return False
414| 
415|     def _test_path (self, start_sq, end_sq):
416|         ''' Test if squares *between* <start> and <end> are open. '''
417|         sr = start_sq[0]
418|         sc = start_sq[1]
419|         rdiff = abs(end_sq[0] - sr)
420|         cdiff = abs(end_sq[1] - sc)
421|         if (rdiff != cdiff) and (rdiff * cdiff):
422|             raise RuntimeError('Illegal Path: Not diagonal or straight.')
423|         # Column Path...
424|         if cdiff == 0:
425|             up_or_dn = 1 if sr < end_sq[0] else -1
426|             for x in range(rdiff-1):
427|                 r = sr + ((1+x) * up_or_dn)
428|                 Log.info('ColTest: (%d,%d) = %s' % (r, sc, self.board[r][sc]))
429|                 if self.board[r][sc][0]:
430|                     return False
431|             return True
432|         # Row Path...
433|         if rdiff == 0:
434|             lt_or_rt = 1 if sc < end_sq[1] else -1
435|             for x in range(cdiff-1):
436|                 c = sc + ((1+x) * lt_or_rt)
437|                 Log.info('RowTest: (%d,%d) = %s' % (sr, c, self.board[sr][c]))
438|                 if self.board[sr][c][0]:
439|                     return False
440|             return True
441|         # Diagonal Path...
442|         up_or_dn = 1 if sr < end_sq[0] else -1
443|         lt_or_rt = 1 if sc < end_sq[1] else -1
444|         for x in range(cdiff):
445|             r = sr + ((1+x) * up_or_dn)
446|             c = sc + ((1+x) * lt_or_rt)
447|             Log.info('DiaTest: (%d,%d) = %s' % (r, c, self.board[r][c]))
448|             if self.board[r][c][0]:
449|                 return False
450|         return True
451| 
452|     def _get_piece_list (self, ptype):
453|         ''' Find Piece. '''
454|         pcs = []
455|         if ptype == KING:
456|             Log.info('get King')
457|             pcs = [self.turn + KING]
458|         if ptype == QUEEN:
459|             Log.info('get Queen')
460|             pcs = [self.turn + QUEEN]
461|         if ptype == BISHOP:
462|             Log.info('get Bishops')
463|             pcs = [self.turn + KING+BISHOP, self.turn + QUEEN+BISHOP]
464|         if ptype == KNIGHT:
465|             Log.info('get Knights')
466|             pcs = [self.turn + KING+KNIGHT, self.turn + QUEEN+KNIGHT]
467|         if ptype == ROOK:
468|             Log.info('get Rooks')
469|             pcs = [self.turn + KING+ROOK, self.turn + QUEEN+ROOK]
470|         # Return only active pieces...
471|         pcs = [px for px in pcs if self.pieces[px][0]]
472|         return pcs
473| 
474|     def _get_pawn_list (self, gender, ptype):
475|         ''' Find Pawn. '''
476|         # Start with all the Pawns...
477|         pawns = [self.turn + PAWN + x for x in range(8)]
478|         if 0 < gender:
479|             Log.info('use gender filter')
480|             if gender == KING:
481|                 Log.info('keep King Pawns')
482|                 pawns = [px for px in pawns if not (px & QUEEN)]
483|             if gender == QUEEN:
484|                 Log.info('keep Queen Pawns')
485|                 pawns = [px for px in pawns if (px & QUEEN)]
486|         if 0 < ptype:
487|             Log.info('use ptype filter')
488|             if ptype == BISHOP:
489|                 Log.info('keep Bishops')
490|                 pawns = [px for px in pawns if ((px & 7) == KING+BISHOP) or ((px & 7) == QUEEN+BISHOP)]
491|             if ptype == KNIGHT:
492|                 Log.info('keep Knights')
493|                 pawns = [px for px in pawns if ((px & 7) == KING+KNIGHT) or ((px & 7) == QUEEN+KNIGHT)]
494|             if ptype == ROOK:
495|                 Log.info('keep Rooks')
496|                 pawns = [px for px in pawns if ((px & 7) == KING+ROOK) or ((px & 7) == QUEEN+ROOK)]
497|         # Return only active Pawns...
498|         return [px for px in pawns if self.pieces[px][0]]
499| 
500|     def move_piece (self, src, dst):
501|         '''\
501|         Move a Piece from one square to another.
501|         Assume the move is legal; this just implements the actual move logic.
501|         Also, this will over-write any Piece at the destination!
501|         e.g.
501|                 WKP-K4: (1,3), (3,3)
501|                 BKP-K4: (6,3), (4,3)
501|         '''

502|         # Check input bounds...
503|         if (src[0] < 0) or (ROWS <= src[0]) or (src[1] < 0) or (COLS <= src[1]):
504|             raise Exception('Invalid Source Square: %s' % str(src))
505|         if (dst[0] < 0) or (ROWS <= dst[0]) or (dst[1] < 0) or (COLS <= dst[1]):
506|             raise Exception('Invalid Destination Square: %s' % str(dst))
507|         # Get the source cell...
508|         cell = self.board[src[0]][src[1]]
509|         if not cell[0]:
510|             raise Exception('No Piece on Square: %s' % str(src))
511|         # Get Piece Index and Coordinates...
512|         px = cell[1]
513|         # Check board/piece validity before proceeding...
514|         pc = self.pieces[px]
515|         coord = pc[1]
516|         if (coord[0] != src[0]) or (coord[1] != src[1]):
517|             raise Exception('Insanity: Invalid Start Square: %s' % str(src))
518|         # Make the move...
519|         self.board[src[0]][src[1]] = (0, 0)
520|         self.board[dst[0]][dst[1]] = (pc[0], px)
521|         self.pieces[px] = (pc[0],(dst[0],dst[1]))
522| 
523|     def validate (self):
524|         '''Scan board and create list of piece positions.'''
525|         # Clear the piece list...
526|         self.pieces = [(0,(-1,-1)) for px in range(len(ChessPieceStartMap))]
527| 
528|         for rx,row in enumerate(self.board):
529|             for cx,cell in enumerate(row):
530|                 if 0 < cell[0]:
531|                     px = cell[1]
532|                     self.pieces[px] = (1,(rx,cx))
533| 
534|     def next_turn (self):
535|         self.turn = BLACK if self.turn == WHITE else WHITE
536| 
537|     def reset (self):
538|         '''Set board to starting position.'''
539|         # Initialize the board...
540|         self.board = [[(0,0) for c in range(COLS)] for r in range(ROWS)]
541|         # Initialize the piece list...
542|         self.pieces = [(1, ChessPieceStartMap[ix]) for ix in range(len(ChessPieceStartMap))]
543|         # Place pieces on the board...
544|         for px,p in enumerate(self.pieces):
545|             rx, cx = p[1]
546|             self.board[rx][cx] = (p[0], px)
547|         # Clear the Move List...
548|         self.moves = []
549|         self.turn = WHITE
550| 
551|     def clear (self):
552|         '''Clear board of all pieces.'''
553|         for ix,pc in enumerate(self.pieces):
554|             if not pc[0]:
555|                 continue
556|             r = pc[1][0]
557|             c = pc[1][1]
558|             self.board[r][c] = (0,0)
559|             self.pieces[ix] = (0, (-1,-1))
560|         self.turn = WHITE
561| 
562|     def list_moves (self, fp=stdout):
563|         '''Print the move list.'''
564|         for ix,mv in enumerate(self.moves):
565|             print('%d: "%s"' % (ix, mv), file=fp)
566| 
567|     def list_pieces (self, fp=stdout):
568|         '''Print the piece list.'''
569|         for ix,pc in enumerate(self.pieces):
570|             pn = ChessPieceName[ix]
571|             r = pc[1][0]
572|             c = pc[1][1]
573|             g = 'Active' if pc[0] else ''
574|             print('%d: %s [%d,%d] %s' % (ix, pn, r,c, g), file=fp)
575| 
576|     def list_captured (self, fp=stdout):
577|         '''Print the piece captured list.'''
578|         for ix,pc in enumerate(self.pieces):
579|             if pc[0]:
580|                 continue
581|             pn = ChessPieceName[ix]
582|             print('%d: %s' % (ix, pn), file=fp)
583| 
584|     def list_board (self, fp=stdout):
585|         '''Print the board.'''
586|         fp.write('\n*')
587|         for c in range(COLS):
588|             fp.write('| %d ' % c)
589|         fp.write('|*\n')
590|         fp.write('-')
591|         for c in range(COLS):
592|             fp.write('+----')
593|         fp.write('+-\n')
594| 
595|         for row in self.board:
596|             fp.write('|')
597|             for cell in row:
598|                 if 0 < cell[0]:
599|                     px = cell[1]
600|                     fp.write('|%-4s' % ChessPieceName[px])
601|                 else:
602|                     fp.write('| ')
603|             fp.write('||\n')
604|             fp.write('-')
605|             for c in range(COLS):
606|                 fp.write('+----')
607|             fp.write('+-\n')
608| 
609|         fp.write('*')
610|         for c in range(COLS):
611|             fp.write('| %d ' % c)
612|         fp.write('|*\n\n')
613| 
614|     def __str__ (self):
615|         s = ''
616|         for c in range(COLS):
617|             s += ('+---')
618|         s += ('+\n')
619|         for row in self.board:
620|             for cell in row:
621|                 if 0 < cell[0]:
622|                     px = cell[1]
623|                     color = 'W' if px < BLACK else 'B'
624|                     pawn = 'p' if px & PAWN else ' '
625|                     s += ('|%c%d%c' % (color, px & 7, pawn))
626|                 else:
627|                     s += ('| ')
628|             s += ('|\n')
629|             for c in range(COLS):
630|                 s += ('+---')
631|             s += ('+\n')
632|         return s
633| 
634|     def __repr__ (self):
635|         s = '{Chessboard:{moves:%d, ...}}'
636|         t = (len(self.moves),)
637|         return s % t
638| 
639| 
640| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
641| class ChessSet:
642|     '''Graphic image chessboard and pieces.'''
643| 
644|     ImgsPath = r'C:\CJS\www\root\img\chess'
645|     ImgNames = ['wk','wq','wb','wn','wr','wp','bk','bq','bb','bn','br','bp', 'rq']
646|     ImgIndex = [0,1,2,2,3,3,4,4,5,5,5,5,5,5,5,5,6,7,8,8,9,9,10,10,11,11,11,11,11,11,11,11,12]
647| 
648|     def __init__ (self):
649|         # Load black & white Squares
650|         self.sq_w = Image.open(path.join(ChessSet.ImgsPath, 'w.gif'))
651|         self.sq_b = Image.open(path.join(ChessSet.ImgsPath, 'b.gif'))
652| 
653|         # Load piece imagess...
654|         self.images = []
655|         for pname in ChessSet.ImgNames:
656|             w = Image.open(path.join(ChessSet.ImgsPath, '%sw.gif' % pname))
657|             b = Image.open(path.join(ChessSet.ImgsPath, '%sb.gif' % pname))
658|             t = (w, b)
659|             self.images.append(t)
660| 
661|         # Initialize pieces...
662|         self.pieces = []
663|         for ix in range(len(ChessPieceStartMap)):
664|             nm = ChessPieceName[ix]
665|             gx = self.ImgIndex[ix]
666|             rc = ChessPieceStartMap[ix]
667|             self.pieces.append([nm, self.images[gx], rc, True])
668| 
669|     def save_image (self, fname='board.png', fpath=None):
670|         sqx = self.sq_w.size[0]
671|         sqy = self.sq_w.size[1]
672|         b1w,b1h = 5,5
673|         b2w,b2h = 3,3
674|         dims=((ROWS*sqx)+(2*(b1w+b2w)), (COLS*sqy)+(2*(b1h+b2h)))
675| 
676|         # New image...
677|         im = Image.new('RGB', dims, (255,255,255))
678|         draw = ImageDraw.Draw(im)
679|         # Draw border 1...
680|         for ix in range(0, b1w):
681|             c = 191 - (ix*32)
682|             draw.rectangle((ix,ix)+(dims[0]-ix,dims[1]-ix), outline=(c,c,c))
683|         # Draw border 2...
684|         for ix in range(b1w, b1w+b2w):
685|             draw.rectangle((ix,ix)+(dims[0]-ix,dims[1]-ix), outline=(0,0,0))
686| 
687|         # Draw squares...
688|         px,py = b1w+b2w, b1h+b2h
689|         for row in range(8):
690|             for col in range(8):
691|                 if (row % 2) == 0:
692|                     sq = self.sq_w if (col % 2) == 0 else self.sq_b
693|                 else:
694|                     sq = self.sq_b if (col % 2) == 0 else self.sq_w
695|                 im.paste(sq, (px,py))
696|                 px = px + sqx
697|             py = py + sqy
698|             px = b1w + b2w
699| 
700|         # Draw pieces...
701|         ulcx,ulcy = b1w+b2w, b1h+b2h
702|         for pc in self.pieces:
703|             if not pc[3]:
704|                 continue
705|             row = 7 - pc[2][0]
706|             col = pc[2][1]
707|             if (row % 2) == 0:
708|                 sx = 0 if (col % 2)==0 else 1
709|             else:
710|                 sx = 1 if (col % 2)==0 else 0
711|             px = ulcx + (col*sqx)
712|             py = ulcy + (row*sqy)
713|             im.paste(pc[1][sx], (px,py))
714| 
715|         # Output image...
716|         fn = path.join(fpath,fname) if fpath else fname
717|         im.save(fn, 'PNG')
718| 
719| 
720| 
721| ####################################################################################################
722| '''eof'''
723|