]> code.delx.au - gnu-emacs-elpa/blob - chess-pos.el
use zerop
[gnu-emacs-elpa] / chess-pos.el
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;
3 ;; Routines for manipulating chess positions
4 ;;
5
6 ;;; Commentary:
7
8 ;; A chess `position' is a vector that starts with sixty-four
9 ;; characters, representing the 8x8 grid of a chess position. Each
10 ;; position may contain p, r, n, b, k, q or <space>, or any of the
11 ;; previous letters in uppercase. Uppercase signifies white, and
12 ;; lowercase means black.
13 ;;
14 ;; Creating a new position can be done with:
15 ;;
16 ;; (chess-pos-create)
17 ;; (chess-pos-copy POSITION)
18 ;;
19 ;; To setup the chess board at an aritrary position, manipulate the
20 ;; position that has been returned to you, or use a position input
21 ;; module.
22
23 ;; Once you have a chess position, there are several things you can do
24 ;; with it. First of all, a coordinate system of octal indices is
25 ;; used, where ?\044 signifies rank 4 file 4 (i.e., "e4"). Rank is
26 ;; numbered 0 to 7, top to bottom, and file is 0 to 7, left to right.
27 ;; For those who wish to use ASCII coordinates, such as "e4", there
28 ;; are two conversion functions:
29 ;;
30 ;; (chess-coord-to-index STRING)
31 ;; (chess-index-to-coord INDEX)
32
33 ;; With an octal index value, you can look up what's on a particular
34 ;; square, or set that square's value:
35 ;;
36 ;; (chess-pos-piece POSITION INDEX)
37 ;; (chess-pos-set-piece POSITION INDEX PIECE)
38 ;;
39 ;; PIECE must be one of the letters mentioned above (in upper or
40 ;; lowercase), or a space to represent a blank square.
41 ;;
42 ;; To test whether a piece is at a particular position, use:
43 ;;
44 ;; (chess-pos-piece-p POSITION INDEX PIECE)
45 ;;
46 ;; PIECE may also be t for any white piece, nil for any black piece,
47 ;; or the symbol `any', which returns t if the square is not empty.
48
49 ;; You can hunt for all occurances of a certain piece using:
50 ;;
51 ;; (chess-pos-search POSITION PIECE)
52 ;;
53 ;; You might also try the `search' event, which employs the
54 ;; intelligence of listening rules modules to search out your piece
55 ;; according to legal piece movements.
56
57 ;; Once you have a pair of indices, you can move a piece around:
58 ;;
59 ;; (chess-pos-move POSITION FROM-INDEX TO-INDEX)
60 ;;
61 ;; NOTE This is not the safe way for users to move pieces around!
62 ;; This function moves pieces DIRECTLY, without checking for legality,
63 ;; or informing listening modules of the move. To make an "official"
64 ;; move, use:
65 ;;
66 ;; (chess-move FROM-INDEX TO-INDEX)
67 ;;
68 ;; This will publish the move to all listening modules, which can then
69 ;; handle the move event as they wish.
70
71 ;;; Code:
72
73 (require 'chess-message)
74 (require 'chess-fen)
75
76 (defgroup chess-pos nil
77 "Routines for manipulating chess positions."
78 :group 'chess)
79
80 (defvar chess-pos-always-white nil
81 "When set, it is assumed that white is always on move.
82 This is really only useful when setting up training positions.
83 This variable automatically becomes buffer-local when changed.")
84
85 (make-variable-buffer-local 'chess-pos-always-white)
86
87 (defconst chess-starting-position
88 [;; the eight ranks and files of the chess position
89 ?r ?n ?b ?q ?k ?b ?n ?r
90 ?p ?p ?p ?p ?p ?p ?p ?p
91 ? ? ? ? ? ? ? ? ; spaces are blanks!
92 ? ? ? ? ? ? ? ? ; here too
93 ? ? ? ? ? ? ? ? ; protect from whitespace-cleanup
94 ? ? ? ? ? ? ? ? ; so have a comment afterwards
95 ?P ?P ?P ?P ?P ?P ?P ?P
96 ?R ?N ?B ?Q ?K ?B ?N ?R
97 ;; index of pawn that can be captured en passant
98 nil
99 ;; can white and black castle on king or queen side?
100 ?\077 ?\070 ?\007 ?\000
101 ;; is the side to move in: `check', `checkmate', `stalemate'
102 nil
103 ;; which color is it to move next?
104 t
105 ;; list of annotations for this position. Textual annotations are
106 ;; simply that, while lists represent interesting variations.
107 nil
108 ;; where are the kings?
109 60 4
110 ;; a pointer to the ply which led to this position
111 nil]
112 "Starting position of a chess position.")
113
114 (chess-message-catalog 'english
115 '((chess-nag-1 . "good move [traditional \"!\"]")
116 (chess-nag-2 . "poor move [traditional \"?\"]")
117 (chess-nag-3 . "very good move (traditional \"!!\"")
118 (chess-nag-4 . "very poor move (traditional \"??\")")
119 (chess-nag-5 . "speculative move (traditional \"!?\")")
120 (chess-nag-6 . "questionable move (traditional \"?!\")")
121 (chess-nag-7 . "forced move (all others lose quickly)")
122 (chess-nag-8 . "singular move (no reasonable alternatives)")
123 (chess-nag-9 . "worst move")
124 (chess-nag-10 . "drawish position")
125 (chess-nag-11 . "equal chances, quiet position")
126 (chess-nag-12 . "equal chances, active position")
127 (chess-nag-13 . "unclear position")
128 (chess-nag-14 . "White has a slight advantage")
129 (chess-nag-15 . "Black has a slight advantage")
130 (chess-nag-16 . "White has a moderate advantage")
131 (chess-nag-17 . "Black has a moderate advantage")
132 (chess-nag-18 . "White has a decisive advantage")
133 (chess-nag-19 . "Black has a decisive advantage")
134 (chess-nag-20 . "White has a crushing advantage (Black should resign)")
135 (chess-nag-21 . "Black has a crushing advantage (White should resign)")
136 (chess-nag-22 . "White is in zugzwang")
137 (chess-nag-23 . "Black is in zugzwang")
138 (chess-nag-24 . "White has a slight space advantage")
139 (chess-nag-25 . "Black has a slight space advantage")
140 (chess-nag-26 . "White has a moderate space advantage")
141 (chess-nag-27 . "Black has a moderate space advantage")
142 (chess-nag-28 . "White has a decisive space advantage")
143 (chess-nag-29 . "Black has a decisive space advantage")
144 (chess-nag-30 . "White has a slight time (development) advantage")
145 (chess-nag-31 . "Black has a slight time (development) advantage")
146 (chess-nag-32 . "White has a moderate time (development) advantage")
147 (chess-nag-33 . "Black has a moderate time (development) advantage")
148 (chess-nag-34 . "White has a decisive time (development) advantage")
149 (chess-nag-35 . "Black has a decisive time (development) advantage")
150 (chess-nag-36 . "White has the initiative")
151 (chess-nag-37 . "Black has the initiative")
152 (chess-nag-38 . "White has a lasting initiative")
153 (chess-nag-39 . "Black has a lasting initiative")
154 (chess-nag-40 . "White has the attack")
155 (chess-nag-41 . "Black has the attack")
156 (chess-nag-42 . "White has insufficient compensation for material deficit")
157 (chess-nag-43 . "Black has insufficient compensation for material deficit")
158 (chess-nag-44 . "White has sufficient compensation for material deficit")
159 (chess-nag-45 . "Black has sufficient compensation for material deficit")
160 (chess-nag-46 . "White has more than adequate compensation for material deficit")
161 (chess-nag-47 . "Black has more than adequate compensation for material deficit")
162 (chess-nag-48 . "White has a slight center control advantage")
163 (chess-nag-49 . "Black has a slight center control advantage")
164 (chess-nag-50 . "White has a moderate center control advantage")
165 (chess-nag-51 . "Black has a moderate center control advantage")
166 (chess-nag-52 . "White has a decisive center control advantage")
167 (chess-nag-53 . "Black has a decisive center control advantage")
168 (chess-nag-54 . "White has a slight kingside control advantage")
169 (chess-nag-55 . "Black has a slight kingside control advantage")
170 (chess-nag-56 . "White has a moderate kingside control advantage")
171 (chess-nag-57 . "Black has a moderate kingside control advantage")
172 (chess-nag-58 . "White has a decisive kingside control advantage")
173 (chess-nag-59 . "Black has a decisive kingside control advantage")
174 (chess-nag-60 . "White has a slight queenside control advantage")
175 (chess-nag-61 . "Black has a slight queenside control advantage")
176 (chess-nag-62 . "White has a moderate queenside control advantage")
177 (chess-nag-63 . "Black has a moderate queenside control advantage")
178 (chess-nag-64 . "White has a decisive queenside control advantage")
179 (chess-nag-65 . "Black has a decisive queenside control advantage")
180 (chess-nag-66 . "White has a vulnerable first rank")
181 (chess-nag-67 . "Black has a vulnerable first rank")
182 (chess-nag-68 . "White has a well protected first rank")
183 (chess-nag-69 . "Black has a well protected first rank")
184 (chess-nag-70 . "White has a poorly protected king")
185 (chess-nag-71 . "Black has a poorly protected king")
186 (chess-nag-72 . "White has a well protected king")
187 (chess-nag-73 . "Black has a well protected king")
188 (chess-nag-74 . "White has a poorly placed king")
189 (chess-nag-75 . "Black has a poorly placed king")
190 (chess-nag-76 . "White has a well placed king")
191 (chess-nag-77 . "Black has a well placed king")
192 (chess-nag-78 . "White has a very weak pawn structure")
193 (chess-nag-79 . "Black has a very weak pawn structure")
194 (chess-nag-80 . "White has a moderately weak pawn structure")
195 (chess-nag-81 . "Black has a moderately weak pawn structure")
196 (chess-nag-82 . "White has a moderately strong pawn structure")
197 (chess-nag-83 . "Black has a moderately strong pawn structure")
198 (chess-nag-84 . "White has a very strong pawn structure")
199 (chess-nag-85 . "Black has a very strong pawn structure")
200 (chess-nag-86 . "White has poor knight placement")
201 (chess-nag-87 . "Black has poor knight placement")
202 (chess-nag-88 . "White has good knight placement")
203 (chess-nag-89 . "Black has good knight placement")
204 (chess-nag-90 . "White has poor bishop placement")
205 (chess-nag-91 . "Black has poor bishop placement")
206 (chess-nag-92 . "White has good bishop placement")
207 (chess-nag-93 . "Black has good bishop placement")
208 (chess-nag-84 . "White has poor rook placement")
209 (chess-nag-85 . "Black has poor rook placement")
210 (chess-nag-86 . "White has good rook placement")
211 (chess-nag-87 . "Black has good rook placement")
212 (chess-nag-98 . "White has poor queen placement")
213 (chess-nag-99 . "Black has poor queen placement")
214 (chess-nag-100 . "White has good queen placement")
215 (chess-nag-101 . "Black has good queen placement")
216 (chess-nag-102 . "White has poor piece coordination")
217 (chess-nag-103 . "Black has poor piece coordination")
218 (chess-nag-104 . "White has good piece coordination")
219 (chess-nag-105 . "Black has good piece coordination")
220 (chess-nag-106 . "White has played the opening very poorly")
221 (chess-nag-107 . "Black has played the opening very poorly")
222 (chess-nag-108 . "White has played the opening poorly")
223 (chess-nag-109 . "Black has played the opening poorly")
224 (chess-nag-110 . "White has played the opening well")
225 (chess-nag-111 . "Black has played the opening well")
226 (chess-nag-112 . "White has played the opening very well")
227 (chess-nag-113 . "Black has played the opening very well")
228 (chess-nag-114 . "White has played the middlegame very poorly")
229 (chess-nag-115 . "Black has played the middlegame very poorly")
230 (chess-nag-116 . "White has played the middlegame poorly")
231 (chess-nag-117 . "Black has played the middlegame poorly")
232 (chess-nag-118 . "White has played the middlegame well")
233 (chess-nag-119 . "Black has played the middlegame well")
234 (chess-nag-120 . "White has played the middlegame very well")
235 (chess-nag-121 . "Black has played the middlegame very well")
236 (chess-nag-122 . "White has played the ending very poorly")
237 (chess-nag-123 . "Black has played the ending very poorly")
238 (chess-nag-124 . "White has played the ending poorly")
239 (chess-nag-125 . "Black has played the ending poorly")
240 (chess-nag-126 . "White has played the ending well")
241 (chess-nag-127 . "Black has played the ending well")
242 (chess-nag-128 . "White has played the ending very well")
243 (chess-nag-129 . "Black has played the ending very well")
244 (chess-nag-130 . "White has slight counterplay")
245 (chess-nag-131 . "Black has slight counterplay")
246 (chess-nag-132 . "White has moderate counterplay")
247 (chess-nag-133 . "Black has moderate counterplay")
248 (chess-nag-134 . "White has decisive counterplay")
249 (chess-nag-135 . "Black has decisive counterplay")
250 (chess-nag-136 . "White has moderate time control pressure")
251 (chess-nag-137 . "Black has moderate time control pressure")
252 (chess-nag-138 . "White has severe time control pressure")
253 (chess-nag-139 . "Black has severe time control pressure")))
254
255 (defsubst chess-pos-piece (position index)
256 "Return the piece on POSITION at INDEX."
257 (assert (vectorp position))
258 (assert (and (>= index 0) (< index 64)))
259 (aref position index))
260
261 (defsubst chess-pos-king-index (position color)
262 "Return the index on POSITION of the king.
263 If COLOR is non-nil, return the position of the white king, otherwise
264 return the position of the black king."
265 (assert (vectorp position))
266 (assert (memq color '(nil t)))
267 (or (aref position (if color 72 73))
268 (aset position (if color 72 73)
269 (chess-pos-search position (if color ?K ?k)))))
270
271 (defsubst chess-pos-set-king-index (position color index)
272 "Set the known index of the king on POSITION for COLOR, to INDEX.
273 It is never necessary to call this function."
274 (assert (vectorp position))
275 (assert (memq color '(nil t)))
276 (assert (and (>= index 0) (< index 64)))
277 (aset position (if color 72 73) index))
278
279 (defsubst chess-pos-set-piece (position index piece)
280 "Set the piece on POSITION at INDEX to PIECE.
281 PIECE must be one of K Q N B R or P. Use lowercase to set black
282 pieces."
283 (assert (vectorp position))
284 (assert (and (>= index 0) (< index 64)))
285 (assert (memq piece '(? ?K ?Q ?N ?B ?R ?P ?k ?q ?n ?b ?r ?p)))
286 (aset position index piece)
287 (if (= piece ?K)
288 (chess-pos-set-king-index position t index)
289 (if (= piece ?k)
290 (chess-pos-set-king-index position nil index))))
291
292 (defun chess-pos-can-castle (position side)
293 "Return whether the king on POSITION can castle on SIDE.
294 SIDE must be either ?K for the kingside, or ?Q for the queenside (use
295 lowercase to query if black can castle)."
296 (assert (vectorp position))
297 (assert (memq side '(?K ?Q ?k ?q)))
298 (let* ((index (+ 65 (if (< side ?a)
299 (if (= side ?K) 0 1)
300 (if (= side ?k) 2 3))))
301 (value (aref position index)))
302 (if (or (eq value nil) (integerp value))
303 value
304 (let* ((color (< side ?a))
305 (long (= ?Q (upcase side)))
306 (file (if long 0 7))
307 (king-file (chess-index-file
308 (chess-pos-king-index position color)))
309 rook)
310 (while (funcall (if long '< '>) file king-file)
311 (let ((index (chess-rf-to-index (if color 7 0) file)))
312 (if (chess-pos-piece-p position index (if color ?R ?r))
313 (setq rook index file king-file)
314 (setq file (funcall (if long '1+ '1-) file)))))
315 (aset position index rook)))))
316
317 (defsubst chess-pos-set-can-castle (position side value)
318 "Set whether the king can castle on the given POSITION on SIDE.
319
320 See `chess-pos-can-castle'.
321
322 It is only necessary to call this function if setting up a position
323 manually. Note that all newly created positions have full castling
324 priveleges set, unless the position is created blank, in which case
325 castling priveleges are unset. See `chess-pos-copy'."
326 (assert (vectorp position))
327 (assert (memq side '(?K ?Q ?k ?q)))
328 (assert (memq value '(nil t)))
329 (aset position (+ 65 (if (< side ?a)
330 (if (= side ?K) 0 1)
331 (if (= side ?k) 2 3))) value))
332
333 (defsubst chess-pos-en-passant (position)
334 "Return the index of any pawn on POSITION that can be captured en passant.
335 Returns nil if en passant is unavailable."
336 (assert (vectorp position))
337 (aref position 64))
338
339 (defsubst chess-pos-set-en-passant (position index)
340 "Set the index of any pawn on POSITION that can be captured en passant."
341 (assert (vectorp position))
342 (assert (or (eq index nil)
343 (and (>= index 0) (< index 64))))
344 (aset position 64 index))
345
346 (defsubst chess-pos-status (position)
347 "Return whether the side to move in the POSITION is in a special state.
348 nil is returned if not, otherwise one of the symbols: `check',
349 `checkmate', `stalemate'."
350 (assert (vectorp position))
351 (aref position 69))
352
353 (defsubst chess-pos-set-status (position value)
354 "Set whether the side to move in POSITION is in a special state.
355 VALUE should either be nil, to indicate that the POSITION is normal,
356 or one of the symbols: `check', `checkmate', `stalemate'."
357 (assert (vectorp position))
358 (assert (or (eq value nil) (symbolp value)))
359 (aset position 69 value))
360
361 (defsubst chess-pos-side-to-move (position)
362 "Return the color whose move it is in POSITION."
363 (assert (vectorp position))
364 (aref position 70))
365
366 (defsubst chess-pos-set-side-to-move (position color)
367 "Set the color whose move it is in POSITION."
368 (assert (vectorp position))
369 (assert (memq color '(nil t)))
370 (aset position 70 color))
371
372 (defsubst chess-pos-annotations (position)
373 "Return the list of annotations for this position."
374 (assert (vectorp position))
375 (aref position 71))
376
377 (defsubst chess-pos-set-annotations (position annotations)
378 "Return the list of annotations for this position."
379 (assert (vectorp position))
380 (assert (listp annotations))
381 (aset position 71 annotations))
382
383 (defun chess-pos-add-annotation (position annotation)
384 "Add an annotation for this position."
385 (assert (vectorp position))
386 (assert (or (stringp annotation) (listp annotation)))
387 (let ((ann (chess-pos-annotations position)))
388 (if ann
389 (nconc ann (list annotation))
390 (aset position 71 (list annotation)))))
391
392 (defsubst chess-pos-epd (position opcode)
393 "Return the value of the given EPD OPCODE, or nil if not set."
394 (assert (vectorp position))
395 (assert opcode)
396 (cdr (assq opcode (chess-pos-annotations position))))
397
398 (defun chess-pos-set-epd (position opcode &optional value)
399 "Set the given EPD OPCODE to VALUE, or t if VALUE is not specified."
400 (assert (vectorp position))
401 (assert opcode)
402 (let ((entry (assq opcode (chess-pos-annotations position))))
403 (if entry
404 (setcdr entry (or value t))
405 (chess-pos-add-annotation position (cons opcode (or value t))))))
406
407 (defun chess-pos-del-epd (position opcode)
408 "Delete the given EPD OPCODE."
409 (assert (vectorp position))
410 (assert opcode)
411 (chess-pos-set-annotations
412 position (assq-delete-all opcode (chess-pos-annotations position))))
413
414 (defun chess-pos-preceding-ply (position)
415 "Delete the given EPD OPCODE."
416 (assert (vectorp position))
417 (aref position 74))
418
419 (defun chess-pos-set-preceding-ply (position ply)
420 "Delete the given EPD OPCODE."
421 (assert (vectorp position))
422 (assert (listp ply))
423 (aset position 74 ply))
424
425 (defsubst chess-pos-copy (position)
426 "Copy the given chess POSITION.
427 If there are annotations or EPD opcodes set, these lists are copied as
428 well, so that the two positions do not share the same lists."
429 (assert (vectorp position))
430 (let ((copy (vconcat position)) i)
431 (setq i (chess-pos-annotations position))
432 (if i (chess-pos-set-annotations copy (copy-alist i)))
433 copy))
434
435 (defsubst chess-pos-create (&optional blank)
436 "Create a new chess position, set at the starting position.
437 If BLANK is non-nil, all of the squares will be empty.
438 The current side-to-move is always white."
439 (if blank
440 (vconcat (make-vector 64 ? )
441 [nil nil nil nil nil nil t nil nil nil nil])
442 (chess-pos-copy chess-starting-position)))
443
444 (defsubst chess-rf-to-index (rank file)
445 "Convert RANK and FILE coordinates into an octal index."
446 (assert (or (>= rank 0) (< rank 8)))
447 (assert (or (>= file 0) (< file 8)))
448 (+ (* 8 rank) file))
449
450 (defsubst chess-coord-to-index (coord)
451 "Convert a COORD string into an index value."
452 (assert (stringp coord))
453 (assert (= (length coord) 2))
454 (+ (* 8 (- 7 (- (aref coord 1) ?1)))
455 (- (aref coord 0) ?a)))
456
457 (defsubst chess-index-to-coord (index)
458 "Convert the chess position INDEX into a coord string."
459 (assert (and (>= index 0) (< index 64)))
460 (concat (char-to-string (+ (mod index 8) ?a))
461 (char-to-string (+ (- 7 (/ index 8)) ?1))))
462
463 (defsubst chess-index-rank (index)
464 "Return the rank component of the given INDEX."
465 (assert (and (>= index 0) (< index 64)))
466 (/ index 8))
467
468 (defsubst chess-index-file (index)
469 "Return the file component of the given INDEX."
470 (assert (and (>= index 0) (< index 64)))
471 (mod index 8))
472
473 (defsubst chess-incr-index (index rank-move file-move)
474 "Create a new INDEX from an old one, by adding RANK-MOVE and FILE-MOVE."
475 (assert (and (>= index 0) (< index 64)))
476 (assert (and (>= rank-move -7) (<= rank-move 7)))
477 (assert (and (>= file-move -7) (<= file-move 7)))
478 (let ((newrank (+ (chess-index-rank index) rank-move))
479 (newfile (+ (chess-index-file index) file-move)))
480 (if (and (>= newrank 0) (< newrank 8)
481 (>= newfile 0) (< newfile 8))
482 (chess-rf-to-index newrank newfile))))
483
484 (defsubst chess-incr-index* (index rank-move file-move)
485 "Create a new INDEX from an old one, by adding RANK-MOVE and FILE-MOVE.
486 This differs from `chess-incr-index' by performing no safety checks,
487 in order to execute faster."
488 (assert (and (>= index 0) (< index 64)))
489 (assert (and (>= rank-move -7) (<= rank-move 7)))
490 (assert (and (>= file-move -7) (<= file-move 7)))
491 (chess-rf-to-index (+ (chess-index-rank index) rank-move)
492 (+ (chess-index-file index) file-move)))
493
494 (defsubst chess-pos-piece-p (position index piece-or-color)
495 "Return non-nil if at POSITION/INDEX there is the given PIECE-OR-COLOR.
496 If PIECE-OR-COLOR is t for white or nil for black, any piece of that
497 color will do."
498 (assert (vectorp position))
499 (assert (and (>= index 0) (< index 64)))
500 (assert (memq piece-or-color
501 '(t nil ? ?K ?Q ?N ?B ?R ?P ?k ?q ?n ?b ?r ?p)))
502 (let ((p (chess-pos-piece position index)))
503 (cond
504 ((= p ? ) (eq p piece-or-color))
505 ((eq piece-or-color t) (< p ?a))
506 ((eq piece-or-color nil) (> p ?a))
507 (t (= p piece-or-color)))))
508
509 (defsubst chess-pos-search (position piece-or-color)
510 "Look on POSITION anywhere for PIECE-OR-COLOR, returning all coordinates.
511 If PIECE-OR-COLOR is t for white or nil for black, any piece of that
512 color will do."
513 (assert (vectorp position))
514 (assert (memq piece-or-color
515 '(t nil ? ?K ?Q ?N ?B ?R ?P ?k ?q ?n ?b ?r ?p)))
516 (let (found)
517 (dotimes (i 64)
518 (if (chess-pos-piece-p position i piece-or-color)
519 (push i found)))
520 found))
521
522 (defsubst chess-pos-to-string (position &optional full)
523 "Convert the given POSITION into a string.
524 The returned string can be converted back to a position using
525 `chess-pos-from-string'."
526 (assert (vectorp position))
527 (chess-pos-to-fen position full))
528
529 (defsubst chess-pos-from-string (string)
530 "Convert the given STRING to a chess position.
531 This string should have been created by `chess-pos-to-string'."
532 (assert (stringp string))
533 (chess-fen-to-pos string))
534
535 (defconst chess-pos-piece-values
536 '((?p . 1)
537 (?n . 3)
538 (?b . 3)
539 (?q . 9)
540 (?r . 5)
541 (?k . 0)))
542
543 (defun chess-pos-material-value (position color)
544 "Return the aggregate material value in POSITION for COLOR."
545 (assert (vectorp position))
546 (assert (memq color '(nil t)))
547 (let ((pieces (chess-pos-search position color))
548 (value 0))
549 (dolist (index pieces)
550 (setq value
551 (+ value (cdr (assq (downcase (chess-pos-piece position index))
552 chess-pos-piece-values)))))
553 value))
554
555 (chess-message-catalog 'english
556 '((move-from-blank . "Attempted piece move from blank square %s")))
557
558 (defun chess-pos-move (position &rest changes)
559 "Move a piece on the POSITION directly, using the indices FROM and TO.
560 This function does not check any rules, it only makes sure you are not
561 trying to move a blank square."
562 (assert (vectorp position))
563 (assert (listp changes))
564 (assert (> (length changes) 0))
565
566 ;; apply the piece movements listed in `changes'
567 (let ((ch changes))
568 (while ch
569 (if (symbolp (car ch))
570 (setq ch nil)
571 (let* ((from (car ch))
572 (to (cadr ch))
573 (piece (chess-pos-piece position from)))
574 (if (= piece ? )
575 (chess-error 'move-from-blank (chess-index-to-coord from)))
576 (chess-pos-set-piece position from ? )
577 (chess-pos-set-piece position to piece))
578 (setq ch (cddr ch)))))
579
580 ;; now fix up the resulting position
581 (let ((color (chess-pos-side-to-move position)))
582
583 ;; if the move was en-passant, remove the captured pawn
584 (if (memq :en-passant changes)
585 (chess-pos-set-piece position
586 (chess-incr-index (cadr changes)
587 (if color 1 -1) 0) ? ))
588
589 ;; once a piece is moved, en passant is no longer available
590 (chess-pos-set-en-passant position nil)
591
592 ;; if a king or rook moves, no more castling; also, if a pawn
593 ;; jumps ahead two, mark it en-passantable
594 (unless (symbolp (car changes))
595 (let ((piece (downcase (chess-pos-piece position (cadr changes)))))
596 (cond
597 ((= piece ?k)
598 (chess-pos-set-can-castle position (if color ?K ?k) nil)
599 (chess-pos-set-can-castle position (if color ?Q ?q) nil))
600
601 ((= piece ?r)
602 (let ((king (chess-pos-king-index position color)))
603 (if (and (chess-pos-can-castle position (if color ?Q ?q))
604 (< (chess-index-file (car changes)) king))
605 (chess-pos-set-can-castle position (if color ?Q ?q) nil)
606 (if (and (chess-pos-can-castle position (if color ?K ?k))
607 (> (chess-index-file (car changes)) king))
608 (chess-pos-set-can-castle position (if color ?K ?k) nil)))))
609
610 ((and (= piece ?p)
611 (> (abs (- (chess-index-rank (cadr changes))
612 (chess-index-rank (car changes)))) 1))
613 (chess-pos-set-en-passant position (cadr changes))))))
614
615 ;; toggle the side whose move it is
616 (unless chess-pos-always-white
617 (chess-pos-set-side-to-move position (not color)))
618
619 ;; promote the piece if we were meant to
620 (let ((new-piece (cadr (memq :promote changes))))
621 (if new-piece
622 (chess-pos-set-piece position (cadr changes)
623 (if color
624 new-piece
625 (downcase new-piece)))))
626
627 ;; did we leave the position in check, mate or stalemate?
628 (chess-pos-set-status position nil)
629 (cond
630 ((memq :check changes)
631 (chess-pos-set-status position :check))
632 ((memq :checkmate changes)
633 (chess-pos-set-status position :checkmate))
634 ((memq :stalemate changes)
635 (chess-pos-set-status position :stalemate)))
636
637 ;; return the final position
638 position))
639
640 (chess-message-catalog 'english
641 '((piece-unrecognized . "Unrecognized piece identifier")))
642
643 (eval-when-compile
644 (defvar candidates)
645 (defvar check-only))
646
647 (defsubst chess--add-candidate (candidate)
648 (if check-only
649 (throw 'in-check t)
650 (push candidate candidates)))
651
652 (defun chess-search-position (position target piece &optional check-only)
653 "Look on POSITION from TARGET for a PIECE that can move there.
654 This routine looks along legal paths of movement for PIECE. It
655 differs from `chess-pos-search', which is a more basic function that
656 doesn't take piece movement into account.
657
658 If PIECE is t or nil, legal piece movements for any piece of that
659 color will be considered (t for white, nil for black). Otherwise, the
660 case of the PIECE determines color.
661
662 The return value is a list of candidates, which means a list of
663 indices which indicate where a piece may have moved from."
664 (assert (vectorp position))
665 (assert (and (>= target 0) (< target 64)))
666 (assert (memq piece '(t nil ?K ?Q ?N ?B ?R ?P ?k ?q ?n ?b ?r ?p)))
667 (let* ((color (if (char-valid-p piece)
668 (< piece ?a)
669 piece))
670 (bias (if color -1 1))
671 (test-piece (and (char-valid-p piece)
672 (upcase piece)))
673 p pos candidates)
674 (cond
675 ;; if the piece is `t', it means to find the candidates resulting
676 ;; from any piece movement. This is useful for testing whether a
677 ;; king is in check, for example.
678 ((memq piece '(t nil))
679 (dolist (p (if check-only
680 '(?P ?R ?N ?B ?Q)
681 '(?P ?R ?N ?B ?Q ?K)))
682 (mapc 'chess--add-candidate
683 (chess-search-position position target
684 (if piece p (downcase p))
685 check-only))))
686
687 ;; skip erroneous space requests
688 ((= test-piece ? ))
689
690 ;; pawn movement, which is diagonal 1 when taking, but forward
691 ;; 1 or 2 when moving (the most complex piece, actually)
692 ((= test-piece ?P)
693 (let ((p (chess-pos-piece position target)))
694 (if (if (= p ? )
695 ;; check for en passant
696 (and (= (chess-index-rank target) (if color 2 5))
697 ;; make this fail if no en-passant is possible
698 (= (or (chess-pos-en-passant position) 100)
699 (or (chess-incr-index target (if color 1 -1) 0) 200))
700 (or (and (setq pos (chess-incr-index target
701 (if color 1 -1) -1))
702 (chess-pos-piece-p position pos
703 (if color ?P ?p)))
704 (and (setq pos (chess-incr-index target
705 (if color 1 -1) 1))
706 (chess-pos-piece-p position pos
707 (if color ?P ?p)))))
708 (if color (> p ?a) (< p ?a)))
709 (progn
710 (if (and (setq pos (chess-incr-index target (- bias) -1))
711 (chess-pos-piece-p position pos piece))
712 (chess--add-candidate pos))
713 (if (and (setq pos (chess-incr-index target (- bias) 1))
714 (chess-pos-piece-p position pos piece))
715 (chess--add-candidate pos)))
716 (if (setq pos (chess-incr-index target (- bias) 0))
717 (if (chess-pos-piece-p position pos piece)
718 (chess--add-candidate pos)
719 (if (and (chess-pos-piece-p position pos ? )
720 (= (if color 4 3) (chess-index-rank target))
721 (setq pos (chess-incr-index pos (- bias) 0))
722 (chess-pos-piece-p position pos piece))
723 (chess--add-candidate pos)))))))
724
725 ;; the rook, bishop and queen are the easiest; just look along
726 ;; rank and file and/or diagonal for the nearest pieces!
727 ((memq test-piece '(?R ?B ?Q))
728 (dolist (dir (cond
729 ((= test-piece ?R)
730 '( (-1 0)
731 (0 -1) (0 1)
732 (1 0)))
733 ((= test-piece ?B)
734 '((-1 -1) (-1 1)
735
736 (1 -1) (1 1)))
737 ((= test-piece ?Q)
738 '((-1 -1) (-1 0) (-1 1)
739 (0 -1) (0 1)
740 (1 -1) (1 0) (1 1)))))
741 ;; up the current file
742 (setq pos (apply 'chess-incr-index target dir))
743 (while pos
744 (if (chess-pos-piece-p position pos piece)
745 (progn
746 (chess--add-candidate pos)
747 (setq pos nil))
748 (setq pos (and (chess-pos-piece-p position pos ? )
749 (apply 'chess-incr-index pos dir)))))
750
751 ;; test whether the rook can move to the target by castling
752 (if (= test-piece ?R)
753 (let (rook)
754 (if (and (equal target (chess-rf-to-index (if color 7 0) 5))
755 (setq rook (chess-pos-can-castle position
756 (if color ?K ?k)))
757 (chess-ply-castling-changes position))
758 (chess--add-candidate rook)
759 (if (and (equal target (chess-rf-to-index (if color 7 0) 3))
760 (setq rook (chess-pos-can-castle position
761 (if color ?Q ?q)))
762 (chess-ply-castling-changes position t))
763 (chess--add-candidate rook)))))))
764
765 ;; the king is a trivial case of the queen, except when castling
766 ((= test-piece ?K)
767 (let ((dirs '((-1 -1) (-1 0) (-1 1)
768 (0 -1) (0 1)
769 (1 -1) (1 0) (1 1))))
770 (while dirs
771 ;; up the current file
772 (setq pos (apply 'chess-incr-index target (car dirs)))
773 (if (and pos (chess-pos-piece-p position pos piece))
774 (progn
775 (chess--add-candidate pos)
776 (setq dirs nil))
777 (setq dirs (cdr dirs))))
778
779 ;; test whether the king can move to the target by castling
780 (if (or (and (equal target (chess-rf-to-index (if color 7 0) 6))
781 (chess-pos-can-castle position (if color ?K ?k))
782 (chess-ply-castling-changes position))
783 (and (equal target (chess-rf-to-index (if color 7 0) 2))
784 (chess-pos-can-castle position (if color ?Q ?q))
785 (chess-ply-castling-changes position t)))
786 (chess--add-candidate (chess-pos-king-index position color)))))
787
788 ;; the knight is a zesty little piece; there may be more than
789 ;; one, but at only one possible square in each direction
790 ((= test-piece ?N)
791 (dolist (dir '((-2 -1) (-2 1)
792 (-1 -2) (-1 2)
793 (1 -2) (1 2)
794 (2 -1) (2 1)))
795 ;; up the current file
796 (if (and (setq pos (apply 'chess-incr-index target dir))
797 (chess-pos-piece-p position pos piece))
798 (chess--add-candidate pos))))
799
800 (t (chess-error 'piece-unrecognized)))
801
802 ;; prune from the discovered candidates list any moves which would
803 ;; leave the king in check; castling through check has already
804 ;; been eliminated.
805 (if (and candidates (char-valid-p piece))
806 (setq candidates
807 (chess-pos-legal-candidates position color target
808 candidates)))
809
810 ;; return the final list of candidate moves
811 candidates))
812
813 (defun chess-pos-legal-candidates (position color target candidates)
814 "Test if TARGET can legally be reached by any of CANDIDATES.
815 Return the list of candidates that can reach it.
816
817 CANDIDATES is a list of position indices which indicate the piece to
818 be moved, and TARGET is the index of the location to be moved to.
819
820 Note: All of the pieces specified by CANDIDATES must be of the same
821 type. Also, it is the callers responsibility to ensure that the piece
822 can legally reach the square in question. This function merely
823 assures that the resulting position is valid."
824 (assert (vectorp position))
825 (assert (memq color '(nil t)))
826 (assert (and (>= target 0) (< target 64)))
827 (assert (listp candidates))
828 (assert (> (length candidates) 0))
829 (let ((cand candidates)
830 (piece (chess-pos-piece position (car candidates)))
831 other-piece last-cand king-pos)
832 (while cand
833 (unwind-protect
834 (progn
835 ;; determine the resulting position
836 (chess-pos-set-piece position (car cand) ? )
837 (setq other-piece (chess-pos-piece position target))
838 (chess-pos-set-piece position target piece)
839 ;; find the king (only once if the king isn't moving)
840 (if (or (null king-pos)
841 (memq piece '(?K ?k)))
842 (setq king-pos (chess-pos-king-index position color)))
843 ;; can anybody from the opposite side reach him? if so,
844 ;; drop the candidate
845 (if (and king-pos
846 (catch 'in-check
847 (chess-search-position position king-pos
848 (not color) t)))
849 (if last-cand
850 (setcdr last-cand (cdr cand))
851 (setq candidates (cdr candidates)))
852 (setq last-cand cand)))
853 ;; return the position to its original state
854 (chess-pos-set-piece position target other-piece)
855 (chess-pos-set-piece position (car cand) piece))
856 ;; try the next candidate
857 (setq cand (cdr cand)))
858 candidates))
859
860 (provide 'chess-pos)
861
862 ;;; chess-pos.el ends here