]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo] Fix bug: Relax sync regexp.
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Version: 2.2.14
7
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;; Playing
24 ;; -------
25 ;;
26 ;; This file provides the command `gnugo' which allows you to play the game of
27 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
28 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
29 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
30 ;; Go" to refer to the process object created by running the external program.
31 ;;
32 ;; At the start of a new game, you can pass additional command-line arguments
33 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
34 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
35 ;; both komi and handicap.
36 ;;
37 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
38 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
39 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
40 ;; back through an arbitrary stone that you played, place the cursor on a
41 ;; stone and type `U' (note: uppercase). Other keybindings are described in
42 ;; the `gnugo-board-mode' documentation, which you may view with the command
43 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
44 ;; the last move and who is currently to play. Capture counts and other info
45 ;; are shown on the mode line immediately following the major mode name.
46 ;;
47 ;; While GNU Go is pondering its next move, certain commands that rely on its
48 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
49 ;; is normal. When it is your turn again you may retry the command. In the
50 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
51 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
52 ;;
53 ;; If GNU Go should crash during a game the mode line will show "no process".
54 ;; Please report the event to the GNU Go maintainers so that they can improve
55 ;; the program.
56 ;;
57 ;;
58 ;; Meta-Playing (aka Customizing)
59 ;; ------------------------------
60 ;;
61 ;; Customization is presently limited to
62 ;; vars: `gnugo-program'
63 ;; `gnugo-animation-string'
64 ;; `gnugo-mode-line'
65 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
66 ;; `gnugo-xpms'
67 ;; normal hooks: `gnugo-board-mode-hook'
68 ;; `gnugo-post-move-hook'
69 ;; and the keymap: `gnugo-board-mode-map'
70 ;;
71 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
72 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
73 ;; interface.
74
75 ;;; Code:
76
77 (require 'cl-lib) ; use the source luke!
78 (require 'time-date) ; for `time-subtract'
79
80 ;;;---------------------------------------------------------------------------
81 ;;; Political arts
82
83 (defconst gnugo-version "2.2.14"
84 "Version of gnugo.el currently loaded.
85 This follows a MAJOR.MINOR.PATCH scheme.")
86
87 ;;;---------------------------------------------------------------------------
88 ;;; Variables for the uninquisitive programmer
89
90 (defvar gnugo-program "gnugo"
91 "Command to start an external program that speaks GTP, such as \"gnugo\".
92 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
93 the command `gnugo' will prefix OPTIONS in its default offering when it
94 queries you for additional options. It is an error for \"--mode\" to appear
95 in OPTIONS.
96
97 For more information on GTP and GNU Go, feel free to visit:
98 http://www.gnu.org/software/gnugo")
99
100 (defvar gnugo-board-mode-map nil
101 "Keymap for GNUGO Board mode.")
102
103 (defvar gnugo-board-mode-hook nil
104 "Hook run when entering GNUGO Board mode.")
105
106 (defvar gnugo-post-move-hook nil
107 "Normal hook run after a move and before the board is refreshed.
108 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
109 (setq inhibit-gnugo-refresh t)
110 Initially, when `run-hooks' is called, the current buffer is the GNUGO
111 Board buffer of the game. Hook functions that switch buffers must take
112 care not to call (directly or indirectly through some other function)
113 `gnugo-put' or `gnugo-get' after the switch.")
114
115 (defvar gnugo-animation-string
116 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
117 (concat jam jam jam jam jam
118 ;; "SECRET MESSAGE HERE"
119 blink blink blink blink blink blink blink blink
120 ;; Playing go is like fighting ignorance: when you think you have
121 ;; surrounded something by knowing it very well it often turns
122 ;; out that in the time you spent deepening this understanding,
123 ;; other areas of ignorance have surrounded you.
124 spin spin spin spin spin spin spin spin spin
125 ;; Playing go is not like fighting ignorance: what one person
126 ;; knows many people may come to know; knowledge does not build
127 ;; solely move by move. Wisdom, on the other hand...
128 yada yada yada))
129 "String whose individual characters are used for animation.
130 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
131 render the stones in their respective result groups as the first character
132 in the string, then the next, and so on.")
133
134 (defvar gnugo-mode-line "~b ~w :~m :~u"
135 "A `mode-line-format'-compliant value for GNUGO Board mode.
136 If a single string, the following special escape sequences are
137 replaced with their associated information:
138 ~b,~w black,white captures (a number)
139 ~p current player (black or white)
140 ~m move number
141 ~t time waiting for the current move
142 ~u time taken for the Ultimate (most recent) move
143 The times are in seconds, or \"-\" if that information is not available.
144 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
145
146 (defvar gnugo-X-face 'font-lock-string-face
147 "Name of face to use for X (black) stones.")
148
149 (defvar gnugo-O-face 'font-lock-builtin-face
150 "Name of face to use for O (white) stones.")
151
152 (defvar gnugo-grid-face 'default
153 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
154
155 ;;;---------------------------------------------------------------------------
156 ;;; Variables for the inquisitive programmer
157
158 (defconst gnugo-font-lock-keywords
159 '(("X" . gnugo-X-face)
160 ("O" . gnugo-O-face))
161 "Font lock keywords for `gnugo-board-mode'.")
162
163 (defvar gnugo-option-history nil)
164
165 (defvar gnugo-state nil) ; hint: C-c C-p
166
167 (eval-when-compile
168 (defvar gnugo-xpms nil))
169
170 ;;;---------------------------------------------------------------------------
171 ;;; Support functions
172
173 (defun gnugo-put (key value)
174 "Associate move/game/board-specific property KEY with VALUE.
175
176 There are many properties, each named by a keyword, that record and control
177 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
178 of properties, stored in the hash table `gnugo-state'. Here we document
179 some of the more stable properties. You may wish to use them as part of
180 a `gnugo-post-move-hook' function, for example. Be careful to preserve
181 the current buffer as `gnugo-state' is made into a buffer-local variable.
182 NOTE: In the following, \"see foo\" actually means \"see foo source or
183 you may never really understand to any degree of personal satisfaction\".
184
185 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
186
187 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
188
189 :game-over -- nil until game over at which time its value is set to
190 the alist `((live GROUP ...) (dead GROUP ...))'
191
192 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
193 a simple list of one or more gametrees, updated in
194 conjunction w/ :sgf-gametree and :monkey
195
196 :sgf-gametree -- one of the gametrees in :sgf-collection
197
198 :monkey -- vector of three elements: LOC, a pointer to a node on the
199 :sgf-gametree representing the most recently-played move
200 (the next move modifies the cdr of LOC); MEM, the simple
201 reverse-chronological list of previous LOC pointers; and
202 COUNT, the number of moves from the beginning of the game
203
204 :gnugo-color -- either \"black\" or \"white\"
205 :user-color
206 :last-mover
207
208 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
209 :waiting-start
210
211 :black-captures -- these are strings since gnugo.el doesn't do anything
212 :white-captures w/ the information besides display it in the mode line;
213 gory details in functions `gnugo-propertize-board-buffer'
214 and `gnugo-merge-showboard-results' (almost more effort
215 than they are worth!)
216
217 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
218 `gnugo-toggle-image-display' and `gnugo-refresh',
219 as well as gnugo-xpms.el (available elsewhere)
220
221 :all-yy -- list of 46 keywords used as the `category' text property
222 (so that their plists, typically w/ property `display' or
223 `do-not-display') are consulted by the Emacs display engine;
224 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
225 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
226
227 :lparen-ov -- overlays shuffled about to indicate the last move; only
228 :rparen-ov one is used when displaying using images
229
230 :last-user-bpos -- board position; keep the hapless human happy
231
232 As things stabilize probably more info will be added to this docstring."
233 (declare (indent 1))
234 (puthash key value gnugo-state))
235
236 (defun gnugo-get (key)
237 "Return the move/game/board-specific value for KEY.
238 See `gnugo-put'."
239 (gethash key gnugo-state))
240
241 (defun gnugo-describe-internal-properties ()
242 "Pretty-print `gnugo-state' properties in another buffer.
243 Handle the big, slow-to-render, and/or uninteresting ones specially."
244 (interactive)
245 (let ((buf (current-buffer))
246 (d (gnugo-get :diamond))
247 acc)
248 (maphash (lambda (&rest args)
249 (case (car args)
250 ((:xpms :local-xpms)
251 (setcdr args (format "hash: %X (%d images)"
252 (sxhash (cadr args))
253 (length (cadr args)))))
254 (:sgf-collection
255 (setcdr args (length (cadr args))))
256 (:monkey
257 (let* ((value (cadr args))
258 (loc (aref value 0)))
259 (setcdr args (list
260 (length (aref value 1))
261 (length (cdr loc))
262 (car loc))))))
263 (setq acc (cons args acc)))
264 gnugo-state)
265 (switch-to-buffer (get-buffer-create
266 (format "%s*GNUGO Board Properties*"
267 (gnugo-get :diamond))))
268 (erase-buffer)
269 (emacs-lisp-mode)
270 (setq truncate-lines t)
271 (save-excursion
272 (let ((standard-output (current-buffer)))
273 (pp (reverse acc)))
274 (goto-char (point-min))
275 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
276 (if (string= "" d)
277 ".+\n"
278 ""))))
279 (while (re-search-forward rx (point-max) t)
280 (let ((pos (get-text-property (string-to-number (match-string 1))
281 'gnugo-position buf)))
282 (delete-region (+ 2 (match-beginning 0)) (point))
283 (insert (format " %S" pos))))))
284 (message "%d properties" (length acc))))
285
286 (defun gnugo-board-buffer-p (&optional buffer)
287 "Return non-nil if BUFFER is a GNUGO Board buffer."
288 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
289
290 (defun gnugo-board-user-play-ok-p (&optional buffer)
291 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
292 (with-current-buffer (or buffer (current-buffer))
293 (and gnugo-state (not (gnugo-get :waitingp)))))
294
295 (defun gnugo-other (color)
296 (if (string= "black" color) "white" "black"))
297
298 (defun gnugo-gate (&optional in-progress-p)
299 (unless (gnugo-board-buffer-p)
300 (user-error "Wrong buffer -- try M-x gnugo"))
301 (unless (gnugo-get :proc)
302 (user-error "No \"gnugo\" process!"))
303 (when (gnugo-get :waitingp)
304 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
305 (gnugo-get :user-color)))
306 (when (and (gnugo-get :game-over) in-progress-p)
307 (user-error "Sorry, game over")))
308
309 (defun gnugo-sentinel (proc string)
310 (let ((status (process-status proc)))
311 (when (or (eq status 'exit)
312 (eq status 'signal))
313 (let ((buf (process-buffer proc)))
314 (when (buffer-live-p buf)
315 (with-current-buffer buf
316 (setq mode-line-process '( " [%s]"))
317 (when (eq proc (gnugo-get :proc))
318 (gnugo-put :proc nil))))))))
319
320 (defun gnugo-send-line (line)
321 (let ((proc (gnugo-get :proc)))
322 (process-send-string proc line)
323 (process-send-string proc "\n")))
324
325 (defun gnugo-synchronous-send/return (message)
326 "Return (TIME . STRING) where TIME is that returned by `current-time' and
327 STRING omits the two trailing newlines. See also `gnugo-query'."
328 (when (gnugo-get :waitingp)
329 (user-error "Sorry, still waiting for %s to play"
330 (gnugo-get :gnugo-color)))
331 (let ((proc (gnugo-get :proc)))
332 (process-put proc :srs "") ; synchronous return stash
333 (set-process-filter
334 proc (lambda (proc string)
335 (let* ((so-far (process-get proc :srs))
336 (start (max 0 (- (length so-far) 2))) ; backtrack a little
337 (full (concat so-far string)))
338 (process-put proc :srs full)
339 (when (string-match "\n\n" full start)
340 (process-put proc :srs (cons (current-time)
341 (substring full 0 -2)))))))
342 (gnugo-send-line message)
343 (let (rv)
344 ;; type change => break
345 (while (stringp (setq rv (process-get proc :srs)))
346 (accept-process-output proc 30))
347 (process-put proc :srs "")
348 rv)))
349
350 (defun gnugo-query (message-format &rest args)
351 "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
352 The TIME portion is omitted as well as the first two characters of the STRING
353 portion (corresponding to the status indicator in the Go Text Protocol). Use
354 this function when you are sure the command cannot fail. The first arg is
355 a format string applied to the rest of the args."
356 (substring (cdr (gnugo-synchronous-send/return
357 (apply 'format message-format args)))
358 2))
359
360 (defun gnugo-lsquery (message-format &rest args)
361 (split-string (apply 'gnugo-query message-format args)))
362
363 (defsubst gnugo-treeroot (prop)
364 (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
365
366 (defun gnugo-goto-pos (pos)
367 "Move point to board position POS, a letter-number string."
368 (goto-char (point-min))
369 (forward-line (- (1+ (gnugo-treeroot :SZ))
370 (string-to-number (substring pos 1))))
371 (forward-char 1)
372 (forward-char (+ (if (= 32 (following-char)) 1 2)
373 (* 2 (- (let ((letter (aref pos 0)))
374 (if (> ?I letter)
375 letter
376 (1- letter)))
377 ?A)))))
378
379 (defun gnugo-f (frag)
380 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
381
382 (defun gnugo-yang (c)
383 (cdr (assq c '((?+ . hoshi)
384 (?. . empty)
385 (?X . (bmoku . bpmoku))
386 (?O . (wmoku . wpmoku))))))
387
388 (defun gnugo-yy (yin yang &optional momentaryp)
389 (gnugo-f (format "%d-%s"
390 yin (cond ((and (consp yang) momentaryp) (cdr yang))
391 ((consp yang) (car yang))
392 (t yang)))))
393
394 (defun gnugo-toggle-image-display ()
395 (unless (and (fboundp 'display-images-p) (display-images-p))
396 (user-error "Display does not support images, sorry"))
397 (require 'gnugo-xpms)
398 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
399 (user-error "Could not load `gnugo-xpms', sorry"))
400 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
401 (unless (eq fresh (gnugo-get :xpms))
402 (gnugo-put :xpms fresh)
403 (gnugo-put :all-yy nil)))
404 (let* ((new (not (gnugo-get :display-using-images)))
405 (act (if new 'display 'do-not-display)))
406 (mapc (lambda (yy)
407 (setcar (symbol-plist yy) act))
408 (or (gnugo-get :all-yy)
409 (gnugo-put :all-yy
410 (prog1 (mapcar (lambda (ent)
411 (let* ((k (car ent))
412 (yy (gnugo-yy (cdr k) (car k))))
413 (setplist yy `(not-yet ,(cdr ent)))
414 yy))
415 (gnugo-get :xpms))
416 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
417 'not-yet))))
418 (gnugo-put :w-imul (car imul))
419 (gnugo-put :h-imul (cdr imul)))))))
420 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
421 (gnugo-put :highlight-last-move-spec
422 (if new
423 '((lambda (p)
424 (get (gnugo-yy (get-text-property p 'gnugo-yin)
425 (get-text-property p 'gnugo-yang)
426 t)
427 'display))
428 0 delete-overlay)
429 (gnugo-get :default-highlight-last-move-spec)))
430 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
431 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
432 (mapc 'delete-overlay (cdar group))
433 (setcdr (car group) nil))
434 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
435 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
436 (gnugo-put :display-using-images new)))
437
438 (defun gnugo-toggle-grid ()
439 "Turn the grid around the board on or off."
440 (interactive)
441 (funcall (if (memq :nogrid buffer-invisibility-spec)
442 'remove-from-invisibility-spec
443 'add-to-invisibility-spec)
444 :nogrid)
445 (save-excursion (gnugo-refresh)))
446
447 (defun gnugo-propertize-board-buffer ()
448 (erase-buffer)
449 (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
450 (let* ((grid-props (list 'invisible :nogrid
451 'font-lock-face gnugo-grid-face))
452 (%gpad (gnugo-f 'gpad))
453 (%gspc (gnugo-f 'gspc))
454 (%lpad (gnugo-f 'lpad))
455 (%rpad (gnugo-f 'rpad))
456 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
457 (size (gnugo-treeroot :SZ))
458 (size-string (number-to-string size)))
459 (goto-char (point-min))
460 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
461 (skip-chars-forward " ")
462 (put-text-property (1- (point)) (point) 'category %gpad)
463 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
464 (forward-char 1)
465 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
466 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
467 (let* ((row (match-string-no-properties 1))
468 (edge (match-end 0))
469 (other-edge (+ edge (* 2 size) -1))
470 (right-empty (+ other-edge (length row) 1))
471 (top-p (string= size-string row))
472 (bot-p (string= "1" row)))
473 (let* ((nL (- edge 1 (length size-string)))
474 (nR (- edge 1))
475 (ov (make-overlay nL nR (current-buffer) t)))
476 (add-text-properties nL nR grid-props)
477 ;; We redundantly set `invisible' in the overlay to workaround
478 ;; a display bug whereby text *following* the overlaid text is
479 ;; displayed with the face of the overlaid text, but only when
480 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
481 ;; This has something to do w/ the bletcherous `before-string'.
482 (overlay-put ov 'invisible :nogrid)
483 (overlay-put ov 'category %lpad))
484 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
485 ((< other-edge p))
486 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
487 (truncate (- p edge) 2))
488 row))
489 (yin (let ((A-p (= edge p))
490 (Z-p (= (1- other-edge) p)))
491 (cond ((and top-p A-p) 1)
492 ((and top-p Z-p) 3)
493 ((and bot-p A-p) 7)
494 ((and bot-p Z-p) 9)
495 (top-p 2)
496 (bot-p 8)
497 (A-p 4)
498 (Z-p 6)
499 (t 5))))
500 (yang (gnugo-yang (char-after p))))
501 (add-text-properties p (1+ p)
502 `(gnugo-position
503 ,position
504 gnugo-yin
505 ,yin
506 gnugo-yang
507 ,yang
508 category
509 ,(gnugo-yy yin yang)
510 front-sticky
511 (gnugo-position gnugo-yin))))
512 (unless (= (1- other-edge) p)
513 (add-text-properties (1+ p) (+ 2 p) ispc-props)
514 (put-text-property p (+ 2 p) 'intangible ival)))
515 (add-text-properties (1+ other-edge) right-empty grid-props)
516 (goto-char right-empty)
517 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
518 (let ((prop (if (string= "WH" (match-string 1))
519 :white-captures
520 :black-captures))
521 (beg (match-beginning 2))
522 (end (match-end 2)))
523 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
524 (gnugo-put prop (match-string-no-properties 2))))
525 (end-of-line)
526 (put-text-property right-empty (point) 'category %rpad)
527 (forward-char 1)))
528 (add-text-properties (1- (point)) (point-max) grid-props)
529 (skip-chars-forward " ")
530 (put-text-property (1- (point)) (point) 'category %gpad)
531 (put-text-property (point) (progn (end-of-line) (point))
532 'category %gspc)))
533
534 (defun gnugo-merge-showboard-results ()
535 (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
536 (adj 1) ; string to buffer position adjustment
537
538 (sync "[0-9]* stones$")
539 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
540 ;; restrictive a condition that fails in the case of:
541 ;;
542 ;; (before)
543 ;; ... WHITE has captured 1 stones
544 ;; ^
545 ;; (after)
546 ;; ... WHITE has captured 14 stones
547 ;; ^
548 ;;
549 ;; where the after count has more digits than the before count,
550 ;; but shares the same leading digits. In this case, the result
551 ;; of `compare-strings' points to the SPC following the before
552 ;; count (indicated by caret in this example).
553
554 (bef (buffer-substring-no-properties (point-min) (point-max)))
555 (bef-start 0) (bef-idx 0)
556 (aft-start 0) (aft-idx 0)
557 aft-sync-backtrack mis inc cut new very-strange)
558 (while (numberp (setq mis (compare-strings bef bef-start nil
559 aft aft-start nil)))
560 (setq aft-sync-backtrack nil
561 inc (if (cl-minusp mis)
562 (- (+ 1 mis))
563 (- mis 1))
564 bef-idx (+ bef-start inc)
565 aft-idx (+ aft-start inc)
566 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
567 (match-end 0)
568 (1+ bef-idx))
569 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
570 (let ((peek (1- aft-idx)))
571 (while (not (= 32 (aref aft peek)))
572 (setq peek (1- peek)))
573 (setq aft-sync-backtrack (1+ peek))))
574 (match-end 0)
575 (1+ aft-idx))
576 cut (+ bef-idx adj
577 (if aft-sync-backtrack
578 (- aft-sync-backtrack aft-idx)
579 0)))
580 (goto-char cut)
581 (if aft-sync-backtrack
582 (let* ((asb aft-sync-backtrack)
583 (l-p (get-text-property cut :gnugo-cf))
584 (old-len (car l-p))
585 (capprop (cdr l-p))
586 (keep (text-properties-at cut)))
587 (setq new (substring aft asb (string-match " " aft asb)))
588 (plist-put keep :gnugo-cf (cons (length new) capprop))
589 (gnugo-put capprop new)
590 (delete-char old-len)
591 (insert (apply 'propertize new keep))
592 (setq adj (+ adj (- (length new) old-len))))
593 (setq new (aref aft aft-idx))
594 (insert-and-inherit (char-to-string new))
595 (let ((yin (get-text-property cut 'gnugo-yin))
596 (yang (gnugo-yang new)))
597 (add-text-properties cut (1+ cut)
598 `(gnugo-yang
599 ,yang
600 category
601 ,(gnugo-yy yin yang))))
602 (delete-char 1)
603 ;; do this last to avoid complications w/ font lock
604 ;; (this also means we cannot include `intangible' in `front-sticky')
605 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
606 (put-text-property cut (1+ cut) 'intangible very-strange))))))
607
608 (defun gnugo-move-history (&optional rsel)
609 "Determine and return the game's move history.
610 Optional arg RSEL controls side effects and return value.
611 If nil, display the history in the echo area as \"(N moves)\"
612 followed by the space-separated list of moves. When called
613 interactively with a prefix arg (i.e., RSEL is `(4)'), display
614 similarly, but suffix with the mover (either \":B\" or \":W\").
615 If RSEL is the symbol `car' return the most-recent move; if
616 `cadr', the next-to-most-recent move; if `count' the number of
617 moves thus far.
618
619 For all other values of RSEL, do nothing and return nil."
620 (interactive "P")
621 (let ((size (gnugo-treeroot :SZ))
622 col
623 (mem (aref (gnugo-get :monkey) 1))
624 acc node mprop move)
625 (cl-labels
626 ((as-pos (cc) (if (string= "tt" cc)
627 "PASS"
628 (setq col (aref cc 0))
629 (format "%c%d"
630 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
631 (- size (- (aref cc 1) ?a)))))
632 (next (byp) (when (setq node (caar mem)
633 mprop (or (assq :B node)
634 (assq :W node)))
635 (setq move (as-pos (cdr mprop))
636 mem (cdr mem))
637 (push (if byp
638 (format "%s%s" move (car mprop))
639 move)
640 acc)))
641 (tell () (message "(%d moves) %s"
642 (length acc)
643 (mapconcat 'identity (nreverse acc) " "))))
644 (cond
645 ((not rsel) (while (next nil)) (tell))
646 ((equal '(4) rsel) (while (next t)) (tell))
647 ((eq 'car rsel) (car (next nil)))
648 ((eq 'cadr rsel) (next nil) (car (next nil)))
649 ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
650
651 (defun gnugo-note (property value &optional movep mogrifyp)
652 (when mogrifyp
653 (let ((sz (gnugo-treeroot :SZ)))
654 (cl-labels
655 ((mog (pos) (if (string= "PASS" pos)
656 "tt"
657 (let* ((col (aref pos 0))
658 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
659 (two (+ ?a (- sz (string-to-number
660 (substring pos 1))))))
661 (format "%c%c" one two)))))
662 (setq value (if (consp value)
663 (mapcar #'mog value)
664 (mog value))))))
665 (let* ((fruit (list (cons property value)))
666 (monkey (gnugo-get :monkey))
667 (loc (aref monkey 0)))
668 (if movep
669 (let ((mem (aref monkey 1)))
670 ;; todo: do variation check/merge/branch here.
671 (setcdr loc (list fruit))
672 (aset monkey 0 (setq loc (cdr loc)))
673 (aset monkey 1 (cons loc mem))
674 (aset monkey 2 (1+ (aref monkey 2))))
675 (setcdr (last (car loc)) fruit))))
676
677 (defun gnugo-close-game (end-time resign)
678 (gnugo-put :game-end-time end-time)
679 (let ((now (or end-time (current-time))))
680 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
681 (cadr now))))
682 (gnugo-put :game-over
683 (if (or (eq t resign)
684 (and (stringp resign)
685 (string-match "[BW][+][Rr]esign" resign)))
686 (cl-labels
687 ((ls (color) (mapcar
688 (lambda (x)
689 (cons (list color)
690 (split-string x)))
691 (split-string
692 (gnugo-query "worm_stones %s" color)
693 "\n"))))
694 (let ((live (append (ls "black") (ls "white"))))
695 `((live ,@live)
696 (dead))))
697 (let ((dd (gnugo-query "dragon_data"))
698 (start 0) mem color ent live dead)
699 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
700 dd start)
701 (setq mem (match-string 1 dd)
702 color (match-string 2 dd)
703 start (match-end 0)
704 ent (cons (list color)
705 (sort (gnugo-lsquery "dragon_stones %s" mem)
706 'string<)))
707 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
708 dd start)
709 (if (match-string 2 dd)
710 (push ent live)
711 (push ent dead))
712 (setq start (match-end 0)))
713 `((live ,@live)
714 (dead ,@dead))))))
715
716 (defun gnugo--unclose-game ()
717 (dolist (prop '(:game-over ; all those in -close-game
718 :scoring-seed
719 :game-end-time))
720 (gnugo-put prop nil))
721 (let* ((root (car (gnugo-get :sgf-gametree)))
722 (cur (assq :RE root)))
723 (when cur
724 (assert (not (eq cur (car root))) nil
725 ":RE at head of root node: %S"
726 root)
727 (delq cur root))))
728
729 (defun gnugo-push-move (userp move)
730 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
731 (start (gnugo-get :waiting-start))
732 (now (current-time))
733 (resignp (string= "resign" move))
734 (passp (string= "PASS" move))
735 (head (gnugo-move-history 'car))
736 (onep (and head (string= "PASS" head)))
737 (donep (or resignp (and onep passp))))
738 (unless passp
739 (gnugo-merge-showboard-results))
740 (gnugo-put :last-mover color)
741 (when userp
742 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
743 (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
744 (when resignp
745 (gnugo-note :EV "resignation"))
746 (when start
747 (gnugo-put :last-waiting (cadr (time-subtract now start))))
748 (when donep
749 (gnugo-close-game now resignp))
750 (gnugo-put :waiting-start (and (not donep) now))
751 donep))
752
753 (defun gnugo-venerate (yin yang)
754 (let* ((fg-yy (gnugo-yy yin yang))
755 (fg-disp (or (get fg-yy 'display)
756 (get fg-yy 'do-not-display)))
757 (fg-data (plist-get (cdr fg-disp) :data))
758 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
759 (bg-disp (or (get bg-yy 'display)
760 (get bg-yy 'do-not-display)))
761 (bg-data (plist-get (cdr bg-disp) :data))
762 (bop (lambda (s)
763 (let* ((start 0)
764 (ncolors
765 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
766 (setq start (match-end 0))
767 (string-to-number (match-string 1 s)))))
768 (while (and (not (cl-minusp ncolors))
769 (string-match ",\n" s start))
770 (setq start (match-end 0)
771 ncolors (1- ncolors)))
772 (string-match "\"" s start)
773 (match-end 0))))
774 (new (copy-sequence fg-data))
775 (lx (length fg-data))
776 (sx (funcall bop fg-data))
777 (sb (funcall bop bg-data))
778 (color-key (aref new sx))) ; blech, heuristic
779 (while (< sx lx)
780 (when (and (not (= color-key (aref new sx)))
781 (cl-plusp (random 4)))
782 (aset new sx (aref bg-data sb)))
783 (incf sx)
784 (incf sb))
785 (create-image new 'xpm t :ascent 'center)))
786
787 (defun gnugo-refresh (&optional nocache)
788 "Update GNUGO Board buffer display.
789 While a game is in progress, parenthesize the last-played stone (no parens
790 for pass). If the buffer is currently displayed in the selected window,
791 recenter the board (presuming there is extra space in the window). Update
792 the mode line. Lastly, move point to the last position played by the user,
793 if that move was not a pass.
794
795 Prefix arg NOCACHE requests complete reconstruction of the display, which may
796 be slow. (This should normally be unnecessary; specify it only if the display
797 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
798 its move."
799 (interactive "P")
800 (when (and nocache (not (gnugo-get :waitingp)))
801 (gnugo-propertize-board-buffer))
802 (let* ((last-mover (gnugo-get :last-mover))
803 (other (gnugo-other last-mover))
804 (move (gnugo-move-history 'car))
805 (game-over (gnugo-get :game-over))
806 window last)
807 ;; last move
808 (when move
809 (let ((l-ov (gnugo-get :lparen-ov))
810 (r-ov (gnugo-get :rparen-ov)))
811 (if (member move '("PASS" "resign"))
812 (mapc 'delete-overlay (list l-ov r-ov))
813 (gnugo-goto-pos move)
814 (let* ((p (point))
815 (hspec (gnugo-get :highlight-last-move-spec))
816 (display-value (nth 0 hspec))
817 (l-offset (nth 1 hspec))
818 (l-new-pos (+ p l-offset))
819 (r-action (nth 2 hspec)))
820 (overlay-put l-ov 'display
821 (if (functionp display-value)
822 (funcall display-value p)
823 display-value))
824 (move-overlay l-ov l-new-pos (1+ l-new-pos))
825 (if r-action
826 (funcall r-action r-ov)
827 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
828 ;; buffer name
829 (rename-buffer (concat (gnugo-get :diamond)
830 (if game-over
831 (format "%s(game over)"
832 (if (string= move "resign")
833 (concat move "ation ")
834 ""))
835 (format "%s(%s to play)"
836 (if move (concat move " ") "")
837 other))))
838 ;; pall of death
839 (when game-over
840 (let ((live (cdr (assq 'live game-over)))
841 (dead (cdr (assq 'dead game-over)))
842 p pall)
843 (unless (eq game-over (get-text-property 1 'game-over))
844 (dolist (group (append live dead))
845 (dolist (pos (cdr group))
846 (gnugo-goto-pos pos)
847 (setq p (point))
848 (put-text-property p (1+ p) 'group group)))
849 (put-text-property 1 2 'game-over game-over))
850 (dolist (group live)
851 (when (setq pall (cdar group))
852 (mapc 'delete-overlay pall)
853 (setcdr (car group) nil)))
854 (dolist (group dead)
855 (unless (cdar group)
856 (let (ov pall c (color (caar group)))
857 (setq c (if (string= "black" color) "x" "o"))
858 (dolist (pos (cdr group))
859 (gnugo-goto-pos pos)
860 (setq p (point) ov (make-overlay p (1+ p)))
861 (overlay-put
862 ov 'display
863 (if (gnugo-get :display-using-images)
864 ;; respect the dead individually; it takes more time
865 ;; but that's not a problem (for them)
866 (gnugo-venerate (get-text-property p 'gnugo-yin)
867 (gnugo-yang (aref (upcase c) 0)))
868 (propertize c 'face 'font-lock-warning-face)))
869 (push ov pall))
870 (setcdr (car group) pall))))))
871 ;; window update
872 (when (setq window (get-buffer-window (current-buffer)))
873 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
874 (size (gnugo-treeroot :SZ))
875 (under10p (< size 10))
876 (h (- (truncate (- (window-height window)
877 (* size (gnugo-get :hmul))
878 (if gridp 2 0))
879 2)
880 (if gridp 0 1)))
881 (edges (window-edges window))
882 (right-w-edge (nth 2 edges))
883 (avail-width (- right-w-edge (nth 0 edges)))
884 (wmul (gnugo-get :wmul))
885 (imagesp (symbol-plist (gnugo-f 'ispc)))
886 (w (/ (- avail-width
887 (* size wmul)
888 (if imagesp
889 0
890 (1- size))
891 2 ; between board and grid
892 (if gridp
893 (if under10p 2 4)
894 0))
895 2.0)))
896 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
897 `(display ,(make-string h 10))
898 '(invisible :nogrid)))
899 (gpad . (display
900 (space :align-to
901 ,(+ w
902 2.0
903 (cond (imagesp (+ (* 0.5 wmul)
904 (if under10p
905 -0.5
906 0.5)))
907 (under10p 0)
908 (t 1))))))
909 (gspc . ,(when imagesp
910 `(display (space-width ,(- wmul 1.0)))))
911 (lpad . ,(let ((d `(display (space :align-to ,w))))
912 ;; We distinguish between these cases to
913 ;; workaround a display bug whereby the
914 ;; `before-string' is omitted entirely (not
915 ;; rendered) when interacting w/ the text
916 ;; mode last-move left-paren for moves in
917 ;; column A.
918 (if gridp
919 `(before-string
920 ,(apply 'propertize " " d))
921 d)))
922 (rpad . (display
923 (space :align-to ,(1- avail-width))))))
924 (setplist (gnugo-f (car pair)) (cdr pair)))))
925 ;; mode line update
926 (let ((cur (gnugo-get :mode-line)))
927 (unless (equal cur gnugo-mode-line)
928 (setq cur gnugo-mode-line)
929 (gnugo-put :mode-line cur)
930 (gnugo-put :mode-line-form
931 (cond ((stringp cur)
932 (setq cur (copy-sequence cur))
933 (let (acc cut c)
934 (while (setq cut (string-match "~[bwpmtu]" cur))
935 (aset cur cut ?%)
936 (setq cut (1+ cut) c (aref cur cut))
937 (aset cur cut ?s)
938 (push
939 `(,(intern (format "squig-%c" c))
940 ,(case c
941 (?b '(or (gnugo-get :black-captures) 0))
942 (?w '(or (gnugo-get :white-captures) 0))
943 (?p '(gnugo-other (gnugo-get :last-mover)))
944 (?t '(let ((ws (gnugo-get :waiting-start)))
945 (if ws
946 (cadr (time-since ws))
947 "-")))
948 (?u '(or (gnugo-get :last-waiting) "-"))
949 (?m '(gnugo-move-history 'count))))
950 acc))
951 `(let ,(delete-dups (copy-sequence acc))
952 (format ,cur ,@(reverse (mapcar 'car acc))))))
953 (t cur))))
954 (let ((form (gnugo-get :mode-line-form)))
955 (setq mode-line-process
956 (and form
957 ;; this dynamicism is nice but excessive in its wantonness
958 ;;- `(" [" (:eval ,form) "]")
959 ;; this dynamicism is ok because the user triggers it
960 (list (format " [%s]" (eval form))))))
961 (force-mode-line-update))
962 ;; last user move
963 (when (setq last (gnugo-get :last-user-bpos))
964 (gnugo-goto-pos last))))
965
966 ;;;---------------------------------------------------------------------------
967 ;;; Game play actions
968
969 (defun gnugo-get-move-insertion-filter (proc string)
970 (with-current-buffer (process-buffer proc)
971 (let* ((so-far (gnugo-get :get-move-string))
972 (full (gnugo-put :get-move-string (concat so-far string))))
973 (when (string-match "^= \\(.+\\)\n\n" full)
974 (let ((pos-or-pass (match-string 1 full)))
975 (gnugo-put :get-move-string nil)
976 (gnugo-put :waitingp nil)
977 (gnugo-push-move nil pos-or-pass)
978 (let ((buf (current-buffer)))
979 (let (inhibit-gnugo-refresh)
980 (run-hooks 'gnugo-post-move-hook)
981 (unless inhibit-gnugo-refresh
982 (with-current-buffer buf
983 (gnugo-refresh))))))))))
984
985 (defun gnugo-get-move (color)
986 (gnugo-put :waitingp t)
987 (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
988 (gnugo-send-line (concat "genmove " color))
989 (accept-process-output))
990
991 (defun gnugo-cleanup ()
992 (when (gnugo-board-buffer-p)
993 (unless (zerop (buffer-size))
994 (message "Thank you for playing GNU Go."))
995 (mapc (lambda (sym)
996 (setplist sym nil) ; "...is next to fordliness." --Huxley
997 (unintern sym))
998 (append (gnugo-get :all-yy)
999 (mapcar 'gnugo-f
1000 '(anim
1001 tpad
1002 gpad
1003 gspc
1004 lpad
1005 rpad
1006 ispc))))
1007 (setq gnugo-state nil)))
1008
1009 (defun gnugo-position ()
1010 (or (get-text-property (point) 'gnugo-position)
1011 (user-error "Not a proper position point")))
1012
1013 (defun gnugo-move ()
1014 "Make a move on the GNUGO Board buffer.
1015 The position is computed from current point.
1016 Signal error if done out-of-turn or if game-over.
1017 To start a game try M-x gnugo."
1018 (interactive)
1019 (gnugo-gate t)
1020 (let* ((buf (current-buffer))
1021 (pos (gnugo-position))
1022 (move (format "play %s %s" (gnugo-get :user-color) pos))
1023 (accept (cdr (gnugo-synchronous-send/return move))))
1024 (unless (= ?= (aref accept 0))
1025 (user-error "%s" accept))
1026 (gnugo-push-move t pos) ; value always nil for non-pass move
1027 (let (inhibit-gnugo-refresh)
1028 (run-hooks 'gnugo-post-move-hook)
1029 (unless inhibit-gnugo-refresh
1030 (with-current-buffer buf
1031 (gnugo-refresh))))
1032 (with-current-buffer buf
1033 (gnugo-get-move (gnugo-get :gnugo-color)))))
1034
1035 (defun gnugo-mouse-move (e)
1036 "Do `gnugo-move' at mouse location."
1037 (interactive "@e")
1038 (mouse-set-point e)
1039 (when (looking-at "[.+]")
1040 (gnugo-move)))
1041
1042 (defun gnugo-pass ()
1043 "Make a pass on the GNUGO Board buffer.
1044 Signal error if done out-of-turn or if game-over.
1045 To start a game try M-x gnugo."
1046 (interactive)
1047 (gnugo-gate t)
1048 (let ((accept (cdr (gnugo-synchronous-send/return
1049 (format "play %s PASS" (gnugo-get :user-color))))))
1050 (unless (= ?= (aref accept 0))
1051 (user-error "%s" accept)))
1052 (let ((donep (gnugo-push-move t "PASS"))
1053 (buf (current-buffer)))
1054 (let (inhibit-gnugo-refresh)
1055 (run-hooks 'gnugo-post-move-hook)
1056 (unless inhibit-gnugo-refresh
1057 (with-current-buffer buf
1058 (gnugo-refresh))))
1059 (unless donep
1060 (with-current-buffer buf
1061 (gnugo-get-move (gnugo-get :gnugo-color))))))
1062
1063 (defun gnugo-mouse-pass (e)
1064 "Do `gnugo-pass' at mouse location."
1065 (interactive "@e")
1066 (mouse-set-point e)
1067 (gnugo-pass))
1068
1069 (defun gnugo-resign ()
1070 (interactive)
1071 (gnugo-gate t)
1072 (if (not (y-or-n-p "Resign? "))
1073 (message "(not resigning)")
1074 (gnugo-push-move t "resign")
1075 (gnugo-refresh)))
1076
1077 (defun gnugo-animate-group (command)
1078 (message "Computing %s ..." command)
1079 (let* ((pos (gnugo-position))
1080 (orig-b-m-p (buffer-modified-p))
1081 (stones (if (memq (char-after) '(?X ?O))
1082 (gnugo-lsquery "%s %s" command pos)
1083 (user-error "No stone at %s" pos))))
1084 (message "Computing %s ... %s in group." command (length stones))
1085 (setplist (gnugo-f 'anim) nil)
1086 (let* ((spec (let ((spec (split-string gnugo-animation-string "" t)))
1087 (cond ((gnugo-get :display-using-images)
1088 (let* ((yin (get-text-property (point) 'gnugo-yin))
1089 (yang (gnugo-yang (char-after)))
1090 (up (get (gnugo-yy yin yang t) 'display))
1091 (dn (get (gnugo-yy yin yang) 'display)))
1092 (mapcar (lambda (n)
1093 (if (cl-oddp n)
1094 dn up))
1095 (number-sequence 1 (length spec)))))
1096 (t spec))))
1097 (cell (list spec))
1098 (ovs (save-excursion
1099 (mapcar (lambda (pos)
1100 (gnugo-goto-pos pos)
1101 (let* ((p (point))
1102 (ov (make-overlay p (1+ p))))
1103 (overlay-put ov 'category (gnugo-f 'anim))
1104 (overlay-put ov 'priority most-positive-fixnum)
1105 ov))
1106 stones))))
1107 (setplist (gnugo-f 'anim) (cons 'display cell))
1108 (while (and (cdr spec) ; let last linger lest levity lost
1109 (sit-for 0.08675309)) ; jenny jenny i got your number...
1110 (setcar cell (setq spec (cdr spec)))
1111 ;; Force redisplay of overlays.
1112 (set-buffer-modified-p orig-b-m-p))
1113 (sit-for 5)
1114 (mapc 'delete-overlay ovs)
1115 t)))
1116
1117 (defun gnugo-display-group-data (command buffer-name)
1118 (message "Computing %s ..." command)
1119 (let ((data (cdr (gnugo-synchronous-send/return
1120 (format "%s %s" command (gnugo-position))))))
1121 (switch-to-buffer buffer-name)
1122 (erase-buffer)
1123 (insert data))
1124 (message "Computing %s ... done." command))
1125
1126 (defun gnugo-worm-stones ()
1127 "In the GNUGO Board buffer, animate \"worm\" at current position.
1128 Signal error if done out-of-turn or if game-over.
1129 See variable `gnugo-animation-string' for customization."
1130 (interactive)
1131 (gnugo-gate)
1132 (gnugo-animate-group "worm_stones"))
1133
1134 (defun gnugo-worm-data ()
1135 "Display in another buffer data from \"worm\" at current position.
1136 Signal error if done out-of-turn or if game-over."
1137 (interactive)
1138 (gnugo-gate)
1139 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1140
1141 (defun gnugo-dragon-stones ()
1142 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1143 Signal error if done out-of-turn or if game-over.
1144 See variable `gnugo-animation-string' for customization."
1145 (interactive)
1146 (gnugo-gate)
1147 (gnugo-animate-group "dragon_stones"))
1148
1149 (defun gnugo-dragon-data ()
1150 "Display in another buffer data from \"dragon\" at current position.
1151 Signal error if done out-of-turn or if game-over."
1152 (interactive)
1153 (gnugo-gate)
1154 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1155
1156 (defun gnugo-toggle-dead-group ()
1157 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1158 The group is selected from current position (point). Signal error if
1159 not in game-over or if there is no group at that position.
1160
1161 In the context of GNU Go, a group is called a \"dragon\" and may be
1162 composed of more than one \"worm\" (set of directly-connected stones).
1163 It is unclear to the gnugo.el author whether or not GNU Go supports
1164 - considering worms as groups in their own right; and
1165 - toggling group aliveness via GTP.
1166 Due to these uncertainties, this command is only half complete; the
1167 changes you may see in Emacs are not propagated to the gnugo subprocess.
1168 Thus, GTP commands like `final_score' may give unexpected results.
1169
1170 If you are able to expose via GTP `change_dragon_status' in utils.c,
1171 you may consider modifying the `gnugo-toggle-dead-group' source code
1172 to enable full functionality."
1173 (interactive)
1174 (let ((game-over (or (gnugo-get :game-over)
1175 (user-error "Sorry, game still in play")))
1176 (group (or (get-text-property (point) 'group)
1177 (user-error "No stone at that position")))
1178 (now (current-time)))
1179 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1180 (cadr now)))
1181 (let ((live (assq 'live game-over))
1182 (dead (assq 'dead game-over))
1183 bef now)
1184 (if (memq group live)
1185 (setq bef live now dead)
1186 (setq bef dead now live))
1187 (setcdr bef (delq group (cdr bef)))
1188 (setcdr now (cons group (cdr now)))
1189 ;; disabled permanently -- too wrong
1190 (when nil
1191 (cl-labels
1192 ((populate (group)
1193 (let ((color (caar group)))
1194 (dolist (stone (cdr group))
1195 (gnugo-query "play %s %s" color stone)))))
1196 (if (eq now live)
1197 (populate group)
1198 ;; drastic (and wrong -- clobbers capture info, etc)
1199 (gnugo-query "clear_board")
1200 (mapc #'populate (cdr live)))))
1201 ;; here is the desired interface (to be enabled Some Day)
1202 (when nil
1203 (gnugo-query "change_dragon_status %s %s"
1204 (cadr group) (if (eq now live)
1205 'alive
1206 'dead)))))
1207 (save-excursion
1208 (gnugo-refresh)))
1209
1210 (defun gnugo-estimate-score ()
1211 "Display estimated score of a game of GNU Go.
1212 Output includes number of stones on the board and number of stones
1213 captured by each player, and the estimate of who has the advantage (and
1214 by how many stones)."
1215 (interactive)
1216 (message "Est.score ...")
1217 (let ((black (length (gnugo-lsquery "list_stones black")))
1218 (white (length (gnugo-lsquery "list_stones white")))
1219 (black-captures (gnugo-query "captures black"))
1220 (white-captures (gnugo-query "captures white"))
1221 (est (gnugo-query "estimate_score")))
1222 ;; might as well update this
1223 (gnugo-put :black-captures black-captures)
1224 (gnugo-put :white-captures white-captures)
1225 (message "Est.score ... B %s %s | W %s %s | %s"
1226 black black-captures white white-captures est)))
1227
1228 (defun gnugo-write-sgf-file (filename)
1229 "Save the game history to FILENAME (even if unfinished).
1230 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1231 (interactive "FWrite game as SGF file: ")
1232 (when (and (file-exists-p filename)
1233 (not (y-or-n-p "File exists. Continue? ")))
1234 (user-error "Not writing %s" filename))
1235 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1236 (set-buffer-modified-p nil))
1237
1238 (defun gnugo-read-sgf-file (filename)
1239 "Load the first game tree from FILENAME, a file in SGF format."
1240 (interactive "fSGF file to load: ")
1241 (when (file-directory-p filename)
1242 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1243 (let (ans play wait samep coll)
1244 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1245 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1246 (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1247 (format "loadsgf %s"
1248 (expand-file-name filename)))))
1249 0))
1250 (user-error "%s" ans))
1251 (setq play (substring ans 2)
1252 wait (gnugo-other play)
1253 samep (string= (gnugo-get :user-color) play))
1254 (gnugo-put :last-mover wait)
1255 (unless samep
1256 (gnugo-put :gnugo-color wait)
1257 (gnugo-put :user-color play))
1258 (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1259 (gnugo-put :sgf-gametree
1260 (nth (let ((n (length coll)))
1261 ;; This is better:
1262 ;; (if (= 1 n)
1263 ;; 0
1264 ;; (let* ((q (format "Which game? (1-%d)" n))
1265 ;; (choice (1- (read-number q 1))))
1266 ;; (if (and (< -1 choice) (< choice n))
1267 ;; choice
1268 ;; (message "(Selecting the first game)")
1269 ;; 0)))
1270 ;; but this is what we use (for now) to accomodate
1271 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1272 (unless (= 1 n)
1273 (message "(Selecting the first game)"))
1274 0)
1275 coll))
1276 (let* ((tree (gnugo-get :sgf-gametree))
1277 (loc tree)
1278 (count 0)
1279 mem node play game-over)
1280 (while (setq node (car loc))
1281 (when (setq play (or (assq :B node)
1282 (assq :W node)))
1283 ;; SGF[4] allows "" to mean PASS. For now,
1284 ;; we normalize here instead of at the lower layer.
1285 (when (string= "" (cdr play))
1286 (setcdr play "tt"))
1287 (incf count)
1288 (push loc mem))
1289 (setq loc (cdr loc)))
1290 (gnugo-put :game-over
1291 (setq game-over
1292 (or (cdr (assq :RE (car tree)))
1293 (and (cdr mem)
1294 (equal '("tt" "tt")
1295 (let ((order (if (string= "black" wait)
1296 '(:B :W)
1297 '(:W :B))))
1298 (mapcar (lambda (pk)
1299 (cdr (assq (funcall pk order)
1300 (car (funcall pk mem)))))
1301 '(car cadr))))
1302 'two-passes))))
1303 (gnugo-put :monkey
1304 (vector (or (car mem) (gnugo-get :sgf-gametree))
1305 mem
1306 count))
1307 (when (and game-over
1308 ;; (maybe) todo: user var to inhibit (can be slow)
1309 t)
1310 (gnugo-close-game nil game-over)))
1311 (gnugo-refresh t)
1312 (set-buffer-modified-p nil)
1313 (message "GNU Go %splays as %s, you as %s (%s)"
1314 (if samep "" "now ")
1315 wait play (if samep
1316 "as before"
1317 "NOTE: this is a switch!"))))
1318
1319 (defun gnugo-magic-undo (spec &optional noalt)
1320 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1321 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1322 check that the position is occupied by a stone of the user's color,
1323 and if so, remove moves from the history until that position is clear.
1324 If SPEC is a positive number, remove exactly that many moves from the
1325 history, signaling an error if the history is exhausted before finishing.
1326 If SPEC is not recognized, signal \"bad spec\" error.
1327
1328 Refresh the board for each move undone. If (in the case where SPEC is
1329 a number) after finishing, the color to play is not the user's color,
1330 schedule a move by GNU Go.
1331
1332 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1333 turn to play. Optional second arg NOALT non-nil inhibits this."
1334 (gnugo-gate)
1335 (let* ((n 0)
1336 (monkey (gnugo-get :monkey))
1337 (mem (aref monkey 1))
1338 (count (aref monkey 2))
1339 done ans)
1340 (cond ((and (numberp spec) (cl-plusp spec))
1341 (setq n spec done (lambda () (zerop n))))
1342 ((string-match "^[a-z]" spec)
1343 (let ((pos (upcase spec)))
1344 (setq done `(lambda ()
1345 (gnugo-goto-pos ,pos)
1346 (memq (char-after) '(?. ?+))))
1347 (when (funcall done)
1348 (user-error "%s already clear" pos))
1349 (let ((u (gnugo-get :user-color)))
1350 (when (= (save-excursion
1351 (gnugo-goto-pos pos)
1352 (char-after))
1353 (if (string= "black" u)
1354 ?O
1355 ?X))
1356 (user-error "%s not occupied by %s" pos u)))))
1357 (t (user-error "Bad spec: %S" spec)))
1358 (when (gnugo-get :game-over)
1359 (gnugo--unclose-game))
1360 (while (not (funcall done))
1361 (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1362 (unless (= ?= (aref ans 0))
1363 (user-error "%s" ans))
1364 (aset monkey 2 (decf count))
1365 (aset monkey 1 (setq mem (cdr mem)))
1366 (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1367 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1368 (gnugo-merge-showboard-results) ; all
1369 (gnugo-refresh) ; this
1370 (decf n) ; is
1371 (redisplay))) ; eye candy
1372 (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1373
1374 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1375 (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1376 ubpos
1377 (gnugo-get :center-position)))
1378 (gnugo-refresh t)
1379 ;; preserve restricted-functionality semantics (todo: remove restriction)
1380 (setcdr (aref (gnugo-get :monkey) 0) nil)
1381 (when (and ulastp (not noalt))
1382 (gnugo-get-move (gnugo-get :gnugo-color)))))
1383
1384 (defun gnugo-undo-one-move ()
1385 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1386 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1387 See also `gnugo-undo-two-moves'."
1388 (interactive)
1389 (gnugo-gate)
1390 (gnugo-magic-undo 1 t))
1391
1392 (defun gnugo-undo-two-moves ()
1393 "Undo a pair of moves (GNU Go's and yours).
1394 However, if you are the last mover, undo only one move.
1395 Regardless, after undoing, it is your turn to play again."
1396 (interactive)
1397 (gnugo-gate)
1398 (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1399 (gnugo-get :last-mover))
1400 1
1401 2)))
1402
1403 (defun gnugo-display-final-score ()
1404 "Display final score and other info in another buffer (when game over).
1405 If the game is still ongoing, Emacs asks if you wish to stop play (by
1406 making sure two \"pass\" moves are played consecutively, if necessary).
1407 Also, add the `:RE' SGF property to the root node of the game tree."
1408 (interactive)
1409 (unless (or (gnugo-get :game-over)
1410 (and (not (gnugo-get :waitingp))
1411 (y-or-n-p "Game still in play. Stop play now? ")))
1412 (user-error "Sorry, game still in play"))
1413 (unless (gnugo-get :game-over)
1414 (cl-labels
1415 ((pass (userp)
1416 (message "Playing PASS for %s ..."
1417 (gnugo-get (if userp :user-color :gnugo-color)))
1418 (sit-for 1)
1419 (gnugo-push-move userp "PASS")))
1420 (unless (pass t)
1421 (pass nil)))
1422 (gnugo-refresh)
1423 (sit-for 3))
1424 (let ((b= " Black = ")
1425 (w= " White = ")
1426 (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1427 (event (and node (cdr (assq :EV node)))))
1428 (and event (string= "resignation" event)
1429 (if (assq :B node) "black" "white"))))
1430 blurb result)
1431 (if res
1432 (setq blurb (list
1433 (format "%s wins.\n"
1434 (substring (if (= ?b (aref res 0)) w= b=)
1435 3 8))
1436 "The game is over.\n"
1437 (format "Resignation by %s.\n" res))
1438 result (concat (upcase (substring (gnugo-other res) 0 1))
1439 "+Resign"))
1440 (message "Computing final score ...")
1441 (let* ((live (cdr (assq 'live (gnugo-get :game-over))))
1442 (dead (cdr (assq 'dead (gnugo-get :game-over))))
1443 (seed (gnugo-get :scoring-seed))
1444 (terr-q (format "final_status_list %%s_territory %d" seed))
1445 (terr "territory")
1446 (capt "captures")
1447 (b-terr (length (gnugo-lsquery terr-q "black")))
1448 (w-terr (length (gnugo-lsquery terr-q "white")))
1449 (b-capt (string-to-number (gnugo-get :black-captures)))
1450 (w-capt (string-to-number (gnugo-get :white-captures)))
1451 (komi (gnugo-treeroot :KM)))
1452 (setq blurb (list "The game is over. Final score:\n")
1453 result (gnugo-query "final_score %d" seed))
1454 (cond ((string= "Chinese" (gnugo-treeroot :RU))
1455 (dolist (group live)
1456 (let ((count (length (cdr group))))
1457 (if (string= "black" (caar group))
1458 (setq b-terr (+ b-terr count))
1459 (setq w-terr (+ w-terr count)))))
1460 (dolist (group dead)
1461 (let* ((color (caar group))
1462 (count (length (cdr group))))
1463 (if (string= "black" color)
1464 (setq w-terr (+ count w-terr))
1465 (setq b-terr (+ count b-terr)))))
1466 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1467 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1468 w-terr terr komi 'komi (+ w-terr komi))
1469 blurb))
1470 (t
1471 (dolist (group dead)
1472 (let* ((color (caar group))
1473 (adjust (* 2 (length (cdr group)))))
1474 (if (string= "black" color)
1475 (setq w-terr (+ adjust w-terr))
1476 (setq b-terr (+ adjust b-terr)))))
1477 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1478 b-terr terr
1479 b-capt capt
1480 (+ b-terr b-capt))
1481 blurb)
1482 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1483 w-terr terr
1484 w-capt capt
1485 komi 'komi
1486 (+ w-terr w-capt komi))
1487 blurb)))
1488 (push (if (string= "0" result)
1489 "The game is a draw.\n"
1490 (format "%s wins by %s.\n"
1491 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1492 (substring result 2)))
1493 blurb)
1494 (message "Computing final score ... done")))
1495 ;; extra info
1496 (when (gnugo-get :game-end-time)
1497 (push "\n" blurb)
1498 (dolist (spec '(("Game start" . :game-start-time)
1499 (" end" . :game-end-time)))
1500 (push (format-time-string
1501 (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1502 (gnugo-get (cdr spec)))
1503 blurb)))
1504 (setq blurb (apply 'concat (nreverse blurb)))
1505 (let* ((root (car (gnugo-get :sgf-gametree)))
1506 (cur (assq :RE root)))
1507 (if cur
1508 (setcdr cur result)
1509 (setcdr (last root) (list (cons :RE result)))))
1510 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1511 (erase-buffer)
1512 (insert blurb)))
1513
1514 (defun gnugo-quit ()
1515 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1516 If the game is not over, ask for confirmation first."
1517 (interactive)
1518 (if (or (gnugo-get :game-over)
1519 (y-or-n-p "Quit? "))
1520 (kill-buffer nil)
1521 (message "(not quitting)")))
1522
1523 (defun gnugo-leave-me-alone ()
1524 "Kill the current buffer unconditionally."
1525 (interactive)
1526 (kill-buffer nil))
1527
1528 (defun gnugo-fancy-undo (count)
1529 "Rewind the game tree in various ways.
1530 Prefix arg COUNT means to undo that many moves.
1531 Otherwise, undo repeatedly up to and including the move
1532 which placed the stone at point."
1533 (interactive "P")
1534 (gnugo-magic-undo
1535 ;; TODO: Move this into `gnugo-magic-undo' proper.
1536 (cond ((numberp count) count)
1537 ((consp count) (car count))
1538 (t (gnugo-position)))))
1539
1540 (defun gnugo-toggle-image-display-command () ; ugh
1541 "Toggle use of images to display the board, then refresh."
1542 (interactive)
1543 (gnugo-toggle-image-display)
1544 (save-excursion (gnugo-refresh)))
1545
1546 (defun gnugo-describe-position ()
1547 "Display the board position under cursor in the echo area."
1548 (interactive)
1549 (message "%s" (gnugo-position)))
1550
1551 ;;;---------------------------------------------------------------------------
1552 ;;; Command properties and gnugo-command
1553
1554 ;; GTP commands entered by the user are never issued directly to GNU Go;
1555 ;; instead, their behavior and output are controlled by the property
1556 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1557 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1558 ;;
1559 ;; :full -- completely interpret the command string; the value is a
1560 ;; func that takes the list of words derived from splitting the
1561 ;; command string (minus the command) and handles everything.
1562 ;;
1563 ;; :output -- either a keyword specifying the preferred output method:
1564 ;; :message -- show output in minibuffer
1565 ;; :discard -- sometimes you just don't care;
1566 ;; or a function that takes one arg, the output string, and
1567 ;; handles it completely. default is to switch to buffer
1568 ;; "*gnugo command output*" if the output has a newline,
1569 ;; otherwise use `message'.
1570 ;;
1571 ;; :post-thunk -- run after output processing (at the very end).
1572
1573 (defun gnugo-command (command)
1574 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1575 Output and Emacs behavior depend on which command is given (some
1576 commands are handled completely by Emacs w/o using the subprocess;
1577 some commands have their output displayed in specially prepared
1578 buffers or in the echo area; some commands are instrumented to do
1579 gnugo.el-specific housekeeping).
1580
1581 For example, for the command \"help\", Emacs visits the
1582 GTP command reference info page.
1583
1584 NOTE: At this time, GTP command handling specification is still
1585 incomplete. Thus, some commands WILL confuse gnugo.el."
1586 (interactive "sCommand: ")
1587 (if (string= "" command)
1588 (message "(no command given)")
1589 (let* ((split (split-string command))
1590 (cmd (intern (car split)))
1591 (spec (get cmd :gnugo-gtp-command-spec))
1592 (full (plist-get spec :full)))
1593 (if full
1594 (funcall full (cdr split))
1595 (message "Doing %s ..." command)
1596 (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1597 (where (plist-get spec :output)))
1598 (if (string-match "unknown.command" ans)
1599 (message "%s" ans)
1600 (cond ((functionp where) (funcall where ans))
1601 ((eq :discard where) (message ""))
1602 ((or (eq :message where)
1603 (not (string-match "\n" ans)))
1604 (message "%s" ans))
1605 (t (switch-to-buffer "*gnugo command output*")
1606 (erase-buffer)
1607 (insert ans)
1608 (message "Doing %s ... done." command)))
1609 (let ((thunk (plist-get spec :post-thunk)))
1610 (when thunk (funcall thunk)))))))))
1611
1612 ;;;---------------------------------------------------------------------------
1613 ;;; Major mode for interacting with a GNUGO subprocess
1614
1615 (put 'gnugo-board-mode 'mode-class 'special)
1616 (defun gnugo-board-mode ()
1617 "Major mode for playing GNU Go.
1618 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1619 In this mode, keys do not self insert. Default keybindings:
1620
1621 ? View this help.
1622
1623 RET or SPC Run `gnugo-move'.
1624
1625 q or Q Quit (the latter without confirmation).
1626
1627 R Resign.
1628
1629 u Run `gnugo-undo-two-moves'.
1630
1631 U Pass to `gnugo-magic-undo' either the board position
1632 at point (if no prefix arg), or the prefix arg converted
1633 to a number. E.g., to undo 16 moves: `C-u C-u U' (see
1634 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1635
1636 C-l Run `gnugo-refresh'.
1637
1638 _ or M-_ Bury the Board buffer (when the boss is near).
1639
1640 P Run `gnugo-pass'.
1641
1642 i Toggle display using XPM images (if supported).
1643
1644 w Run `gnugo-worm-stones'.
1645 d Run `gnugo-dragon-stones'.
1646
1647 W Run `gnugo-worm-data'.
1648 D Run `gnugo-dragon-data'.
1649
1650 t Run `gnugo-toggle-dead-group'.
1651
1652 ! Run `gnugo-estimate-score'.
1653
1654 : or ; Run `gnugo-command' (for GTP commands to GNU Go).
1655
1656 = Display board position under point (if valid).
1657
1658 h Run `gnugo-move-history'.
1659
1660 F Run `gnugo-display-final-score'.
1661
1662 s Run `gnugo-write-sgf-file'.
1663 or C-x C-w
1664 or C-x C-s
1665
1666 l Run `gnugo-read-sgf-file'."
1667 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1668 (buffer-disable-undo) ; todo: undo undo undoing
1669 (kill-all-local-variables)
1670 (setq truncate-lines t)
1671 (use-local-map gnugo-board-mode-map)
1672 (set (make-local-variable 'font-lock-defaults)
1673 '(gnugo-font-lock-keywords t))
1674 (setq major-mode 'gnugo-board-mode)
1675 (setq mode-name "GNUGO Board")
1676 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1677 (set (make-local-variable 'gnugo-state)
1678 (make-hash-table :size (1- 42) :test 'eq))
1679 (add-to-invisibility-spec :nogrid)
1680 (mapc (lambda (prop)
1681 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1682 '(:game-over ; move latter to func `gnugo'
1683 :waitingp
1684 :last-waiting
1685 :black-captures
1686 :white-captures
1687 :mode-line
1688 :mode-line-form
1689 :display-using-images
1690 :xpms
1691 :local-xpms
1692 :all-yy))
1693 (let ((name (if (string-match "[ ]" gnugo-program)
1694 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1695 (o (substring gnugo-program (match-end 0)))
1696 (h (or (car gnugo-option-history) "")))
1697 (when (string-match "--mode" o)
1698 (user-error "Found \"--mode\" in `gnugo-program'"))
1699 (when (and o (cl-plusp (length o))
1700 h (cl-plusp (length o))
1701 (or (< (length h) (length o))
1702 (not (string= (substring h 0 (length o))
1703 o))))
1704 (push (concat o " " h) gnugo-option-history))
1705 p)
1706 gnugo-program))
1707 (args (read-string "GNU Go options: "
1708 (car gnugo-option-history)
1709 'gnugo-option-history))
1710 (rules "Japanese")
1711 board-size user-color handicap komi minus-l infile)
1712 (dolist (x '((board-size 19 "--boardsize")
1713 (user-color "black" "--color" "\\(black\\|white\\)")
1714 (handicap 0 "--handicap")
1715 (komi 0.0 "--komi")
1716 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1717 (infile nil "--infile" "[ ]*[^ ]+")))
1718 (destructuring-bind (var default opt &optional rx) x
1719 (set var
1720 (or (when (string-match opt args)
1721 (let ((start (match-end 0)) s)
1722 (string-match (or rx "[0-9.]+") args start)
1723 (setq s (match-string 0 args))
1724 (if rx s (string-to-number s))))
1725 default))))
1726 (gnugo-put :user-color user-color)
1727 (when (string-match "--chinese-rules" args)
1728 (setq rules "Chinese"))
1729 (let ((proc-args (split-string args)))
1730 (gnugo-put :proc-args proc-args)
1731 (gnugo-put :proc (apply 'start-process "gnugo" nil name
1732 "--mode" "gtp" "--quiet"
1733 proc-args)))
1734 ;; Emacs is too protective sometimes, blech.
1735 (set-process-query-on-exit-flag (gnugo-get :proc) nil)
1736 (when (or minus-l infile)
1737 (mapc (lambda (x)
1738 (apply (lambda (prop q)
1739 (set prop (string-to-number (gnugo-query q))))
1740 x))
1741 '((board-size "query_boardsize")
1742 (komi "get_komi")
1743 (handicap "get_handicap"))))
1744 (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1745 (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1746 (gnugo-put :highlight-last-move-spec
1747 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1748 (gnugo-put :lparen-ov (make-overlay 1 1))
1749 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1750 (overlay-put ov 'display ")")
1751 ov))
1752 (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1753 (let ((tree (gnugo-get :sgf-gametree)))
1754 (gnugo-put :sgf-collection (list tree))
1755 (gnugo-put :monkey (vector tree nil 0)))
1756 (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1757 (mapc (lambda (x) (apply 'gnugo-note x))
1758 `((:SZ ,board-size)
1759 (:DT ,(format-time-string "%Y-%m-%d"))
1760 (:RU ,rules)
1761 (:AP ("gnugo.el" . ,gnugo-version))
1762 (:KM ,komi)
1763 (,(if g-blackp :PW :PB) ,(user-full-name))
1764 (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1765 (gnugo-query "version")))
1766 ,@(when (not (zerop handicap))
1767 `((:HA ,handicap)
1768 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1769 nil t)))))))
1770 (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1771 (set-process-buffer (gnugo-get :proc) (current-buffer))
1772 (gnugo-put :waiting-start (current-time))
1773 (gnugo-put :hmul 1)
1774 (gnugo-put :wmul 1)
1775 (run-hooks 'gnugo-board-mode-hook)
1776 (gnugo-refresh t))
1777
1778 ;;;---------------------------------------------------------------------------
1779 ;;; Entry point
1780
1781 ;;;###autoload
1782 (defun gnugo (&optional new-game)
1783 "Run gnugo in a buffer, or resume a game in progress.
1784 Prefix arg means skip the game-in-progress check and start a new
1785 game straight away.
1786
1787 You are queried for additional command-line options (Emacs supplies
1788 \"--mode gtp --quiet\" automatically). Here is a list of options
1789 that gnugo.el understands and handles specially:
1790
1791 --boardsize num Set the board size to use (5--19)
1792 --color <color> Choose your color ('black' or 'white')
1793 --handicap <num> Set the number of handicap stones (0--9)
1794
1795 If there is already a game in progress you may resume it instead of
1796 starting a new one. See `gnugo-board-mode' documentation for more info."
1797 (interactive "P")
1798 (let* ((all (let (acc)
1799 (dolist (buf (buffer-list))
1800 (when (gnugo-board-buffer-p buf)
1801 (push (cons (buffer-name buf) buf) acc)))
1802 acc))
1803 (n (length all)))
1804 (if (and (not new-game)
1805 (cl-plusp n)
1806 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1807 (if (= 1 n) "" "s"))))
1808 ;; resume
1809 (switch-to-buffer
1810 (cdr (if (= 1 n)
1811 (car all)
1812 (let ((sel (completing-read "Which one? " all nil t)))
1813 (if (string= "" sel)
1814 (car all)
1815 (assoc sel all))))))
1816 ;; set up a new board
1817 (gnugo-board-mode)
1818 (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1819 (gnugo-goto-pos (format "A%d" half))
1820 (forward-char (* 2 (1- half)))
1821 (gnugo-put :last-user-bpos
1822 (gnugo-put :center-position
1823 (get-text-property (point) 'gnugo-position))))
1824 ;; first move
1825 (gnugo-put :game-start-time (current-time))
1826 (let ((g (gnugo-get :gnugo-color))
1827 (n (or (gnugo-treeroot :HA) 0))
1828 (u (gnugo-get :user-color)))
1829 (gnugo-put :last-mover g)
1830 (when (or (and (string= "black" u) (< 1 n))
1831 (and (string= "black" g) (< n 2)))
1832 (gnugo-put :last-mover u)
1833 (gnugo-refresh t)
1834 (gnugo-get-move g))))))
1835
1836 ;;;---------------------------------------------------------------------------
1837 ;;; Load-time actions
1838
1839 (unless gnugo-board-mode-map
1840 (setq gnugo-board-mode-map (make-sparse-keymap))
1841 (suppress-keymap gnugo-board-mode-map)
1842 (mapc (lambda (pair)
1843 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1844 '(("?" . describe-mode)
1845 ("\C-m" . gnugo-move)
1846 (" " . gnugo-move)
1847 ("P" . gnugo-pass)
1848 ("R" . gnugo-resign)
1849 ("q" . gnugo-quit)
1850 ("Q" . gnugo-leave-me-alone)
1851 ("U" . gnugo-fancy-undo)
1852 ("u" . gnugo-undo-two-moves)
1853 ("\C-l" . gnugo-refresh)
1854 ("\M-_" . bury-buffer)
1855 ("_" . bury-buffer)
1856 ("h" . gnugo-move-history)
1857 ("i" . gnugo-toggle-image-display-command)
1858 ("w" . gnugo-worm-stones)
1859 ("W" . gnugo-worm-data)
1860 ("d" . gnugo-dragon-stones)
1861 ("D" . gnugo-dragon-data)
1862 ("t" . gnugo-toggle-dead-group)
1863 ("g" . gnugo-toggle-grid)
1864 ("!" . gnugo-estimate-score)
1865 (":" . gnugo-command)
1866 (";" . gnugo-command)
1867 ("=" . gnugo-describe-position)
1868 ("s" . gnugo-write-sgf-file)
1869 ("\C-x\C-s" . gnugo-write-sgf-file)
1870 ("\C-x\C-w" . gnugo-write-sgf-file)
1871 ("l" . gnugo-read-sgf-file)
1872 ("F" . gnugo-display-final-score)
1873 ;; mouse
1874 ([(down-mouse-1)] . gnugo-mouse-move)
1875 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1876 ([(down-mouse-3)] . gnugo-mouse-pass)
1877 ;; delving into the curiosities
1878 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1879
1880 (unless (get 'help :gnugo-gtp-command-spec)
1881 (cl-labels
1882 ((sget (x) (get x :gnugo-gtp-command-spec))
1883 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1884 (plist-put (sget cmd) prop val)))
1885 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1886 (let ((ls props))
1887 (while ls
1888 (jam cmd (car ls) (cadr ls))
1889 (setq ls (cddr ls)))))))
1890
1891 (defgtp 'help :full
1892 (lambda (sel)
1893 (info "(gnugo)GTP command reference")
1894 (when sel (setq sel (intern (car sel))))
1895 (let (buffer-read-only pad cur spec output found)
1896 (cl-labels
1897 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1898 (goto-char (point-min))
1899 (save-excursion
1900 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1901 (point-max) t)
1902 (unless pad
1903 (setq pad (make-string (- (match-beginning 1)
1904 (match-beginning 0))
1905 32)))
1906 (when (plist-get
1907 (setq spec
1908 (get (setq cur (intern (match-string 1)))
1909 :gnugo-gtp-command-spec))
1910 :full)
1911 (note "handles this command completely"))
1912 (when (setq output (plist-get spec :output))
1913 (cond ((functionp output)
1914 (note "handles the output specially"))
1915 ((eq :discard output)
1916 (note "discards the output"))
1917 ((eq :message output)
1918 (note "displays the output in the echo area"))))
1919 (when (eq sel cur)
1920 (setq found (match-beginning 0))))))
1921 (cond (found (goto-char found))
1922 ((not sel))
1923 (t (message "(no such command: %s)" sel))))))
1924
1925 (defgtp 'final_score :full
1926 (lambda (sel) (gnugo-display-final-score)))
1927
1928 (defgtp '(boardsize
1929 clear_board
1930 fixed_handicap)
1931 :output :discard
1932 :post-thunk (lambda ()
1933 (gnugo--unclose-game)
1934 (gnugo-put :last-mover nil)
1935 (gnugo-refresh t)))
1936
1937 (defgtp 'loadsgf :full
1938 (lambda (sel) (gnugo-read-sgf-file (car sel))))
1939
1940 (defgtp '(undo gg-undo) :full
1941 (lambda (sel) (gnugo-magic-undo
1942 (let (n)
1943 (cond ((not sel) 1)
1944 ((cl-plusp (setq n (string-to-number (car sel)))) n)
1945 (t (car sel)))))))))
1946
1947 (provide 'gnugo)
1948
1949 \f
1950 ;;;---------------------------------------------------------------------------
1951 ;;; The remainder of this file defines a simplified SGF-handling library.
1952 ;;; When/if it should start to attain generality, it should be split off into
1953 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
1954 ;;; "gnugo/" prefix.
1955
1956 (defconst gnugo/sgf-*r4-properties*
1957 '((AB "Add Black" setup list stone)
1958 (AE "Add Empty" game list point)
1959 (AN "Annotation" game simpletext)
1960 (AP "Application" root (simpletext . simpletext))
1961 (AR "Arrow" - list (point . point))
1962 (AS "Who adds stones" - simpletext) ; (LOA)
1963 (AW "Add White" setup list stone)
1964 (B "Black" move move)
1965 (BL "Black time left" move real)
1966 (BM "Bad move" move double)
1967 (BR "Black rank" game simpletext)
1968 (BT "Black team" game simpletext)
1969 (C "Comment" - text)
1970 (CA "Charset" root simpletext)
1971 (CP "Copyright" game simpletext)
1972 (CR "Circle" - list point)
1973 (DD "Dim points" - elist point) ; (inherit)
1974 (DM "Even position" - double)
1975 (DO "Doubtful" move none)
1976 (DT "Date" game simpletext)
1977 (EV "Event" game simpletext)
1978 (FF "Fileformat" root [number (1 . 4)])
1979 (FG "Figure" - (or none (number . simpletext)))
1980 (GB "Good for Black" - double)
1981 (GC "Game comment" game text)
1982 (GM "Game" root [number (1 . 20)])
1983 (GN "Game name" game simpletext)
1984 (GW "Good for White" - double)
1985 (HA "Handicap" game number) ; (Go)
1986 (HO "Hotspot" - double)
1987 (IP "Initial pos." game simpletext) ; (LOA)
1988 (IT "Interesting" move none)
1989 (IY "Invert Y-axis" game simpletext) ; (LOA)
1990 (KM "Komi" game real) ; (Go)
1991 (KO "Ko" move none)
1992 (LB "Label" - list (point . simpletext))
1993 (LN "Line" - list (point . point))
1994 (MA "Mark" - list point)
1995 (MN "set move number" move number)
1996 (N "Nodename" - simpletext)
1997 (OB "OtStones Black" move number)
1998 (ON "Opening" game text)
1999 (OT "Overtime" game simpletext)
2000 (OW "OtStones White" move number)
2001 (PB "Player Black" game simpletext)
2002 (PC "Place" game simpletext)
2003 (PL "Player to play" setup color)
2004 (PM "Print move mode" - number) ; (inherit)
2005 (PW "Player White" game simpletext)
2006 (RE "Result" game simpletext)
2007 (RO "Round" game simpletext)
2008 (RU "Rules" game simpletext)
2009 (SE "Markup" - point) ; (LOA)
2010 (SL "Selected" - list point)
2011 (SO "Source" game simpletext)
2012 (SQ "Square" - list point)
2013 (ST "Style" root [number (0 . 3)])
2014 (SU "Setup type" game simpletext) ; (LOA)
2015 (SZ "Size" root (or number (number . number)))
2016 (TB "Territory Black" - elist point) ; (Go)
2017 (TE "Tesuji" move double)
2018 (TM "Timelimit" game real)
2019 (TR "Triangle" - list point)
2020 (TW "Territory White" - elist point) ; (Go)
2021 (UC "Unclear pos" - double)
2022 (US "User" game simpletext)
2023 (V "Value" - real)
2024 (VW "View" - elist point) ; (inherit)
2025 (W "White" move move)
2026 (WL "White time left" move real)
2027 (WR "White rank" game simpletext)
2028 (WT "White team" game simpletext)
2029 (LT "Lose on time" setup simpletext))
2030 ;; r4-specific notes
2031 ;; - changed: DT FG LB RE RU SZ
2032 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2033 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2034
2035 (defun gnugo/sgf-read-file (filename)
2036 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2037 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2038 (put 'gnugo/sgf-*r4-properties* :keywords
2039 (mapcar (lambda (full)
2040 (cons (car full)
2041 (intern (format ":%s" (car full)))))
2042 gnugo/sgf-*r4-properties*))))
2043 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2044 (put 'gnugo/sgf-*r4-properties* :specs
2045 (mapcar (lambda (full)
2046 (cons (car full) (cdddr full)))
2047 gnugo/sgf-*r4-properties*)))))
2048 (cl-labels
2049 ((sw () (skip-chars-forward " \t\n"))
2050 (x (end) (let ((beg (point))
2051 (endp (case end
2052 (:end (lambda (char) (= ?\] char)))
2053 (:mid (lambda (char) (= ?\: char)))
2054 (t (lambda (char) (or (= ?\: char)
2055 (= ?\] char))))))
2056 c)
2057 (while (not (funcall endp (setq c (char-after))))
2058 (cond ((= ?\\ c)
2059 (delete-char 1)
2060 (if (eolp)
2061 (kill-line 1)
2062 (forward-char 1)))
2063 ((looking-at "\\s-+")
2064 (delete-region (point) (match-end 0))
2065 (insert " "))
2066 (t (forward-char 1))))
2067 (buffer-substring-no-properties beg (point))))
2068 (one (type end) (unless (eq 'none type)
2069 (forward-char 1)
2070 (let ((s (x end)))
2071 (case type
2072 ((stone point move simpletext color) s)
2073 ((number real double) (string-to-number s))
2074 ((text) s)
2075 (t (error "Unhandled type: %S" type))))))
2076 (val (spec) (cond ((symbolp spec)
2077 (one spec :end))
2078 ((vectorp spec)
2079 ;; todo: check range here.
2080 (one (aref spec 0) :end))
2081 ((eq 'or (car spec))
2082 (let ((v (one (cadr spec) t)))
2083 (if (= ?\] (char-after))
2084 v
2085 (forward-char 1)
2086 ;; todo: this assumes `spec' has the form
2087 ;; (or foo (foo . bar))
2088 ;; i.e., foo is not rescanned. e.g., `SZ'.
2089 ;; probably this assumption is consistent
2090 ;; w/ the SGF authors' desire to make the
2091 ;; parsing easy, but you never know...
2092 (cons v (one (cdaddr spec) :end)))))
2093 (t (cons (one (car spec) :mid)
2094 (one (cdr spec) :end)))))
2095 (short (who) (when (eobp)
2096 (error "Unexpected EOF while reading %s" who)))
2097 (atvalp () (= ?\[ (char-after)))
2098 (PROP () (let (name spec ltype)
2099 (sw) (short 'property)
2100 (when (looking-at "[A-Z]")
2101 (setq name (read (current-buffer))
2102 spec (cdr (assq name specs)))
2103 (sw)
2104 (cons
2105 (cdr (assq name keywords))
2106 (prog1 (if (= 1 (length spec))
2107 (val (car spec))
2108 (unless (memq (setq ltype (car spec))
2109 '(elist list))
2110 (error "Bad spec: %S" spec))
2111 (if (and (eq 'elist ltype) (sw)
2112 (not (atvalp)))
2113 nil
2114 (let ((type (cadr spec))
2115 mo ls)
2116 (while (and (sw) (atvalp)
2117 (setq mo (val type)))
2118 (push mo ls)
2119 (forward-char 1))
2120 (forward-char -1)
2121 (nreverse ls))))
2122 (forward-char 1))))))
2123 (NODE () (let (prop props)
2124 (sw) (short 'node)
2125 (when (= ?\; (char-after))
2126 (forward-char 1)
2127 (while (setq prop (PROP))
2128 (push prop props))
2129 (nreverse props))))
2130 (TREE () (let (nodes)
2131 (while (and (sw) (not (eobp)))
2132 (case (char-after)
2133 (?\; (push (NODE) nodes))
2134 (?\( (forward-char 1)
2135 (push (TREE) nodes))
2136 (?\) (forward-char 1))))
2137 (nreverse nodes))))
2138 (with-temp-buffer
2139 (insert-file-contents filename)
2140 (let (trees)
2141 (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2142 (forward-char 1)
2143 (push (TREE) trees))
2144 (nreverse trees))))))
2145
2146 (defun gnugo/sgf-write-file (collection filename)
2147 ;; take responsibility for our actions
2148 (dolist (tree collection)
2149 (let* ((root (car tree))
2150 (who (assq :AP root))
2151 (fruit (cons "gnugo.el" gnugo-version)))
2152 (if who
2153 (setcdr who fruit)
2154 (setcdr (last root) (list (cons :AP fruit))))))
2155 ;; write it out
2156 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2157 (specs (mapcar (lambda (full)
2158 (cons (intern (format ":%s" (car full)))
2159 (cdddr full)))
2160 gnugo/sgf-*r4-properties*))
2161 p name v spec)
2162 ;; todo: escape special chars for `text' and `simpletext'.
2163 (cl-labels
2164 ((>>one (v) (insert (format "[%s]" v)))
2165 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2166 (>>nl () (cond ((memq name aft-newline-appreciated)
2167 (insert "\n"))
2168 ((< 60 (current-column))
2169 (save-excursion
2170 (goto-char p)
2171 (insert "\n"))))))
2172 (with-temp-buffer
2173 (dolist (tree collection)
2174 (insert "(")
2175 (dolist (node tree)
2176 (insert ";")
2177 (dolist (prop node)
2178 (setq p (point)
2179 name (car prop)
2180 v (cdr prop))
2181 (insert (substring (symbol-name name) 1))
2182 (cond ((not v))
2183 ((and (consp v)
2184 (memq (car (setq spec (cdr (assq name specs))))
2185 '(list elist)))
2186 (>>nl)
2187 (let ((>> (if (consp (cadr spec))
2188 #'>>two
2189 #'>>one)))
2190 (dolist (little-v v)
2191 (setq p (point)) (funcall >> little-v) (>>nl))))
2192 ((consp v)
2193 (>>two v) (>>nl))
2194 (t
2195 (>>one v) (>>nl)))))
2196 (insert ")\n"))
2197 (write-file filename)))))
2198
2199 ;;; gnugo.el ends here