]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo int] Add abstraction: gnugo--no-worries
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Version: 2.3.1
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
8
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Playing
25 ;; -------
26 ;;
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
32 ;;
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
37 ;;
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase).
43 ;;
44 ;; There are a great many other commands. Other keybindings are described in
45 ;; the `gnugo-board-mode' documentation, which you may view with the command
46 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
47 ;; the last move and who is currently to play. Capture counts and other info
48 ;; are shown on the mode line immediately following the major mode name.
49 ;;
50 ;; While GNU Go is pondering its next move, certain commands that rely on its
51 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
52 ;; is normal. When it is your turn again you may retry the command. In the
53 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
54 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
55 ;;
56 ;; If GNU Go should crash during a game the mode line will show "no process".
57 ;; Please report the event to the GNU Go maintainers so that they can improve
58 ;; the program.
59 ;;
60 ;;
61 ;; Meta-Playing (aka Customizing)
62 ;; ------------------------------
63 ;;
64 ;; Customization is presently limited to
65 ;; vars: `gnugo-program'
66 ;; `gnugo-animation-string'
67 ;; `gnugo-mode-line'
68 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
69 ;; `gnugo-xpms'
70 ;; normal hooks: `gnugo-board-mode-hook'
71 ;; `gnugo-frolic-mode-hook'
72 ;; `gnugo-start-game-hook'
73 ;; `gnugo-post-move-hook'
74 ;; and the keymap: `gnugo-board-mode-map'
75 ;;
76 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
77 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
78 ;; interface.
79
80 ;;; Code:
81
82 (eval-when-compile (require 'cl)) ; use the source luke!
83 (require 'ascii-art-to-unicode) ; for `aa2u'
84 (require 'time-date) ; for `time-subtract'
85
86 ;;;---------------------------------------------------------------------------
87 ;;; Political arts
88
89 (defconst gnugo-version "2.3.1"
90 "Version of gnugo.el currently loaded.
91 This follows a MAJOR.MINOR.PATCH scheme.")
92
93 ;;;---------------------------------------------------------------------------
94 ;;; Variables for the uninquisitive programmer
95
96 (defvar gnugo-program "gnugo"
97 "Name of the GNU Go program (executable file).
98 \\[gnugo] validates this using `executable-find'.
99 This program must accept command line args:
100 --mode gtp --quiet
101 For more information on GTP and GNU Go, please visit:
102 <http://www.gnu.org/software/gnugo>")
103
104 (defvar gnugo-board-mode-map nil
105 "Keymap for GNUGO Board mode.")
106
107 (defvar gnugo-frolic-mode-map nil
108 "Keymap for GNUGO Frolic mode.")
109
110 (defvar gnugo-board-mode-hook nil
111 "Hook run when entering GNUGO Board mode.")
112
113 (defvar gnugo-start-game-hook nil
114 "Normal hook run immediately before the first move of the game.
115 To find out who is to move first, use `gnugo-current-player'.
116 See also `gnugo-board-mode'.")
117
118 (defvar gnugo-post-move-hook nil
119 "Normal hook run after a move and before the board is refreshed.
120 Initially, when `run-hooks' is called, the current buffer is the GNUGO
121 Board buffer of the game. Hook functions that switch buffers must take
122 care not to call (directly or indirectly through some other function)
123 `gnugo-put' or `gnugo-get' after the switch.")
124
125 (defvar gnugo-animation-string
126 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
127 (concat jam jam jam jam jam
128 ;; "SECRET MESSAGE HERE"
129 blink blink blink blink blink blink blink blink
130 ;; Playing go is like fighting ignorance: when you think you have
131 ;; surrounded something by knowing it very well it often turns
132 ;; out that in the time you spent deepening this understanding,
133 ;; other areas of ignorance have surrounded you.
134 spin spin spin spin spin spin spin spin spin
135 ;; Playing go is not like fighting ignorance: what one person
136 ;; knows many people may come to know; knowledge does not build
137 ;; solely move by move. Wisdom, on the other hand...
138 yada yada yada))
139 "String whose individual characters are used for animation.
140 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
141 render the stones in their respective result groups as the first character
142 in the string, then the next, and so on.")
143
144 (defvar gnugo-mode-line "~b ~w :~m :~u"
145 "A `mode-line-format'-compliant value for GNUGO Board mode.
146 If a single string, the following special escape sequences are
147 replaced with their associated information:
148 ~b,~w black,white captures (a number)
149 ~p current player (black or white)
150 ~m move number
151 ~t time waiting for the current move
152 ~u time taken for the Ultimate (most recent) move
153 The times are in seconds, or \"-\" if that information is not available.
154 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
155
156 (defvar gnugo-X-face 'font-lock-string-face
157 "Name of face to use for X (black) stones.")
158
159 (defvar gnugo-O-face 'font-lock-builtin-face
160 "Name of face to use for O (white) stones.")
161
162 (defvar gnugo-grid-face 'default
163 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
164
165 ;;;---------------------------------------------------------------------------
166 ;;; Variables for the inquisitive programmer
167
168 (defconst gnugo-font-lock-keywords
169 '(("X" . gnugo-X-face)
170 ("O" . gnugo-O-face))
171 "Font lock keywords for `gnugo-board-mode'.")
172
173 (defvar gnugo-option-history nil)
174
175 (defvar gnugo-state nil) ; hint: C-c C-p
176
177 (eval-when-compile
178 (defvar gnugo-xpms nil))
179
180 (defvar gnugo-frolic-parent-buffer nil)
181 (defvar gnugo-frolic-origin nil)
182
183 ;;;---------------------------------------------------------------------------
184 ;;; Support functions
185
186 (defsubst gnugo--mkht (&rest etc)
187 (apply 'make-hash-table :test 'eq etc))
188
189 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
190 (compare-strings s1 beg1 nil s2 beg2 nil))
191
192 (defun gnugo-put (key value)
193 "Associate move/game/board-specific property KEY with VALUE.
194
195 There are many properties, each named by a keyword, that record and control
196 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
197 of properties, stored in the hash table `gnugo-state'. Here we document
198 some of the more stable properties. You may wish to use them as part of
199 a `gnugo-post-move-hook' function, for example. Be careful to preserve
200 the current buffer as `gnugo-state' is made into a buffer-local variable.
201 NOTE: In the following, \"see foo\" actually means \"see foo source or
202 you may never really understand to any degree of personal satisfaction\".
203
204 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
205
206 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
207
208 :game-over -- nil until game over at which time its value is set to
209 the alist `((live GROUP ...) (dead GROUP ...))'
210
211 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
212 a simple list of one or more gametrees, updated in
213 conjunction w/ :sgf-gametree and :monkey
214
215 :sgf-gametree -- one of the gametrees in :sgf-collection
216
217 :monkey -- vector of two elements:
218 MEM, a pointer to one of the branches in the gametree;
219 BIDX, the index of the \"current branch\"
220
221 :gnugo-color -- either \"black\" or \"white\"
222 :user-color
223 :last-mover
224
225 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
226 :waiting-start
227
228 :black-captures -- these are strings since gnugo.el doesn't do anything
229 :white-captures w/ the information besides display it in the mode line;
230 gory details in functions `gnugo-propertize-board-buffer'
231 and `gnugo-merge-showboard-results' (almost more effort
232 than they are worth!)
233
234 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
235 `gnugo-toggle-image-display' and `gnugo-refresh',
236 as well as gnugo-xpms.el (available elsewhere)
237
238 :all-yy -- list of 46 keywords used as the `category' text property
239 (so that their plists, typically w/ property `display' or
240 `do-not-display') are consulted by the Emacs display engine;
241 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
242 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
243
244 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
245 the last move; only one is used when displaying using images
246
247 :last-user-bpos -- board position; keep the hapless human happy
248
249 As things stabilize probably more info will be added to this docstring."
250 (declare (indent 1))
251 (puthash key value gnugo-state))
252
253 (defun gnugo-get (key)
254 "Return the move/game/board-specific value for KEY.
255 See `gnugo-put'."
256 (gethash key gnugo-state))
257
258 (defun gnugo--forget (&rest keys)
259 (dolist (key keys)
260 (remhash key gnugo-state)))
261
262 (defsubst gnugo--tree-mnum (tree)
263 (aref tree 1))
264
265 (defsubst gnugo--tree-ends (tree)
266 (aref tree 0))
267
268 (defsubst gnugo--set-tree-ends (tree ls)
269 (aset tree 0 (apply 'vector ls))
270 (gnugo--tree-ends tree))
271
272 (defun gnugo--root-node (&optional tree)
273 (aref (or tree (gnugo-get :sgf-gametree))
274 2))
275
276 (defun gnugo-describe-internal-properties ()
277 "Pretty-print `gnugo-state' properties in another buffer.
278 Handle the big, slow-to-render, and/or uninteresting ones specially."
279 (interactive)
280 (let ((buf (current-buffer))
281 (d (gnugo-get :diamond))
282 acc)
283 (loop for key being the hash-keys of gnugo-state
284 using (hash-values val)
285 do (push (cons key
286 (case key
287 ((:xpms :local-xpms)
288 (format "hash: %X (%d images)"
289 (sxhash val)
290 (length val)))
291 (:sgf-collection
292 (length val))
293 (:sgf-gametree
294 (list (hash-table-count
295 (gnugo--tree-mnum val))
296 (gnugo--root-node val)
297 (gnugo--tree-ends val)))
298 (:monkey
299 (let ((mem (aref val 0)))
300 (list (aref val 1)
301 (car mem))))
302 (t val)))
303 acc))
304 (switch-to-buffer (get-buffer-create
305 (format "%s*GNUGO Board Properties*"
306 (gnugo-get :diamond))))
307 (erase-buffer)
308 (emacs-lisp-mode)
309 (setq truncate-lines t)
310 (save-excursion
311 (pp acc
312 (current-buffer))
313 (goto-char (point-min))
314 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
315 (if (string= "" d)
316 ".+\n"
317 ""))))
318 (while (re-search-forward rx (point-max) t)
319 (let ((pos (get-text-property (string-to-number (match-string 1))
320 'gnugo-position buf)))
321 (delete-region (+ 2 (match-beginning 0)) (point))
322 (insert (format " %S" pos))))))
323 (message "%d properties" (length acc))))
324
325 (defun gnugo-board-buffer-p (&optional buffer)
326 "Return non-nil if BUFFER is a GNUGO Board buffer."
327 (eq 'gnugo-board-mode
328 (buffer-local-value
329 'major-mode
330 (or buffer (current-buffer)))))
331
332 (defun gnugo-board-user-play-ok-p (&optional buffer)
333 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
334 (with-current-buffer (or buffer (current-buffer))
335 (and gnugo-state (not (gnugo-get :waiting)))))
336
337 (defsubst gnugo--blackp (string)
338 (string= "black" string))
339
340 (defun gnugo-other (color)
341 (if (gnugo--blackp color) "white" "black"))
342
343 (defun gnugo-current-player ()
344 "Return the current player, either \"black\" or \"white\"."
345 (gnugo-other (gnugo-get :last-mover)))
346
347 (defsubst gnugo--prop<-color (color)
348 (if (gnugo--blackp color) :B :W))
349
350 (defsubst gnugo--gate-game-over (enable)
351 (when (and enable (gnugo-get :game-over))
352 (user-error "Sorry, game over")))
353
354 (defun gnugo--ERR-wait (color why)
355 (user-error "%s -- please wait for \"(%s to play)\""
356 why color))
357
358 (defun gnugo-gate (&optional in-progress-p)
359 (unless (gnugo-board-buffer-p)
360 (user-error "Wrong buffer -- try M-x gnugo"))
361 (unless (gnugo-get :proc)
362 (user-error "No \"gnugo\" process!"))
363 (destructuring-bind (&optional color . suggestion)
364 (gnugo-get :waiting)
365 (when color
366 (gnugo--ERR-wait
367 color (if suggestion
368 "Still thinking"
369 "Not your turn yet"))))
370 (gnugo--gate-game-over in-progress-p))
371
372 (defun gnugo-sentinel (proc string)
373 (let ((status (process-status proc)))
374 (when (memq status '(exit signal))
375 (let ((buf (process-buffer proc)))
376 (when (buffer-live-p buf)
377 (with-current-buffer buf
378 (setq mode-line-process
379 (list " [%s ("
380 (propertize (car (split-string string))
381 'face 'font-lock-warning-face)
382 ")]"))
383 (when (eq proc (gnugo-get :proc))
384 (gnugo--forget :proc))))))))
385
386 (defun gnugo--begin-exchange (proc filter line)
387 (declare (indent 2)) ; good time, for a rime
388 ; nice style, for a wile...
389 (set-process-filter proc filter)
390 (process-send-string proc line)
391 (process-send-string proc "\n"))
392
393 (defun gnugo--q (fmt &rest args)
394 "Send formatted command \"FMT ARGS...\"; wait for / return response.
395 The response is a string whose first two characters indicate the
396 status of the command. See also `gnugo-query'."
397 (let ((slow (gnugo-get :waiting))
398 (proc (gnugo-get :proc)))
399 (when slow
400 (user-error "Sorry, still waiting for %s to %s"
401 (car slow) (if (cdr slow)
402 "receive a suggestion"
403 "play")))
404 (process-put proc :incomplete t)
405 (process-put proc :srs "") ; synchronous return stash
406 (gnugo--begin-exchange
407 proc (lambda (proc string)
408 (let ((full (concat (process-get proc :srs)
409 string)))
410 (process-put proc :srs full)
411 (unless (numberp (gnugo--compare-strings
412 full (max 0 (- (length full)
413 2))
414 "\n\n" nil))
415 (process-put proc :incomplete nil))))
416 (if (null args)
417 fmt
418 (apply #'format fmt args)))
419 (while (process-get proc :incomplete)
420 (accept-process-output proc 30))
421 (prog1 (substring (process-get proc :srs) 0 -2)
422 (process-put proc :srs ""))))
423
424 (defsubst gnugo--no-worries (string)
425 (= ?= (aref string 0)))
426
427 (defun gnugo--q/ue (fmt &rest args)
428 (let ((ans (apply 'gnugo--q fmt args)))
429 (unless (gnugo--no-worries ans)
430 (user-error "%s" ans))
431 (substring ans 2)))
432
433 (defun gnugo-query (message-format &rest args)
434 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
435 Return a string that omits the first two characters (corresponding
436 to the status indicator in the Go Text Protocol). Use this function
437 when you are sure the command cannot fail."
438 (substring (apply 'gnugo--q message-format args)
439 2))
440
441 (defun gnugo--nquery (cmd)
442 (string-to-number (gnugo-query cmd)))
443
444 (defun gnugo-lsquery (message-format &rest args)
445 (split-string (apply 'gnugo-query message-format args)))
446
447 (defsubst gnugo--count-query (fmt &rest args)
448 (length (apply 'gnugo-lsquery fmt args)))
449
450 (defsubst gnugo--root-prop (prop &optional tree)
451 (cdr (assq prop (gnugo--root-node tree))))
452
453 (defun gnugo--set-root-prop (prop value &optional tree)
454 (let* ((root (gnugo--root-node tree))
455 (cur (assq prop root)))
456 (if cur
457 (setcdr cur value)
458 (push (cons prop value)
459 (cdr (last root))))))
460
461 (defun gnugo-goto-pos (pos)
462 "Move point to board position POS, a letter-number string."
463 (goto-char (point-min))
464 (forward-line (- (1+ (gnugo-get :SZ))
465 (string-to-number (substring pos 1))))
466 (forward-char 1)
467 (forward-char (+ (if (= 32 (following-char)) 1 2)
468 (* 2 (- (let ((letter (aref pos 0)))
469 (if (> ?I letter)
470 letter
471 (1- letter)))
472 ?A)))))
473
474 (defun gnugo-f (frag)
475 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
476
477 (defun gnugo-yang (c)
478 (cdr (assq c '((?+ . hoshi)
479 (?. . empty)
480 (?X . (bmoku . bpmoku))
481 (?O . (wmoku . wpmoku))))))
482
483 (defun gnugo-yy (yin yang &optional momentaryp)
484 (gnugo-f (format "%d-%s"
485 yin (cond ((and (consp yang) momentaryp) (cdr yang))
486 ((consp yang) (car yang))
487 (t yang)))))
488
489 (defun gnugo-toggle-image-display ()
490 (unless (and (fboundp 'display-images-p) (display-images-p))
491 (user-error "Display does not support images, sorry"))
492 (require 'gnugo-xpms)
493 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
494 (user-error "Could not load `gnugo-xpms', sorry"))
495 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
496 (unless (eq fresh (gnugo-get :xpms))
497 (gnugo-put :xpms fresh)
498 (gnugo--forget :all-yy)))
499 (let* ((new (not (gnugo-get :display-using-images)))
500 (act (if new 'display 'do-not-display)))
501 (mapc (lambda (yy)
502 (setcar (symbol-plist yy) act))
503 (or (gnugo-get :all-yy)
504 (gnugo-put :all-yy
505 (prog1 (mapcar (lambda (ent)
506 (let* ((k (car ent))
507 (yy (gnugo-yy (cdr k) (car k))))
508 (setplist yy `(not-yet ,(cdr ent)))
509 yy))
510 (gnugo-get :xpms))
511 (gnugo-put :imul
512 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
513 'not-yet)))))))
514 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
515 (gnugo-put :highlight-last-move-spec
516 (if new
517 '((lambda (p)
518 (get (gnugo-yy (get-text-property p 'gnugo-yin)
519 (get-text-property p 'gnugo-yang)
520 t)
521 'display))
522 0 delete-overlay)
523 (gnugo-get :default-highlight-last-move-spec)))
524 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
525 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
526 (mapc 'delete-overlay (cdar group))
527 (setcdr (car group) nil))
528 (gnugo-put :mul (if new
529 (gnugo-get :imul)
530 '(1 . 1)))
531 (gnugo-put :display-using-images new)))
532
533 (defun gnugo-toggle-grid ()
534 "Turn the grid around the board on or off."
535 (interactive)
536 (funcall (if (memq :nogrid buffer-invisibility-spec)
537 'remove-from-invisibility-spec
538 'add-to-invisibility-spec)
539 :nogrid)
540 (save-excursion (gnugo-refresh)))
541
542 (defun gnugo-propertize-board-buffer ()
543 (erase-buffer)
544 (insert (substring (gnugo--q "showboard") 3))
545 (let* ((grid-props (list 'invisible :nogrid
546 'font-lock-face gnugo-grid-face))
547 (%gpad (gnugo-f 'gpad))
548 (%gspc (gnugo-f 'gspc))
549 (%lpad (gnugo-f 'lpad))
550 (%rpad (gnugo-f 'rpad))
551 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
552 (size (gnugo-get :SZ))
553 (size-string (number-to-string size)))
554 (goto-char (point-min))
555 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
556 (skip-chars-forward " ")
557 (put-text-property (1- (point)) (point) 'category %gpad)
558 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
559 (forward-char 1)
560 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
561 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
562 (let* ((row (match-string-no-properties 1))
563 (edge (match-end 0))
564 (other-edge (+ edge (* 2 size) -1))
565 (right-empty (+ other-edge (length row) 1))
566 (top-p (string= size-string row))
567 (bot-p (string= "1" row)))
568 (let* ((nL (- edge 1 (length size-string)))
569 (nR (- edge 1))
570 (ov (make-overlay nL nR (current-buffer) t)))
571 (add-text-properties nL nR grid-props)
572 ;; We redundantly set `invisible' in the overlay to workaround
573 ;; a display bug whereby text *following* the overlaid text is
574 ;; displayed with the face of the overlaid text, but only when
575 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
576 ;; This has something to do w/ the bletcherous `before-string'.
577 (overlay-put ov 'invisible :nogrid)
578 (overlay-put ov 'category %lpad))
579 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
580 ((< other-edge p))
581 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
582 (truncate (- p edge) 2))
583 row))
584 (yin (let ((A-p (= edge p))
585 (Z-p (= (1- other-edge) p)))
586 (cond ((and top-p A-p) 1)
587 ((and top-p Z-p) 3)
588 ((and bot-p A-p) 7)
589 ((and bot-p Z-p) 9)
590 (top-p 2)
591 (bot-p 8)
592 (A-p 4)
593 (Z-p 6)
594 (t 5))))
595 (yang (gnugo-yang (char-after p))))
596 (add-text-properties p (1+ p)
597 `(gnugo-position
598 ,position
599 gnugo-yin
600 ,yin
601 gnugo-yang
602 ,yang
603 category
604 ,(gnugo-yy yin yang)
605 front-sticky
606 (gnugo-position gnugo-yin))))
607 (unless (= (1- other-edge) p)
608 (add-text-properties (1+ p) (+ 2 p) ispc-props)
609 (put-text-property p (+ 2 p) 'intangible ival)))
610 (add-text-properties (1+ other-edge) right-empty grid-props)
611 (goto-char right-empty)
612 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
613 (let ((prop (if (string= "WH" (match-string 1))
614 :white-captures
615 :black-captures))
616 (beg (match-beginning 2))
617 (end (match-end 2)))
618 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
619 (gnugo-put prop (match-string-no-properties 2))))
620 (end-of-line)
621 (put-text-property right-empty (point) 'category %rpad)
622 (forward-char 1)))
623 (add-text-properties (1- (point)) (point-max) grid-props)
624 (skip-chars-forward " ")
625 (put-text-property (1- (point)) (point) 'category %gpad)
626 (put-text-property (point) (progn (end-of-line) (point))
627 'category %gspc)))
628
629 (defun gnugo-merge-showboard-results ()
630 (let ((aft (substring (gnugo--q "showboard") 3))
631 (adj 1) ; string to buffer position adjustment
632
633 (sync "[0-9]* stones$")
634 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
635 ;; restrictive a condition that fails in the case of:
636 ;;
637 ;; (before)
638 ;; ... WHITE has captured 1 stones
639 ;; ^
640 ;; (after)
641 ;; ... WHITE has captured 14 stones
642 ;; ^
643 ;;
644 ;; where the after count has more digits than the before count,
645 ;; but shares the same leading digits. In this case, the result
646 ;; of `compare-strings' points to the SPC following the before
647 ;; count (indicated by caret in this example).
648
649 (bef (buffer-substring-no-properties (point-min) (point-max)))
650 (bef-start 0) (bef-idx 0)
651 (aft-start 0) (aft-idx 0)
652 aft-sync-backtrack mis inc cut new very-strange
653
654 (inhibit-read-only t))
655 (while (numberp (setq mis (gnugo--compare-strings
656 bef bef-start
657 aft aft-start)))
658 (setq aft-sync-backtrack nil
659 inc (if (cl-minusp mis)
660 (- (+ 1 mis))
661 (- mis 1))
662 bef-idx (+ bef-start inc)
663 aft-idx (+ aft-start inc)
664 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
665 (match-end 0)
666 (1+ bef-idx))
667 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
668 (let ((peek (1- aft-idx)))
669 (while (not (= 32 (aref aft peek)))
670 (setq peek (1- peek)))
671 (setq aft-sync-backtrack (1+ peek))))
672 (match-end 0)
673 (1+ aft-idx))
674 cut (+ bef-idx adj
675 (if aft-sync-backtrack
676 (- aft-sync-backtrack aft-idx)
677 0)))
678 (goto-char cut)
679 (if aft-sync-backtrack
680 (let* ((asb aft-sync-backtrack)
681 (l-p (get-text-property cut :gnugo-cf))
682 (old-len (car l-p))
683 (capprop (cdr l-p))
684 (keep (text-properties-at cut)))
685 (setq new (substring aft asb (string-match " " aft asb)))
686 (plist-put keep :gnugo-cf (cons (length new) capprop))
687 (gnugo-put capprop new)
688 (delete-char old-len)
689 (insert (apply 'propertize new keep))
690 (incf adj (- (length new) old-len)))
691 (setq new (aref aft aft-idx))
692 (insert-and-inherit (char-to-string new))
693 (let ((yin (get-text-property cut 'gnugo-yin))
694 (yang (gnugo-yang new)))
695 (add-text-properties cut (1+ cut)
696 `(gnugo-yang
697 ,yang
698 category
699 ,(gnugo-yy yin yang))))
700 (delete-char 1)
701 ;; do this last to avoid complications w/ font lock
702 ;; (this also means we cannot include `intangible' in `front-sticky')
703 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
704 (put-text-property cut (1+ cut) 'intangible very-strange))))))
705
706 (defsubst gnugo--move-prop (node)
707 (or (assq :B node)
708 (assq :W node)))
709
710 (defun gnugo--as-pos-func ()
711 (lexical-let ((size (gnugo-get :SZ)))
712 ;; rv
713 (lambda (cc)
714 (if (string= "" cc)
715 "PASS"
716 (let ((col (aref cc 0)))
717 (format "%c%d"
718 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
719 (- size (- (aref cc 1) ?a))))))))
720
721 (defsubst gnugo--resignp (string)
722 (string= "resign" string))
723
724 (defsubst gnugo--passp (string)
725 (string= "PASS" string))
726
727 (defun gnugo-move-history (&optional rsel color)
728 "Determine and return the game's move history.
729 Optional arg RSEL controls side effects and return value.
730 If nil, display the history in the echo area as \"(N moves)\"
731 followed by the space-separated list of moves. When called
732 interactively with a prefix arg (i.e., RSEL is `(4)'), display
733 similarly, but suffix with the mover (either \":B\" or \":W\").
734 RSEL may also be a symbol that selects what to return:
735 car -- the most-recent move
736 cadr -- the next-to-most-recent move
737 two -- the last two moves as a list, oldest last
738 bpos -- the last stone on the board placed by COLOR
739 For all other values of RSEL, do nothing and return nil."
740 (interactive "P")
741 (let* ((monkey (gnugo-get :monkey))
742 (mem (aref monkey 0))
743 (as-pos (gnugo--as-pos-func))
744 acc node mprop move)
745 (cl-flet*
746 ((as-pos-maybe (x) (if (gnugo--resignp x)
747 x
748 (funcall as-pos x)))
749 (remem () (setq node (pop mem)
750 mprop (gnugo--move-prop node)))
751 (next (byp) (when (remem)
752 (setq move (as-pos-maybe (cdr mprop)))
753 (push (if byp
754 (format "%s%s" move (car mprop))
755 move)
756 acc)))
757 (nn () (next nil))
758 (tell () (message "(%d moves) %s"
759 (length acc)
760 (mapconcat 'identity (nreverse acc) " ")))
761 (finish (byp) (while mem (next byp)) (tell)))
762 (pcase rsel
763 (`(4) (finish t))
764 (`nil (finish nil))
765 (`car (car (nn)))
766 (`cadr (nn) (car (nn)))
767 (`two (nn) (nn) acc)
768 (`bpos (loop with prop = (gnugo--prop<-color color)
769 while mem
770 when (and (remem)
771 (eq prop (car mprop))
772 (setq move (cdr mprop))
773 ;; i.e., "normal CC" position
774 (= 2 (length move)))
775 return (funcall as-pos move)))
776 (_ nil)))))
777
778 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
779 "A special mode for manipulating a GNUGO gametree.
780
781 \\{gnugo-frolic-mode-map}"
782 (setq truncate-lines t)
783 (buffer-disable-undo))
784
785 (defun gnugo-frolic-quit ()
786 "Kill GNUGO Frolic buffer and switch to its parent buffer."
787 (interactive)
788 (let ((bye (current-buffer)))
789 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
790 gnugo-frolic-parent-buffer))
791 (kill-buffer bye)))
792
793 (defun gnugo-frolic-return-to-origin ()
794 "Move point to the board's current position."
795 (interactive)
796 (if (not gnugo-frolic-origin)
797 (message "No origin")
798 (goto-char gnugo-frolic-origin)
799 (recenter (- (count-lines (line-beginning-position)
800 (point-max))))))
801
802 (defun gnugo-frolic-in-the-leaves ()
803 "Display the game tree in a *GNUGO Frolic* buffer.
804 This looks something like:
805
806 1 B -- E7 E7 E7 E7
807 2 W -- K10 K10 K10 K10
808 3 B -- E2 E2 E2 E2
809 4 W -- J3 J3 J3 J3
810 5 B -- A6 A6 A6 A6
811 6 W -- C9 C9 C9 C9
812
813 ├─────┬─────┐
814 │ │ │
815 7 B -- H7 !B8 C8 C8
816
817 ├─────┐
818 │ │
819 8 W -- D9 D9 D9 E9
820 9 B -- H8 H8
821 10 W -- PASS PASS
822 11 B -- H5 PASS
823 12 W -- PASS
824 13 B -- *PASS
825
826 with 0, 1, ... N (in this case N is 3) in the header line
827 to indicate the branches. Branch 0 is the \"main line\".
828 Point (* in this example) indicates the current position,
829 \"!\" indicates comment properties (e.g., B8, branch 1),
830 and moves not actually on the game tree (e.g., E7, branch 3)
831 are dimmed. Type \\[describe-mode] in that buffer for details."
832 (interactive)
833 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
834 "*GNUGO Frolic*")))
835 (from (or gnugo-frolic-parent-buffer
836 (current-buffer)))
837 ;; todo: use defface once we finally succumb to ‘customize’
838 (dimmed-node-face (list :inherit 'default
839 :foreground "gray50"))
840 (tree (gnugo-get :sgf-gametree))
841 (ends (copy-sequence (gnugo--tree-ends tree)))
842 (mnum (gnugo--tree-mnum tree))
843 (seen (gnugo--mkht))
844 (soil (gnugo--mkht))
845 (width (length ends))
846 (lanes (number-sequence 0 (1- width)))
847 (monkey (gnugo-get :monkey))
848 (as-pos (gnugo--as-pos-func))
849 (at (car (aref monkey 0)))
850 (bidx (aref monkey 1))
851 (valid (map 'vector (lambda (end)
852 (gethash (car end) mnum))
853 ends))
854 (max-move-num (apply 'max (append valid nil)))
855 (inhibit-read-only t)
856 finish)
857 (cl-flet
858 ((on (node)
859 (gethash node seen))
860 (emph (s face)
861 (propertize s 'face face))
862 (fsi (properties fmt &rest args)
863 (insert (apply 'propertize
864 (apply 'format fmt args)
865 properties))))
866 ;; breathe in
867 (loop
868 for bx below width
869 do (loop
870 with fork
871 for node in (aref ends bx)
872 do (if (setq fork (on node))
873 (cl-flet
874 ((tip-p (bix)
875 ;; todo: ignore non-"move" nodes
876 (eq node (car (aref ends bix))))
877 (link (other)
878 (pushnew other (gethash node soil))))
879 (unless (tip-p bx)
880 (unless (tip-p fork)
881 (link fork))
882 (link bx)))
883 (puthash node bx seen))
884 until fork))
885 ;; breathe out
886 (switch-to-buffer buf)
887 (gnugo-frolic-mode)
888 (erase-buffer)
889 (setq header-line-format
890 (lexical-let ((full (concat
891 (make-string 11 ?\s)
892 (mapconcat (lambda (n)
893 (format "%-5s" n))
894 lanes
895 " "))))
896 `((:eval
897 (funcall
898 ,(lambda ()
899 (cl-flet
900 ((sp (w) (propertize
901 " " 'display
902 `(space :width ,w))))
903 (concat
904 (when (eq 'left scroll-bar-mode)
905 (let ((w (or scroll-bar-width
906 (frame-parameter
907 nil 'scroll-bar-width)))
908 (cw (frame-char-width)))
909 (sp (if w
910 (/ w cw)
911 2))))
912 (let ((fc (fringe-columns 'left t)))
913 (unless (zerop fc)
914 (sp fc)))
915 (condition-case nil
916 (substring full (window-hscroll))
917 (error ""))))))))))
918 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
919 (set (make-local-variable 'gnugo-state)
920 (buffer-local-value 'gnugo-state from))
921 (loop
922 with props
923 for n ; move number
924 from max-move-num downto 1
925 do (setq props (list 'n n))
926 do
927 (loop
928 with (move forks br)
929 initially (progn
930 (goto-char (point-min))
931 (fsi props
932 "%3d %s -- "
933 n (aref ["W" "B"] (logand 1 n))))
934 for bx below width
935 do (let* ((node (unless (< (aref valid bx) n)
936 ;; todo: ignore non-"move" nodes
937 (pop (aref ends bx))))
938 (zow (list* 'bx bx props))
939 (ok (when node
940 (= bx (on node))))
941 (comment (when ok
942 (cdr (assq :C node))))
943 (s (cond ((not node) "")
944 ((not (setq move (gnugo--move-prop node))) "-")
945 (t (funcall as-pos (cdr move))))))
946 (when comment
947 (push comment zow)
948 (push 'help-echo zow))
949 (when (and ok (setq br (gethash node soil)))
950 (push (cons bx (sort br '<))
951 forks))
952 (fsi zow
953 "%c%-5s"
954 (if comment ?! ?\s)
955 (cond ((and (eq at node)
956 (or ok (= bx bidx)))
957 (when (= bx bidx)
958 (setq finish (point-marker)))
959 (emph s (list :inherit 'default
960 :foreground (frame-parameter
961 nil 'cursor-color))))
962 ((not ok)
963 (emph s dimmed-node-face))
964 (t s))))
965 finally do
966 (when (progn (fsi props "\n")
967 (setq forks (nreverse forks)))
968 (let* ((margin (make-string 11 ?\s))
969 (heads (mapcar #'car forks))
970 (tails (mapcar #'cdr forks)))
971 (cl-flet*
972 ((spaced (lanes func)
973 (mapconcat func lanes " "))
974 ;; live to play ~ ~ ()
975 ;; play to learn (+) (-) . o O
976 ;; learn to live --ttn .M. _____U
977 (dashed (lanes func) ;;; _____ ^^^^
978 (mapconcat func lanes "-----"))
979 (cnxn (lanes set)
980 (spaced lanes (lambda (bx)
981 (if (memq bx set)
982 "|"
983 " "))))
984 (pad-unless (condition)
985 (if condition
986 ""
987 " "))
988 (edge (set)
989 (insert margin
990 (cnxn lanes set)
991 "\n")))
992 (edge heads)
993 (loop with bef
994 for ls on forks
995 do (let* ((one (car ls))
996 (yes (append
997 ;; "aft" heads
998 (mapcar 'car (cdr ls))
999 ;; ‘bef’ tails
1000 (apply 'append (mapcar 'cdr bef))))
1001 (ord (sort one '<))
1002 (beg (car ord))
1003 (end (car (last ord))))
1004 (cl-flet
1005 ((also (b e) (cnxn (number-sequence b e)
1006 yes)))
1007 (insert
1008 margin
1009 (also 0 (1- beg))
1010 (pad-unless (zerop beg))
1011 (dashed (number-sequence beg end)
1012 (lambda (bx)
1013 (cond ((memq bx ord) "+")
1014 ((memq bx yes) "|")
1015 (t "-"))))
1016 (pad-unless (>= end width))
1017 (also (1+ end) (1- width))
1018 "\n"))
1019 (push one bef)))
1020 (edge (apply 'append tails))
1021 (aa2u (line-beginning-position
1022 (- (1+ (length forks))))
1023 (point))))))))
1024 (when finish
1025 (set (make-local-variable 'gnugo-frolic-origin) finish)
1026 (gnugo-frolic-return-to-origin))))
1027
1028 (defun gnugo--awake (how)
1029 ;; Valid HOW elements:
1030 ;; require-valid-branch
1031 ;; (line . numeric)
1032 ;; (line . move-string)
1033 ;; Invalid elements blissfully ignored. :-D
1034 (let* ((tree (gnugo-get :sgf-gametree))
1035 (ends (gnugo--tree-ends tree))
1036 (width (length ends))
1037 (monkey (gnugo-get :monkey))
1038 (line (case (cdr (assq 'line how))
1039 (numeric
1040 (count-lines (point-min) (line-beginning-position)))
1041 (move-string
1042 (save-excursion
1043 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1044 (match-string 0))))
1045 (t nil)))
1046 (col (current-column))
1047 (a (unless (> 10 col)
1048 (let ((try (/ (- col 10)
1049 6)))
1050 (unless (<= width try)
1051 try))))
1052 (rv (list a)))
1053 (when (memq 'require-valid-branch how)
1054 (unless a
1055 (user-error "No branch here")))
1056 (loop with omit = (cdr (assq 'omit how))
1057 for (name . value) in `((line . ,line)
1058 (bidx . ,(aref monkey 1))
1059 (monkey . ,monkey)
1060 (width . ,width)
1061 (ends . ,ends)
1062 (tree . ,tree))
1063 do (unless (memq name omit)
1064 (push value rv)))
1065 rv))
1066
1067 (defmacro gnugo--awakened (how &rest body)
1068 (declare (indent 1))
1069 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1070 with ls = (list 'a)
1071 for name in '(line bidx monkey
1072 width ends
1073 tree)
1074 do (unless (memq name omit)
1075 (push name ls))
1076 finally return ls)
1077 (gnugo--awake ',how)
1078 ,@body))
1079
1080 (defsubst gnugo--move-to-bcol (bidx)
1081 (move-to-column (+ 10 (* 6 bidx))))
1082
1083 (defun gnugo--swiz (direction &optional blunt)
1084 (gnugo--awakened (require-valid-branch
1085 (omit tree)
1086 (line . numeric))
1087 (let* ((b (cond ((numberp blunt)
1088 (unless (and (< -1 blunt)
1089 (< blunt width))
1090 (user-error "No such branch: %s" blunt))
1091 blunt)
1092 (t (mod (+ direction a) width))))
1093 (flit (if blunt (lambda (n)
1094 (cond ((= n a) b)
1095 ((= n b) a)
1096 (t n)))
1097 (lambda (n)
1098 (mod (+ direction n) width))))
1099 (was (copy-sequence ends))
1100 (new-bidx (funcall flit bidx)))
1101 (loop for bx below width
1102 do (aset ends (funcall flit bx)
1103 (aref was bx)))
1104 (unless (= new-bidx bidx)
1105 (aset monkey 1 new-bidx))
1106 (gnugo-frolic-in-the-leaves)
1107 (goto-char (point-min))
1108 (forward-line line)
1109 (gnugo--move-to-bcol b))))
1110
1111 (defun gnugo-frolic-exchange-left ()
1112 "Exchange the current branch with the one to its left."
1113 (interactive)
1114 (gnugo--swiz -1 t))
1115
1116 (defun gnugo-frolic-rotate-left ()
1117 "Rotate all branches left."
1118 (interactive)
1119 (gnugo--swiz -1))
1120
1121 (defun gnugo-frolic-exchange-right ()
1122 "Exchange the current branch with the one to its right."
1123 (interactive)
1124 (gnugo--swiz 1 t))
1125
1126 (defun gnugo-frolic-rotate-right ()
1127 "Rotate all branches right."
1128 (interactive)
1129 (gnugo--swiz 1))
1130
1131 (defun gnugo-frolic-set-as-main-line ()
1132 "Make the current branch the main line."
1133 (interactive)
1134 (gnugo--swiz nil 0))
1135
1136 (defun gnugo-frolic-prune-branch ()
1137 "Remove the current branch from the gametree.
1138 This fails if there is only one branch in the tree.
1139 This fails if the monkey is on the current branch
1140 \(a restriction that will probably be lifted Real Soon Now\)."
1141 (interactive)
1142 (gnugo--awakened (require-valid-branch
1143 (line . move-string))
1144 ;; todo: define meaningful eviction semantics; remove restriction
1145 (when (= a bidx)
1146 (user-error "Cannot prune with monkey on branch"))
1147 (when (= 1 width)
1148 (user-error "Cannot prune last remaining branch"))
1149 (let ((new (append ends nil)))
1150 ;; Explicit ignorance avoids byte-compiler warning.
1151 (ignore (pop (nthcdr a new)))
1152 (gnugo--set-tree-ends tree new))
1153 (when (< a bidx)
1154 (aset monkey 1 (decf bidx)))
1155 (gnugo-frolic-in-the-leaves)
1156 (when line
1157 (goto-char (point-min))
1158 (search-forward line)
1159 (gnugo--move-to-bcol (min a (- width 2))))))
1160
1161 (defun gnugo--sideways (backwards n)
1162 (gnugo--awakened ((omit tree ends monkey bidx line))
1163 (gnugo--move-to-bcol (mod (if backwards
1164 (- (or a width) n)
1165 (+ (or a -1) n))
1166 width))))
1167
1168 (defun gnugo-frolic-backward-branch (&optional n)
1169 "Move backward N (default 1) branches."
1170 (interactive "p")
1171 (gnugo--sideways t n))
1172
1173 (defun gnugo-frolic-forward-branch (&optional n)
1174 "Move forward N (default 1) branches."
1175 (interactive "p")
1176 (gnugo--sideways nil n))
1177
1178 (defun gnugo--vertical (n direction)
1179 (when (> 0 n)
1180 (setq n (- n)
1181 direction (- direction)))
1182 (gnugo--awakened ((line . numeric)
1183 (omit tree ends width monkey bidx))
1184 (let ((stop (if (> 0 direction)
1185 0
1186 (max 0 (1- (count-lines (point-min)
1187 (point-max))))))
1188 (col (unless a
1189 (current-column))))
1190 (loop while (not (= line stop))
1191 do (loop do (progn
1192 (forward-line direction)
1193 (incf line direction))
1194 until (get-text-property (point) 'n))
1195 until (zerop (decf n)))
1196 (if a
1197 (gnugo--move-to-bcol a)
1198 (move-to-column col)))))
1199
1200 (defun gnugo-frolic-previous-move (&optional n)
1201 "Move to the Nth (default 1) previous move."
1202 (interactive "p")
1203 (gnugo--vertical n -1))
1204
1205 (defun gnugo-frolic-next-move (&optional n)
1206 "Move to the Nth (default 1) next move."
1207 (interactive "p")
1208 (gnugo--vertical n 1))
1209
1210 (defun gnugo-boss-is-near ()
1211 "Do `bury-buffer' until the current one is not a GNU Board."
1212 (interactive)
1213 (while (gnugo-board-buffer-p)
1214 (bury-buffer)))
1215
1216 (defsubst gnugo--no-regrets (monkey ends)
1217 (eq (aref ends (aref monkey 1))
1218 (aref monkey 0)))
1219
1220 (defun gnugo--as-cc-func ()
1221 (lexical-let ((size (gnugo-get :SZ)))
1222 (lambda (pos)
1223 (let* ((col (aref pos 0))
1224 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1225 (two (+ ?a (- size (string-to-number
1226 (substring pos 1))))))
1227 (format "%c%c" one two)))))
1228
1229 (defsubst gnugo--decorate (node alist)
1230 ;; NB: ALIST should not have :B or :W keys.
1231 (setcdr (last node) alist))
1232
1233 (defun gnugo-close-game (end-time resign)
1234 (gnugo-put :game-end-time end-time)
1235 (let ((now (or end-time (current-time))))
1236 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1237 (cadr now))))
1238 (gnugo-put :game-over
1239 (if (or (eq t resign)
1240 (and (stringp resign)
1241 (string-match "[BW][+][Rr]esign" resign)))
1242 (cl-flet
1243 ((ls (color) (mapcar
1244 (lambda (x)
1245 (cons (list color)
1246 (split-string x)))
1247 (split-string
1248 (gnugo-query "worm_stones %s" color)
1249 "\n"))))
1250 (let ((live (append (ls "black") (ls "white"))))
1251 `((live ,@live)
1252 (dead))))
1253 (let ((dd (gnugo-query "dragon_data"))
1254 (start 0) mem color ent live dead)
1255 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1256 dd start)
1257 (setq mem (match-string 1 dd)
1258 color (match-string 2 dd)
1259 start (match-end 0)
1260 ent (cons (list color)
1261 (sort (gnugo-lsquery "dragon_stones %s" mem)
1262 'string<)))
1263 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1264 dd start)
1265 (if (match-string 2 dd)
1266 (push ent live)
1267 (push ent dead))
1268 (setq start (match-end 0)))
1269 `((live ,@live)
1270 (dead ,@dead))))))
1271
1272 (defun gnugo--unclose-game ()
1273 (gnugo--forget :game-over ; all those in -close-game
1274 :scoring-seed
1275 :game-end-time)
1276 (let* ((root (gnugo--root-node))
1277 (cur (assq :RE root)))
1278 (when cur
1279 (assert (not (eq cur (car root))) nil
1280 ":RE at head of root node: %S"
1281 root)
1282 (delq cur root))))
1283
1284 (defun gnugo-push-move (who move)
1285 (let* ((simple (booleanp who))
1286 (ucolor (gnugo-get :user-color))
1287 (color (if simple
1288 (if who
1289 ucolor
1290 (gnugo-get :gnugo-color))
1291 who))
1292 (start (gnugo-get :waiting-start))
1293 (now (current-time))
1294 (resignp (gnugo--resignp move))
1295 (passp (gnugo--passp move))
1296 (head (gnugo-move-history 'car))
1297 (onep (and head (gnugo--passp head)))
1298 (donep (or resignp (and onep passp))))
1299 (unless resignp
1300 (gnugo--q/ue "play %s %s" color move))
1301 (unless passp
1302 (gnugo-merge-showboard-results))
1303 (gnugo-put :last-mover color)
1304 (when (if simple
1305 who
1306 (string= ucolor color))
1307 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1308 ;; update :sgf-gametree and :monkey
1309 (let* ((property (gnugo--prop<-color color))
1310 (pair (cons property (cond (resignp move)
1311 (passp "")
1312 (t (funcall (gnugo--as-cc-func)
1313 move)))))
1314 (fruit (list pair))
1315 (monkey (gnugo-get :monkey))
1316 (mem (aref monkey 0))
1317 (tip (car mem))
1318 (tree (gnugo-get :sgf-gametree))
1319 (ends (gnugo--tree-ends tree))
1320 (mnum (gnugo--tree-mnum tree))
1321 (count (length ends))
1322 (tip-move-num (gethash tip mnum))
1323 (bidx (aref monkey 1)))
1324 ;; Detect déjà-vu. That is, when placing "A", avoid:
1325 ;;
1326 ;; X---Y---A new
1327 ;; \
1328 ;; --A---B old
1329 ;;
1330 ;; (such "variations" do not actually vary!) in favor of:
1331 ;;
1332 ;; X---Y---A new
1333 ;; \
1334 ;; --B old
1335 ;;
1336 ;; This linear search loses for multiple ‘old’ w/ "A",
1337 ;; a very unusual (but not invalid, sigh) situation.
1338 (loop
1339 with (bx previous)
1340 for i
1341 ;; Start with latest / highest likelihood for hit.
1342 ;; (See "to the right" comment, below.)
1343 from (if (gnugo--no-regrets monkey ends)
1344 1
1345 0)
1346 below count
1347 if (setq bx (mod (+ bidx i) count)
1348 previous
1349 (loop with node
1350 for m on (aref ends bx)
1351 while (< tip-move-num
1352 (gethash (setq node (car m))
1353 mnum))
1354 if (eq mem (cdr m))
1355 return
1356 (when (equal pair (assq property node))
1357 m)
1358 finally return
1359 nil))
1360 ;; yes => follow
1361 return
1362 (progn
1363 (unless (= bidx bx)
1364 (rotatef (aref ends bidx)
1365 (aref ends bx)))
1366 (setq mem previous))
1367 ;; no => construct
1368 finally do
1369 (progn
1370 (unless (gnugo--no-regrets monkey ends)
1371 (setq ends (gnugo--set-tree-ends
1372 tree (let ((ls (append ends nil)))
1373 ;; copy old to the right of new
1374 (push mem (nthcdr bidx ls))
1375 ls))))
1376 (puthash fruit (1+ (gethash tip mnum)) mnum)
1377 (push fruit mem)
1378 (aset ends bidx mem)))
1379 (setf (aref monkey 0) mem))
1380 (when start
1381 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1382 (when donep
1383 (gnugo-close-game now resignp))
1384 (gnugo-put :waiting-start (and (not donep) now))
1385 donep))
1386
1387 (defun gnugo-venerate (yin yang)
1388 (let* ((fg-yy (gnugo-yy yin yang))
1389 (fg-disp (or (get fg-yy 'display)
1390 (get fg-yy 'do-not-display)))
1391 (fg-data (plist-get (cdr fg-disp) :data))
1392 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1393 (bg-disp (or (get bg-yy 'display)
1394 (get bg-yy 'do-not-display)))
1395 (bg-data (plist-get (cdr bg-disp) :data))
1396 (bop (lambda (s)
1397 (let* ((start 0)
1398 (ncolors
1399 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1400 (setq start (match-end 0))
1401 (string-to-number (match-string 1 s)))))
1402 (while (and (not (cl-minusp ncolors))
1403 (string-match ",\n" s start))
1404 (setq start (match-end 0)
1405 ncolors (1- ncolors)))
1406 (string-match "\"" s start)
1407 (match-end 0))))
1408 (new (copy-sequence fg-data))
1409 (lx (length fg-data))
1410 (sx (funcall bop fg-data))
1411 (sb (funcall bop bg-data))
1412 (color-key (aref new sx))) ; blech, heuristic
1413 (while (< sx lx)
1414 (when (and (not (= color-key (aref new sx)))
1415 (cl-plusp (random 4)))
1416 (aset new sx (aref bg-data sb)))
1417 (incf sx)
1418 (incf sb))
1419 (create-image new 'xpm t :ascent 'center)))
1420
1421 (defun gnugo-refresh (&optional nocache)
1422 "Update GNUGO Board buffer display.
1423 While a game is in progress, parenthesize the last-played stone (no parens
1424 for pass). If the buffer is currently displayed in the selected window,
1425 recenter the board (presuming there is extra space in the window). Update
1426 the mode line. Lastly, move point to the last position played by the user,
1427 if that move was not a pass.
1428
1429 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1430 be slow. (This should normally be unnecessary; specify it only if the display
1431 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1432 its move."
1433 (interactive "P")
1434 (let* ((move (gnugo-move-history 'car))
1435 (game-over (gnugo-get :game-over))
1436 (inhibit-read-only t)
1437 window last)
1438 (when (and nocache (not (gnugo-get :waiting)))
1439 (gnugo-propertize-board-buffer))
1440 ;; last move
1441 (when move
1442 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1443 (if (member move '("PASS" "resign"))
1444 (mapc 'delete-overlay (list l-ov r-ov))
1445 (gnugo-goto-pos move)
1446 (let* ((p (point))
1447 (hspec (gnugo-get :highlight-last-move-spec))
1448 (display-value (nth 0 hspec))
1449 (l-offset (nth 1 hspec))
1450 (l-new-pos (+ p l-offset))
1451 (r-action (nth 2 hspec)))
1452 (overlay-put l-ov 'display
1453 (if (functionp display-value)
1454 (funcall display-value p)
1455 display-value))
1456 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1457 (if r-action
1458 (funcall r-action r-ov)
1459 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1460 ;; buffer name
1461 (rename-buffer (concat (gnugo-get :diamond)
1462 (if game-over
1463 (format "%s(game over)"
1464 (if (gnugo--resignp move)
1465 (concat move "ation ")
1466 ""))
1467 (format "%s(%s to play)"
1468 (if move (concat move " ") "")
1469 (gnugo-current-player)))))
1470 ;; pall of death
1471 (when game-over
1472 (let ((live (cdr (assq 'live game-over)))
1473 (dead (cdr (assq 'dead game-over)))
1474 p pall)
1475 (unless (eq game-over (get-text-property 1 'game-over))
1476 (dolist (group (append live dead))
1477 (dolist (pos (cdr group))
1478 (gnugo-goto-pos pos)
1479 (setq p (point))
1480 (put-text-property p (1+ p) 'group group)))
1481 (put-text-property 1 2 'game-over game-over))
1482 (dolist (group live)
1483 (when (setq pall (cdar group))
1484 (mapc 'delete-overlay pall)
1485 (setcdr (car group) nil)))
1486 (dolist (group dead)
1487 (unless (cdar group)
1488 (let (ov pall c (color (caar group)))
1489 (setq c (if (gnugo--blackp color) "x" "o"))
1490 (dolist (pos (cdr group))
1491 (gnugo-goto-pos pos)
1492 (setq p (point) ov (make-overlay p (1+ p)))
1493 (overlay-put
1494 ov 'display
1495 (if (gnugo-get :display-using-images)
1496 ;; respect the dead individually; it takes more time
1497 ;; but that's not a problem (for them)
1498 (gnugo-venerate (get-text-property p 'gnugo-yin)
1499 (gnugo-yang (aref (upcase c) 0)))
1500 (propertize c 'face 'font-lock-warning-face)))
1501 (push ov pall))
1502 (setcdr (car group) pall))))))
1503 ;; window update
1504 (when (setq window (get-buffer-window (current-buffer)))
1505 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1506 (size (gnugo-get :SZ))
1507 (under10p (< size 10))
1508 (mul (gnugo-get :mul))
1509 (h (- (truncate (- (window-height window)
1510 (* size (cdr mul))
1511 (if gridp 2 0))
1512 2)
1513 (if gridp 0 1)))
1514 (edges (window-edges window))
1515 (right-w-edge (nth 2 edges))
1516 (avail-width (- right-w-edge (nth 0 edges)))
1517 (wmul (car mul))
1518 (imagesp (symbol-plist (gnugo-f 'ispc)))
1519 (w (/ (- avail-width
1520 (* size wmul)
1521 (if imagesp
1522 0
1523 (1- size))
1524 2 ; between board and grid
1525 (if gridp
1526 (if under10p 2 4)
1527 0))
1528 2.0)))
1529 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1530 `(display ,(make-string h 10))
1531 '(invisible :nogrid)))
1532 (gpad . (display
1533 (space :align-to
1534 ,(+ w
1535 2.0
1536 (cond (imagesp (+ (* 0.5 wmul)
1537 (if under10p
1538 -0.5
1539 0.5)))
1540 (under10p 0)
1541 (t 1))))))
1542 (gspc . ,(when imagesp
1543 `(display
1544 (space-width
1545 ,(-
1546 ;; DWR: image width alone => OBOE!
1547 ;;- wmul
1548 ;; NB: ‘(* wmul cw)’ is the same
1549 ;; as ‘(car (image-size ... t))’.
1550 (let ((cw (frame-char-width)))
1551 (/ (+ 1.0 (* wmul cw))
1552 cw))
1553 1.0)))))
1554 (lpad . ,(let ((d `(display (space :align-to ,w))))
1555 ;; We distinguish between these cases to
1556 ;; workaround a display bug whereby the
1557 ;; `before-string' is omitted entirely (not
1558 ;; rendered) when interacting w/ the text
1559 ;; mode last-move left-paren for moves in
1560 ;; column A.
1561 (if gridp
1562 `(before-string
1563 ,(apply 'propertize " " d))
1564 d)))
1565 (rpad . (display
1566 (space :align-to ,(1- avail-width))))))
1567 (setplist (gnugo-f (car pair)) (cdr pair)))))
1568 ;; mode line update
1569 (let ((cur (gnugo-get :mode-line)))
1570 (unless (equal cur gnugo-mode-line)
1571 (setq cur gnugo-mode-line)
1572 (gnugo-put :mode-line cur)
1573 (gnugo-put :mode-line-form
1574 (cond ((stringp cur)
1575 (setq cur (copy-sequence cur))
1576 (let (acc cut c)
1577 (while (setq cut (string-match "~[bwpmtu]" cur))
1578 (aset cur cut ?%)
1579 (setq c (aref cur (incf cut)))
1580 (aset cur cut ?s)
1581 (push
1582 `(,(intern (format "squig-%c" c))
1583 ,(case c
1584 (?b '(or (gnugo-get :black-captures) 0))
1585 (?w '(or (gnugo-get :white-captures) 0))
1586 (?p '(gnugo-current-player))
1587 (?t '(let ((ws (gnugo-get :waiting-start)))
1588 (if ws
1589 (cadr (time-since ws))
1590 "-")))
1591 (?u '(or (gnugo-get :last-waiting) "-"))
1592 (?m '(let ((tree (gnugo-get :sgf-gametree))
1593 (monkey (gnugo-get :monkey)))
1594 (gethash (car (aref monkey 0))
1595 (gnugo--tree-mnum tree)
1596 ;; should be unnecessary
1597 "?")))))
1598 acc))
1599 `(let ,(delete-dups (copy-sequence acc))
1600 (format ,cur ,@(reverse (mapcar 'car acc))))))
1601 (t cur))))
1602 (let ((form (gnugo-get :mode-line-form)))
1603 (setq mode-line-process
1604 (and form
1605 ;; this dynamicism is nice but excessive in its wantonness
1606 ;;- `(" [" (:eval ,form) "]")
1607 ;; this dynamicism is ok because the user triggers it
1608 (list (format " [%s]" (eval form))
1609 '(:eval (if (gnugo-get :abd)
1610 " Abd"
1611 ""))))))
1612 (force-mode-line-update))
1613 ;; last user move
1614 (when (setq last (gnugo-get :last-user-bpos))
1615 (gnugo-goto-pos last))))
1616
1617 (defun gnugo--finish-move (buf)
1618 (run-hooks 'gnugo-post-move-hook)
1619 (with-current-buffer buf
1620 (gnugo-refresh)))
1621
1622 ;;;---------------------------------------------------------------------------
1623 ;;; Game play actions
1624
1625 (defun gnugo--rename-buffer-portion (&optional back)
1626 (let ((old "to play")
1627 (new "waiting for suggestion"))
1628 (when back
1629 (rotatef old new))
1630 (let ((name (buffer-name)))
1631 (when (string-match old name)
1632 (rename-buffer (replace-match new t t name))))))
1633
1634 (defun gnugo-get-move-insertion-filter (proc string)
1635 (with-current-buffer (process-buffer proc)
1636 (let* ((so-far (gnugo-get :get-move-string))
1637 (full (gnugo-put :get-move-string (concat so-far string))))
1638 (when (string-match "^= \\(.+\\)\n\n" full)
1639 (setq full (match-string 1 full)) ; POS or "PASS"
1640 (destructuring-bind (color . suggestion)
1641 (gnugo-get :waiting)
1642 (gnugo--forget :get-move-string
1643 :waiting)
1644 (if suggestion
1645 (progn
1646 (gnugo--rename-buffer-portion t)
1647 (unless (or (gnugo--passp full)
1648 (eq 'nowarp suggestion))
1649 (gnugo-goto-pos full))
1650 (message "%sSuggestion for %s: %s"
1651 (gnugo-get :diamond)
1652 color full))
1653 (let* ((donep (gnugo-push-move color full))
1654 (buf (current-buffer)))
1655 (gnugo--finish-move buf)
1656 (when (gnugo-get :abd)
1657 (gnugo-put :abd
1658 (unless donep
1659 (run-at-time
1660 2 ;;; sec (frettoloso? dubioso!)
1661 nil (lambda (buf color)
1662 (with-current-buffer buf
1663 (gnugo-get-move color)))
1664 buf
1665 (gnugo-other color))))))))))))
1666
1667 (defun gnugo-get-move (color &optional suggestion)
1668 (gnugo-put :waiting (cons color suggestion))
1669 (gnugo--begin-exchange
1670 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1671 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1672 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1673 (concat "reg_genmove " color))
1674 (accept-process-output))
1675
1676 (defun gnugo-cleanup ()
1677 (when (gnugo-board-buffer-p)
1678 (unless (zerop (buffer-size))
1679 (message "Thank you for playing GNU Go."))
1680 (mapc (lambda (sym)
1681 (setplist sym nil) ; "...is next to fordliness." --Huxley
1682 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1683 ;; No worries, things will be Much Better w/ structs, RSN...
1684 (unintern sym nil))
1685 (append (gnugo-get :all-yy)
1686 (mapcar 'gnugo-f
1687 '(anim
1688 tpad
1689 gpad
1690 gspc
1691 lpad
1692 rpad
1693 ispc))))
1694 (setq gnugo-state nil)))
1695
1696 (defun gnugo-position ()
1697 (or (get-text-property (point) 'gnugo-position)
1698 (user-error "Not a proper position point")))
1699
1700 (defun gnugo-request-suggestion (&optional nowarp)
1701 "Request a move suggestion from GNU Go.
1702 After some time (during which you can do other stuff),
1703 Emacs displays the suggestion in the echo area and warps the
1704 cursor to the suggested position. Prefix arg inhibits warp."
1705 (interactive "P")
1706 (gnugo-gate t)
1707 (gnugo--rename-buffer-portion)
1708 (gnugo-get-move (gnugo-current-player)
1709 (if nowarp
1710 'nowarp
1711 t)))
1712
1713 (defun gnugo--user-play (pos-or-pass)
1714 (gnugo-gate t)
1715 ;; The "user" in this func's name used to signify both
1716 ;; who does the action and for whom the action is done.
1717 ;; Now, it signifies only the former.
1718 (let* ((gcolor (gnugo-get :gnugo-color))
1719 (userp (string= gcolor (gnugo-get :last-mover)))
1720 (donep (gnugo-push-move userp pos-or-pass))
1721 (buf (current-buffer)))
1722 (gnugo--finish-move buf)
1723 (when (and userp (not donep))
1724 (with-current-buffer buf
1725 (gnugo-get-move gcolor)))))
1726
1727 (defun gnugo-move ()
1728 "Make a move on the GNUGO Board buffer.
1729 The position is computed from current point.
1730 Signal error if done out-of-turn or if game-over.
1731 To start a game try M-x gnugo."
1732 (interactive)
1733 (gnugo--user-play (gnugo-position)))
1734
1735 (defun gnugo-mouse-move (e)
1736 "Do `gnugo-move' at mouse location."
1737 (interactive "@e")
1738 (mouse-set-point e)
1739 (when (memq (following-char) '(?. ?+))
1740 (gnugo-move)))
1741
1742 (defun gnugo-pass ()
1743 "Make a pass on the GNUGO Board buffer.
1744 Signal error if done out-of-turn or if game-over.
1745 To start a game try M-x gnugo."
1746 (interactive)
1747 (gnugo--user-play "PASS"))
1748
1749 (defun gnugo-mouse-pass (e)
1750 "Do `gnugo-pass' at mouse location."
1751 (interactive "@e")
1752 (mouse-set-point e)
1753 (gnugo-pass))
1754
1755 (defun gnugo-resign ()
1756 (interactive)
1757 (gnugo-gate t)
1758 (if (not (y-or-n-p "Resign? "))
1759 (message "(not resigning)")
1760 (gnugo-push-move t "resign")
1761 (gnugo-refresh)))
1762
1763 (defun gnugo-animate-group (w/d)
1764 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1765 (let* ((pos (gnugo-position))
1766 (orig-b-m-p (buffer-modified-p))
1767 blurb stones)
1768 (unless (memq (following-char) '(?X ?O))
1769 (user-error "No stone at %s" pos))
1770 (setq blurb (message "Computing %s stones ..." w/d)
1771 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1772 (message "%s %s in group." blurb (length stones))
1773 (setplist (gnugo-f 'anim) nil)
1774 (let* ((spec (if (gnugo-get :display-using-images)
1775 (loop with yin = (get-text-property (point) 'gnugo-yin)
1776 with yang = (gnugo-yang (following-char))
1777 with up = (get (gnugo-yy yin yang t) 'display)
1778 with dn = (get (gnugo-yy yin yang) 'display)
1779 for n below (length gnugo-animation-string)
1780 collect (if (zerop (logand 1 n))
1781 dn up))
1782 (split-string gnugo-animation-string "" t)))
1783 (cell (list spec))
1784 (ovs (save-excursion
1785 (mapcar (lambda (pos)
1786 (gnugo-goto-pos pos)
1787 (let* ((p (point))
1788 (ov (make-overlay p (1+ p))))
1789 (overlay-put ov 'category (gnugo-f 'anim))
1790 (overlay-put ov 'priority most-positive-fixnum)
1791 ov))
1792 stones))))
1793 (setplist (gnugo-f 'anim) (cons 'display cell))
1794 (while (and (cdr spec) ; let last linger lest levity lost
1795 (sit-for 0.08675309)) ; jenny jenny i got your number...
1796 (setcar cell (setq spec (cdr spec)))
1797 ;; Force redisplay of overlays.
1798 (set-buffer-modified-p orig-b-m-p))
1799 (sit-for 5)
1800 (mapc 'delete-overlay ovs)
1801 t)))
1802
1803 (defun gnugo-display-group-data (command buffer-name)
1804 (message "Computing %s ..." command)
1805 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1806 (switch-to-buffer buffer-name)
1807 (erase-buffer)
1808 (insert data))
1809 (message "Computing %s ... done." command))
1810
1811 (defun gnugo-worm-stones ()
1812 "In the GNUGO Board buffer, animate \"worm\" at current position.
1813 Signal error if done out-of-turn or if game-over.
1814 See variable `gnugo-animation-string' for customization."
1815 (interactive)
1816 (gnugo-gate)
1817 (gnugo-animate-group 'worm))
1818
1819 (defun gnugo-worm-data ()
1820 "Display in another buffer data from \"worm\" at current position.
1821 Signal error if done out-of-turn or if game-over."
1822 (interactive)
1823 (gnugo-gate)
1824 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1825
1826 (defun gnugo-dragon-stones ()
1827 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1828 Signal error if done out-of-turn or if game-over.
1829 See variable `gnugo-animation-string' for customization."
1830 (interactive)
1831 (gnugo-gate)
1832 (gnugo-animate-group 'dragon))
1833
1834 (defun gnugo-dragon-data ()
1835 "Display in another buffer data from \"dragon\" at current position.
1836 Signal error if done out-of-turn or if game-over."
1837 (interactive)
1838 (gnugo-gate)
1839 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1840
1841 (defun gnugo-estimate-score ()
1842 "Display estimated score of a game of GNU Go.
1843 Output includes number of stones on the board and number of stones
1844 captured by each player, and the estimate of who has the advantage (and
1845 by how many stones)."
1846 (interactive)
1847 (message "Est.score ...")
1848 (let ((black (gnugo--count-query "list_stones black"))
1849 (white (gnugo--count-query "list_stones white"))
1850 (black-captures (gnugo-query "captures black"))
1851 (white-captures (gnugo-query "captures white"))
1852 (est (gnugo-query "estimate_score")))
1853 ;; might as well update this
1854 (gnugo-put :black-captures black-captures)
1855 (gnugo-put :white-captures white-captures)
1856 (message "Est.score ... B %s %s | W %s %s | %s"
1857 black black-captures white white-captures est)))
1858
1859 (defun gnugo-write-sgf-file (filename)
1860 "Save the game history to FILENAME (even if unfinished).
1861 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1862 (interactive "FWrite game as SGF file: ")
1863 (when (and (file-exists-p filename)
1864 (not (y-or-n-p "File exists. Continue? ")))
1865 (user-error "Not writing %s" filename))
1866 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1867 (set-buffer-modified-p nil))
1868
1869 (defun gnugo--who-is-who (wait play samep)
1870 (message "GNU Go %splays as %s, you as %s (%s)"
1871 (if samep "" "now ")
1872 wait play (if samep
1873 "as before"
1874 "NOTE: this is a switch!")))
1875
1876 (defsubst gnugo--nodep (x)
1877 (keywordp (caar x)))
1878
1879 (defun gnugo--SZ! (size)
1880 (gnugo-put :SZ size)
1881 (gnugo-put :center-position
1882 (funcall (gnugo--as-pos-func)
1883 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1884 (string c c)))))
1885
1886 (defun gnugo--plant-and-climb (collection &optional sel)
1887 (gnugo-put :sgf-collection collection)
1888 (let ((tree (nth (or sel 0) collection)))
1889 (gnugo-put :sgf-gametree tree)
1890 (gnugo-put :monkey (vector
1891 ;; mem
1892 (aref (gnugo--tree-ends tree) 0)
1893 ;; bidx
1894 0))
1895 tree))
1896
1897 (defun gnugo-read-sgf-file (filename)
1898 "Load the first game tree from FILENAME, a file in SGF format."
1899 (interactive "fSGF file to load: ")
1900 (when (file-directory-p filename)
1901 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1902 (let (play wait samep coll tree game-over)
1903 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1904 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1905 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1906 wait (gnugo-other play)
1907 samep (string= (gnugo-get :user-color) play))
1908 (gnugo-put :last-mover wait)
1909 (unless samep
1910 (gnugo-put :gnugo-color wait)
1911 (gnugo-put :user-color play))
1912 (setq coll (gnugo/sgf-create filename)
1913 tree (gnugo--plant-and-climb
1914 coll (let ((n (length coll)))
1915 ;; This is better:
1916 ;; (if (= 1 n)
1917 ;; 0
1918 ;; (let* ((q (format "Which game? (1-%d)" n))
1919 ;; (choice (1- (read-number q 1))))
1920 ;; (if (and (< -1 choice) (< choice n))
1921 ;; choice
1922 ;; (message "(Selecting the first game)")
1923 ;; 0)))
1924 ;; but this is what we use (for now) to accomodate
1925 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1926 (unless (= 1 n)
1927 (message "(Selecting the first game)"))
1928 0)))
1929 ;; This is deliberately undocumented for now.
1930 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1931 (when (setq game-over (or (gnugo--root-prop :RE tree)
1932 (when (equal '("PASS" "PASS")
1933 (gnugo-move-history 'two))
1934 'two-passes)))
1935 (gnugo-close-game nil game-over))
1936 (gnugo-put :last-user-bpos
1937 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1938 (gnugo-refresh t)
1939 (set-buffer-modified-p nil)
1940 (gnugo--who-is-who wait play samep)))
1941
1942 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1943 (let ((color (case (following-char)
1944 (?X :B)
1945 (?O :W))))
1946 (if (not color)
1947 (unless noerror
1948 (user-error "No stone at %s" pos))
1949 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1950 for mem on (aref (gnugo-get :monkey) 0)
1951 when (equal fruit (caar mem))
1952 return mem
1953 finally return nil))))
1954
1955 (defun gnugo--climb-towards-root (spec &optional noalt keep)
1956 (gnugo-gate)
1957 (let* ((user-color (gnugo-get :user-color))
1958 (monkey (gnugo-get :monkey))
1959 (tree (gnugo-get :sgf-gametree))
1960 (ends (gnugo--tree-ends tree))
1961 (remorseful (not (gnugo--no-regrets monkey ends)))
1962 (stop (if (numberp spec)
1963 (nthcdr (if (zerop spec)
1964 (if (string= (gnugo-get :last-mover)
1965 user-color)
1966 1
1967 2)
1968 spec)
1969 (aref monkey 0))
1970 (let* ((pos (if (stringp spec)
1971 spec
1972 (gnugo-position)))
1973 (hmm (gnugo--mem-with-played-stone pos)))
1974 ;; todo: relax ‘gnugo--user-play’ then lift restriction
1975 (unless (eq (gnugo--prop<-color user-color)
1976 (car (gnugo--move-prop (car hmm))))
1977 (user-error "%s not occupied by %s"
1978 pos user-color))
1979 (cdr hmm)))))
1980 (when (gnugo-get :game-over)
1981 (gnugo--unclose-game))
1982 (while (not (eq stop (aref monkey 0)))
1983 (gnugo--q/ue "undo")
1984 (pop (aref monkey 0))
1985 (gnugo-put :last-mover (gnugo-current-player))
1986 (gnugo-merge-showboard-results) ; all
1987 (gnugo-refresh) ; this
1988 (redisplay)) ; eye candy
1989 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1990
1991 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1992 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1993 ubpos
1994 (gnugo-get :center-position)))
1995 (gnugo-refresh t)
1996 (unless (or keep remorseful)
1997 (aset ends (aref monkey 1) (aref monkey 0)))
1998 (when (and ulastp (not noalt))
1999 (gnugo-get-move (gnugo-get :gnugo-color))))))
2000
2001 (defun gnugo-undo-one-move (&optional me-next)
2002 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2003 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2004 Prefix arg ME-NEXT means to arrange for you to play
2005 the color of the next move (and GNU Go the opposite).
2006 This is useful after loading an SGF file whose last
2007 move was done by the color you prefer to play:
2008 \\[gnugo-read-sgf-file] FILENAME RET
2009 C-u \\[gnugo-undo-one-move]
2010
2011 See also `gnugo-undo-two-moves'."
2012 (interactive "P")
2013 (gnugo-gate)
2014 (when me-next
2015 (let* ((play (gnugo-get :last-mover))
2016 (wait (gnugo-other play)))
2017 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2018 (gnugo-put :user-color play)
2019 (gnugo-put :gnugo-color wait)))
2020 (gnugo--climb-towards-root 1 t))
2021
2022 (defun gnugo-undo-two-moves ()
2023 "Undo a pair of moves (GNU Go's and yours).
2024 However, if you are the last mover, undo only one move.
2025 Regardless, after undoing, it is your turn to play again."
2026 (interactive)
2027 (gnugo-gate)
2028 (gnugo--climb-towards-root 0))
2029
2030 (defun gnugo-oops (&optional position)
2031 "Like `gnugo-undo-two-moves', but keep the undone moves.
2032 The kept moves become a sub-gametree (variation) when play resumes.
2033 Prefix arg means, instead, undo repeatedly up to and including
2034 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2035 (interactive "P")
2036 (gnugo-gate)
2037 (gnugo--climb-towards-root (unless position
2038 0)
2039 nil t))
2040
2041 (defun gnugo-okay (&optional full)
2042 "Redo a pair of undone moves.
2043 Prefix arg means to redo all the undone moves."
2044 (interactive "P")
2045 (gnugo-gate)
2046 (let* ((tree (gnugo-get :sgf-gametree))
2047 (ends (gnugo--tree-ends tree))
2048 (monkey (gnugo-get :monkey)))
2049 (if (gnugo--no-regrets monkey ends)
2050 (message "Oop ack!")
2051 (let* ((as-pos (gnugo--as-pos-func))
2052 (mnum (gnugo--tree-mnum tree))
2053 (mem (aref monkey 0))
2054 (bidx (aref monkey 1))
2055 (end (aref ends bidx))
2056 (ucolor (gnugo-get :user-color))
2057 (uprop (gnugo--prop<-color ucolor)))
2058 (cl-flet ((mvno (node) (gethash node mnum)))
2059 (loop
2060 with ok = (if full
2061 (mvno (car end))
2062 (+ 2 (mvno (car mem))))
2063 with (node move todo)
2064 for ls on end
2065 do (progn
2066 (setq node (car ls)
2067 move (gnugo--move-prop node))
2068 (when (and move (>= ok (mvno node)))
2069 (let ((userp (eq uprop (car move))))
2070 (push (list userp
2071 (funcall as-pos (cdr move)))
2072 todo))))
2073 until (eq mem (cdr ls))
2074 finally do
2075 (loop
2076 for (userp pos) in todo
2077 do (progn
2078 (gnugo-push-move userp pos)
2079 (gnugo-refresh)
2080 (redisplay)))))))))
2081
2082 (defun gnugo-display-final-score (&optional comment)
2083 "Display final score and other info in another buffer (when game over).
2084 If the game is still ongoing, Emacs asks if you wish to stop play (by
2085 making sure two \"pass\" moves are played consecutively, if necessary).
2086 Also, add the `:RE' SGF property to the root node of the game tree.
2087 Prefix arg COMMENT means to also attach the text (slightly compacted)
2088 to the last move, as a comment."
2089 (interactive "P")
2090 (let ((game-over (gnugo-get :game-over)))
2091 (unless (or game-over
2092 (and (not (gnugo-get :waiting))
2093 (y-or-n-p "Game still in play. Stop play now? ")))
2094 (user-error "Sorry, game still in play"))
2095 (unless game-over
2096 (cl-flet
2097 ((pass (userp)
2098 (message "Playing PASS for %s ..."
2099 (gnugo-get (if userp :user-color :gnugo-color)))
2100 (sit-for 1)
2101 (gnugo-push-move userp "PASS")))
2102 (unless (pass t)
2103 (pass nil)))
2104 (gnugo-refresh)
2105 (sit-for 3)))
2106 (let ((b= " Black = ")
2107 (w= " White = ")
2108 (res (when (gnugo--resignp (gnugo-move-history 'car))
2109 (gnugo-get :last-mover)))
2110 blurb result)
2111 (if res
2112 (setq blurb (list
2113 (format "%s wins.\n"
2114 (substring (if (= ?b (aref res 0)) w= b=)
2115 3 8))
2116 "The game is over.\n"
2117 (format "Resignation by %s.\n" res))
2118 result (concat (upcase (substring (gnugo-other res) 0 1))
2119 "+Resign"))
2120 (message "Computing final score ...")
2121 (let* ((g-over (gnugo-get :game-over))
2122 (live (cdr (assq 'live g-over)))
2123 (dead (cdr (assq 'dead g-over)))
2124 (seed (gnugo-get :scoring-seed))
2125 (terr-q (format "final_status_list %%s_territory %d" seed))
2126 (terr "territory")
2127 (capt "captures")
2128 (b-terr (gnugo--count-query terr-q "black"))
2129 (w-terr (gnugo--count-query terr-q "white"))
2130 (b-capt (string-to-number (gnugo-get :black-captures)))
2131 (w-capt (string-to-number (gnugo-get :white-captures)))
2132 (komi (gnugo--root-prop :KM)))
2133 (setq blurb (list "The game is over. Final score:\n")
2134 result (gnugo-query "final_score %d" seed))
2135 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2136 (dolist (group live)
2137 (incf (if (gnugo--blackp (caar group))
2138 b-terr
2139 w-terr)
2140 (length (cdr group))))
2141 (dolist (group dead)
2142 (incf (if (gnugo--blackp (caar group))
2143 w-terr
2144 b-terr)
2145 (length (cdr group))))
2146 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2147 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2148 w-terr terr komi 'komi (+ w-terr komi))
2149 blurb))
2150 (t
2151 (dolist (group dead)
2152 (incf (if (gnugo--blackp (caar group))
2153 w-terr
2154 b-terr)
2155 (* 2 (length (cdr group)))))
2156 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2157 b-terr terr
2158 b-capt capt
2159 (+ b-terr b-capt))
2160 blurb)
2161 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2162 w-terr terr
2163 w-capt capt
2164 komi 'komi
2165 (+ w-terr w-capt komi))
2166 blurb)))
2167 (push (if (string= "0" result)
2168 "The game is a draw.\n"
2169 (format "%s wins by %s.\n"
2170 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2171 (substring result 2)))
2172 blurb)
2173 (message "Computing final score ... done")))
2174 ;; extra info
2175 (let ((beg (gnugo-get :game-start-time))
2176 (end (gnugo-get :game-end-time)))
2177 (when end
2178 (push "\n" blurb)
2179 (cl-flet
2180 ((yep (pretty moment)
2181 (push (format-time-string
2182 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2183 moment)
2184 blurb)))
2185 (yep "Game start" beg)
2186 (yep " end" end))))
2187 (setq blurb (apply 'concat (nreverse blurb)))
2188 (gnugo--set-root-prop :RE result)
2189 (when comment
2190 (let ((node (car (aref (gnugo-get :monkey) 0))))
2191 (gnugo--decorate
2192 (delq (assq :C node) node)
2193 (with-temp-buffer ; lame
2194 (insert blurb)
2195 (when (search-backward "\n\nGame start:" nil t)
2196 (delete-region (point) (point-max)))
2197 (cl-flet ((rep (old new)
2198 (goto-char (point-min))
2199 (while (search-forward old nil t)
2200 (replace-match new))))
2201 (rep "The game is over. " "")
2202 (rep "territory" "T")
2203 (rep "captures" "C")
2204 (rep "komi" "K"))
2205 `((:C . ,(buffer-string)))))))
2206 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2207 (erase-buffer)
2208 (insert blurb)))
2209
2210 (defun gnugo-quit ()
2211 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2212 If the game is not over, ask for confirmation first."
2213 (interactive)
2214 (if (or (gnugo-get :game-over)
2215 (y-or-n-p "Quit? "))
2216 (kill-buffer nil)
2217 (message "(not quitting)")))
2218
2219 (defun gnugo-leave-me-alone ()
2220 "Kill the current buffer unconditionally."
2221 (interactive)
2222 (kill-buffer nil))
2223
2224 (defun gnugo-fancy-undo (count)
2225 "Rewind the game tree in various ways.
2226 Prefix arg COUNT means to undo that many moves.
2227 Otherwise, undo repeatedly up to and including the move
2228 which placed the stone at point."
2229 (interactive "P")
2230 (gnugo--climb-towards-root
2231 (cond ((numberp count) count)
2232 ((consp count) (car count)))))
2233
2234 (defun gnugo-toggle-image-display-command () ; ugh
2235 "Toggle use of images to display the board, then refresh."
2236 (interactive)
2237 (gnugo-toggle-image-display)
2238 (save-excursion (gnugo-refresh)))
2239
2240 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2241 (car (gnugo--mem-with-played-stone pos noerror)))
2242
2243 (defun gnugo-describe-position ()
2244 "Display the board position under cursor in the echo area.
2245 If there a stone at that position, also display its move number."
2246 (interactive)
2247 (let* ((pos (gnugo-position)) ; do first (can throw)
2248 (node (gnugo--node-with-played-stone pos t)))
2249 (message
2250 "%s%s" pos
2251 (or (when node
2252 (let* ((tree (gnugo-get :sgf-gametree))
2253 (mnum (gnugo--tree-mnum tree))
2254 (move-num (gethash node mnum)))
2255 (format " (move %d)" move-num)))
2256 ""))))
2257
2258 (defun gnugo-switch-to-another ()
2259 "Switch to another GNU Go game buffer (if any)."
2260 (interactive)
2261 (loop for buf in (cdr (buffer-list))
2262 if (gnugo-board-buffer-p buf)
2263 return (progn
2264 (bury-buffer)
2265 (switch-to-buffer buf))
2266 finally do (message "(only one)")))
2267
2268 (defun gnugo-comment (node comment)
2269 "Add to NODE a COMMENT (string) property.
2270 Called interactively, NODE is the one corresponding to the
2271 stone at point, and any previous comment is inserted as the
2272 initial-input (see `read-string').
2273
2274 If COMMENT is nil or the empty string, remove the property entirely."
2275 (interactive
2276 (let* ((pos (gnugo-position))
2277 (node (gnugo--node-with-played-stone pos)))
2278 (list node
2279 (read-string (format "Comment for %s: "
2280 (gnugo-describe-position))
2281 (cdr (assq :C node))))))
2282 (setq node (delq (assq :C node) node))
2283 (unless (zerop (length comment))
2284 (gnugo--decorate node `((:C . ,comment)))))
2285
2286 (defun gnugo-toggle-abdication ()
2287 "Toggle abdication, i.e., letting GNU Go play for you.
2288 When enabled, the mode line includes \"Abd\".
2289 Enabling signals error if the game is over.
2290 When disabling, if GNU Go has already started thinking of
2291 a move to play for you, the thinking is not cancelled but instead
2292 transformed into a move suggestion (see `gnugo-request-suggestion')."
2293 (interactive)
2294 (let ((last-mover (gnugo-get :last-mover))
2295 (abd (gnugo-get :abd))
2296 xform)
2297 (if abd
2298 ;; disable
2299 (let* ((gcolor (gnugo-get :gnugo-color))
2300 (waiting (gnugo-get :waiting))
2301 (userp (string= last-mover gcolor)))
2302 (when (and userp waiting)
2303 (gnugo--rename-buffer-portion)
2304 (setcdr waiting (setq xform 'nowarp)))
2305 (when (timerp abd)
2306 (cancel-timer abd))
2307 (gnugo--forget :abd)
2308 (unless (or userp waiting)
2309 (gnugo-get-move gcolor)))
2310 ;; enable
2311 (gnugo-gate t)
2312 (gnugo-put :abd t)
2313 (gnugo-get-move (gnugo-other last-mover)))
2314 (message "Abdication %sabled%s"
2315 (if (gnugo-get :abd)
2316 "en"
2317 "dis")
2318 (if xform
2319 (format " (suggestion for %s forthcoming)"
2320 (gnugo-get :user-color))
2321 ""))
2322 (when xform
2323 (sleep-for 2))))
2324
2325 ;;;---------------------------------------------------------------------------
2326 ;;; Command properties and gnugo-command
2327
2328 ;; GTP commands entered by the user are never issued directly to GNU Go;
2329 ;; instead, their behavior and output are controlled by the property
2330 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2331 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2332 ;;
2333 ;; :full -- completely interpret the command string; the value is a
2334 ;; func that takes the list of words derived from splitting the
2335 ;; command string (minus the command) and handles everything.
2336 ;;
2337 ;; :output -- either a keyword specifying the preferred output method:
2338 ;; :message -- show output in minibuffer
2339 ;; :discard -- sometimes you just don't care;
2340 ;; or a function that takes one arg, the output string, and
2341 ;; handles it completely. default is to switch to buffer
2342 ;; "*gnugo command output*" if the output has a newline,
2343 ;; otherwise use `message'.
2344 ;;
2345 ;; :post-thunk -- run after output processing (at the very end).
2346
2347 (defun gnugo-command (command)
2348 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2349 Output and Emacs behavior depend on which command is given (some
2350 commands are handled completely by Emacs w/o using the subprocess;
2351 some commands have their output displayed in specially prepared
2352 buffers or in the echo area; some commands are instrumented to do
2353 gnugo.el-specific housekeeping).
2354
2355 For example, for the command \"help\", Emacs visits the
2356 GTP command reference info page.
2357
2358 NOTE: At this time, GTP command handling specification is still
2359 incomplete. Thus, some commands WILL confuse gnugo.el."
2360 (interactive "sCommand: ")
2361 (if (string= "" command)
2362 (message "(no command given)")
2363 (let* ((split (split-string command))
2364 (cmd (intern (car split)))
2365 (spec (get cmd :gnugo-gtp-command-spec))
2366 (full (plist-get spec :full)))
2367 (if full
2368 (funcall full (cdr split))
2369 (message "Doing %s ..." command)
2370 (let* ((ans (gnugo--q command))
2371 (where (plist-get spec :output)))
2372 (if (string-match "unknown.command" ans)
2373 (message "%s" ans)
2374 (cond ((functionp where) (funcall where ans))
2375 ((eq :discard where) (message ""))
2376 ((or (eq :message where)
2377 (not (string-match "\n" ans)))
2378 (message "%s" ans))
2379 (t (switch-to-buffer "*gnugo command output*")
2380 (erase-buffer)
2381 (insert ans)
2382 (message "Doing %s ... done." command)))
2383 (let ((thunk (plist-get spec :post-thunk)))
2384 (when thunk (funcall thunk)))))))))
2385
2386 ;;;---------------------------------------------------------------------------
2387 ;;; Major mode for interacting with a GNUGO subprocess
2388
2389 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2390 "Major mode for playing GNU Go.
2391 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2392 In this mode, keys do not self insert.
2393
2394 \\{gnugo-board-mode-map}"
2395 (buffer-disable-undo) ; todo: undo undo undoing
2396 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2397 truncate-lines t)
2398 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2399 (set (make-local-variable 'gnugo-state)
2400 (gnugo--mkht :size (1- 42)))
2401 (gnugo-put :highlight-last-move-spec
2402 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2403 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2404 (let ((ov (make-overlay 1 1)))
2405 (overlay-put ov 'display ")")
2406 ov)))
2407 (gnugo-put :mul '(1 . 1))
2408 (add-to-invisibility-spec :nogrid))
2409
2410 ;;;---------------------------------------------------------------------------
2411 ;;; Entry point
2412
2413 ;;;###autoload
2414 (defun gnugo (&optional new-game)
2415 "Run gnugo in a buffer, or resume a game in progress.
2416 If there is already a game in progress you may resume it instead
2417 of starting a new one. Prefix arg means skip the game-in-progress
2418 check and start a new game straight away.
2419
2420 Before starting, Emacs queries you for additional command-line
2421 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2422
2423 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2424 silently clobbers certain other options, such as \"--color\".
2425 For details, see info node `(gnugo) Invoking GNU Go'.
2426
2427 \\<gnugo-board-mode-map>
2428 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2429 See `gnugo-board-mode' for a full list of commands."
2430 (interactive "P")
2431 (let* ((all (let (acc)
2432 (dolist (buf (buffer-list))
2433 (when (gnugo-board-buffer-p buf)
2434 (push (cons (buffer-name buf) buf) acc)))
2435 acc))
2436 (n (length all)))
2437 (if (and (not new-game)
2438 (cl-plusp n)
2439 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2440 (if (= 1 n) "" "s"))))
2441 ;; resume
2442 (switch-to-buffer
2443 (cdr (if (= 1 n)
2444 (car all)
2445 (let ((sel (completing-read "Which one? " all nil t)))
2446 (if (string= "" sel)
2447 (car all)
2448 (assoc sel all))))))
2449 ;; sanity check
2450 (unless (executable-find gnugo-program)
2451 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2452 ;; set up a new board
2453 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2454 (gnugo-board-mode)
2455 (let* ((filename nil)
2456 (user-color "black")
2457 (args (loop
2458 with ls = (split-string
2459 ;; todo: grok ‘gnugo --help’; completion
2460 (read-string
2461 "GNU Go options: "
2462 (car gnugo-option-history)
2463 'gnugo-option-history))
2464 with ok
2465 while ls do
2466 (let ((arg (pop ls)))
2467 (cl-flet
2468 ((ex (opt fn)
2469 (if filename
2470 (warn "%s %s ignored" opt fn)
2471 (setq filename fn))))
2472 (cond
2473 ((string= "--color" arg)
2474 (push arg ok)
2475 (push
2476 ;; Unfortunately, GTP does not provide
2477 ;; a way to query the user color, so
2478 ;; we must resort to this weirdness.
2479 (setq user-color
2480 (pop ls))
2481 ok))
2482 ((string= "--infile" arg)
2483 (ex "--infile" (pop ls)))
2484 ((string-match "^-l" arg)
2485 (ex "-l" (if (< 2 (length arg))
2486 (substring arg 2)
2487 (pop ls))))
2488 (t (push arg ok)))))
2489 finally return (nreverse ok)))
2490 (proc (apply 'start-process "gnugo"
2491 (current-buffer)
2492 gnugo-program
2493 "--mode" "gtp" "--quiet"
2494 args))
2495 root board-size handicap komi)
2496 (gnugo-put :user-color user-color)
2497 (gnugo-put :proc proc)
2498 (set-process-sentinel proc 'gnugo-sentinel)
2499 ;; Emacs is too protective sometimes, blech.
2500 (set-process-query-on-exit-flag proc nil)
2501 (gnugo-put :diamond (substring (process-name proc) 5))
2502 (gnugo-put :gnugo-color (gnugo-other user-color))
2503 (if filename
2504 (gnugo-read-sgf-file (expand-file-name filename))
2505 (cl-flet
2506 ((r! (&rest plist)
2507 (gnugo--decorate
2508 root (loop ; hmm, available elsewhere?
2509 while plist
2510 collect (let* ((k (pop plist))
2511 (v (pop plist)))
2512 (cons k v))))))
2513 (gnugo--SZ!
2514 (setq root (gnugo--root-node
2515 (gnugo--plant-and-climb
2516 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2517 komi (gnugo--nquery "get_komi")
2518 handicap (gnugo--nquery "get_handicap")
2519 board-size (gnugo--nquery "query_boardsize")))
2520 (r! :SZ board-size
2521 :DT (format-time-string "%Y-%m-%d")
2522 :RU (if (member "--chinese-rules" args)
2523 "Chinese"
2524 "Japanese")
2525 :AP (cons "gnugo.el" gnugo-version)
2526 :KM komi)
2527 (let ((ub (gnugo--blackp user-color)))
2528 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2529 (if ub :PB :PW) (user-full-name)))
2530 (unless (zerop handicap)
2531 (r! :HA handicap
2532 :AB (mapcar (gnugo--as-cc-func)
2533 (gnugo-lsquery "fixed_handicap %d"
2534 handicap)))))))
2535 (gnugo-put :waiting-start (current-time))
2536 (gnugo-refresh t)
2537 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2538 (gnugo-get :center-position)))
2539 ;; first move
2540 (gnugo-put :game-start-time (current-time))
2541 (let ((g (gnugo-get :gnugo-color))
2542 (n (or (gnugo--root-prop :HA) 0))
2543 (u (gnugo-get :user-color)))
2544 (unless (gnugo-get :last-mover)
2545 (gnugo-put :last-mover
2546 (if (or (and (gnugo--blackp u) (< 1 n))
2547 (and (gnugo--blackp g) (< n 2)))
2548 u
2549 g)))
2550 (run-hooks 'gnugo-start-game-hook)
2551 (when (and (not (gnugo-get :game-over))
2552 (string= g (gnugo-current-player)))
2553 (gnugo-refresh t)
2554 (gnugo-get-move g))))))
2555
2556 ;;;---------------------------------------------------------------------------
2557 ;;; Load-time actions
2558
2559 (unless gnugo-frolic-mode-map
2560 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2561 (suppress-keymap gnugo-frolic-mode-map)
2562 (mapc (lambda (pair)
2563 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2564 '(("q" . gnugo-frolic-quit)
2565 ("Q" . gnugo-frolic-quit)
2566 ("\C-q" . gnugo-frolic-quit)
2567 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2568 ("\C-b" . gnugo-frolic-backward-branch)
2569 ("\C-f" . gnugo-frolic-forward-branch)
2570 ("\C-p" . gnugo-frolic-previous-move)
2571 ("\C-n" . gnugo-frolic-next-move)
2572 ("j" . gnugo-frolic-exchange-left)
2573 ("J" . gnugo-frolic-rotate-left)
2574 ("k" . gnugo-frolic-exchange-right)
2575 ("K" . gnugo-frolic-rotate-right)
2576 ("\C-m" . gnugo-frolic-set-as-main-line)
2577 ("\C-\M-p" . gnugo-frolic-prune-branch)
2578 ("o" . gnugo-frolic-return-to-origin))))
2579
2580 (unless gnugo-board-mode-map
2581 (setq gnugo-board-mode-map (make-sparse-keymap))
2582 (suppress-keymap gnugo-board-mode-map)
2583 (mapc (lambda (pair)
2584 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2585 '(("?" . describe-mode)
2586 ("S" . gnugo-request-suggestion)
2587 ("\C-m" . gnugo-move)
2588 (" " . gnugo-move)
2589 ("P" . gnugo-pass)
2590 ("R" . gnugo-resign)
2591 ("q" . gnugo-quit)
2592 ("Q" . gnugo-leave-me-alone)
2593 ("U" . gnugo-fancy-undo)
2594 ("\M-u" . gnugo-undo-one-move)
2595 ("u" . gnugo-undo-two-moves)
2596 ("\C-?" . gnugo-undo-two-moves)
2597 ("o" . gnugo-oops)
2598 ("O" . gnugo-okay)
2599 ("\C-l" . gnugo-refresh)
2600 ("\M-_" . gnugo-boss-is-near)
2601 ("_" . gnugo-boss-is-near)
2602 ("h" . gnugo-move-history)
2603 ("L" . gnugo-frolic-in-the-leaves)
2604 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2605 ("i" . gnugo-toggle-image-display-command)
2606 ("w" . gnugo-worm-stones)
2607 ("W" . gnugo-worm-data)
2608 ("d" . gnugo-dragon-stones)
2609 ("D" . gnugo-dragon-data)
2610 ("g" . gnugo-toggle-grid)
2611 ("!" . gnugo-estimate-score)
2612 (":" . gnugo-command)
2613 (";" . gnugo-command)
2614 ("=" . gnugo-describe-position)
2615 ("s" . gnugo-write-sgf-file)
2616 ("\C-x\C-s" . gnugo-write-sgf-file)
2617 ("\C-x\C-w" . gnugo-write-sgf-file)
2618 ("l" . gnugo-read-sgf-file)
2619 ("F" . gnugo-display-final-score)
2620 ("A" . gnugo-switch-to-another)
2621 ("C" . gnugo-comment)
2622 ("\C-c\C-a" . gnugo-toggle-abdication)
2623 ;; mouse
2624 ([(down-mouse-1)] . gnugo-mouse-move)
2625 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2626 ([(down-mouse-3)] . gnugo-mouse-pass)
2627 ;; delving into the curiosities
2628 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2629
2630 (unless (get 'help :gnugo-gtp-command-spec)
2631 (cl-flet*
2632 ((sget (x) (get x :gnugo-gtp-command-spec))
2633 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2634 (plist-put (sget cmd) prop val)))
2635 (validpos (s &optional go)
2636 (let ((pos (upcase s)))
2637 (loop with size = (gnugo-get :SZ)
2638 for c across (funcall (gnugo--as-cc-func)
2639 pos)
2640 do (let ((norm (- c ?a)))
2641 (unless (and (< -1 norm)
2642 (> size norm))
2643 (user-error "Invalid position: %s"
2644 pos))))
2645 (when go
2646 (gnugo-goto-pos pos))
2647 pos))
2648 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2649 (let ((ls props))
2650 (while ls
2651 (jam cmd (car ls) (cadr ls))
2652 (setq ls (cddr ls)))))))
2653 (cl-macrolet ((deffull (who &body body)
2654 (declare (indent 1))
2655 `(defgtp ',who :full (lambda (sel)
2656 ,@body))))
2657
2658 (deffull help
2659 (info "(gnugo)GTP command reference")
2660 (when sel (setq sel (intern (car sel))))
2661 (let (buffer-read-only pad cur spec output found)
2662 (cl-flet
2663 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2664 (goto-char (point-min))
2665 (save-excursion
2666 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2667 (point-max) t)
2668 (unless pad
2669 (setq pad (make-string (- (match-beginning 1)
2670 (match-beginning 0))
2671 32)))
2672 (when (plist-get
2673 (setq spec
2674 (get (setq cur (intern (match-string 1)))
2675 :gnugo-gtp-command-spec))
2676 :full)
2677 (note "handles this command completely"))
2678 (when (setq output (plist-get spec :output))
2679 (if (functionp output)
2680 (note "handles the output specially")
2681 (case output
2682 (:discard (note "discards the output"))
2683 (:message (note "displays the output in the echo area")))))
2684 (when (eq sel cur)
2685 (setq found (match-beginning 0))))))
2686 (cond (found (goto-char found))
2687 ((not sel))
2688 (t (message "(no such command: %s)" sel)))))
2689
2690 (deffull final_score
2691 ;; Explicit ignorance avoids byte-compiler warning.
2692 (ignore sel)
2693 (gnugo-display-final-score))
2694
2695 (defgtp '(boardsize
2696 clear_board
2697 fixed_handicap)
2698 :output :discard
2699 :post-thunk (lambda ()
2700 (gnugo--unclose-game)
2701 (gnugo--forget :last-mover)
2702 ;; ugh
2703 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2704 (gnugo-refresh t)))
2705
2706 (deffull loadsgf
2707 (gnugo-read-sgf-file (car sel)))
2708
2709 (deffull (undo gg-undo)
2710 (gnugo--climb-towards-root
2711 (let (n)
2712 (cond ((not sel) 1)
2713 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2714 (t (validpos (car sel) t)))))))))
2715
2716 (provide 'gnugo)
2717
2718 \f
2719 ;;;---------------------------------------------------------------------------
2720 ;;; The remainder of this file defines a simplified SGF-handling library.
2721 ;;; When/if it should start to attain generality, it should be split off into
2722 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2723 ;;; "gnugo/" prefix.
2724
2725 (defconst gnugo/sgf-*r4-properties*
2726 '((AB "Add Black" setup list stone)
2727 (AE "Add Empty" game list point)
2728 (AN "Annotation" game simpletext)
2729 (AP "Application" root (simpletext . simpletext))
2730 (AR "Arrow" - list (point . point))
2731 (AS "Who adds stones" - simpletext) ; (LOA)
2732 (AW "Add White" setup list stone)
2733 (B "Black" move move)
2734 (BL "Black time left" move real)
2735 (BM "Bad move" move double)
2736 (BR "Black rank" game simpletext)
2737 (BT "Black team" game simpletext)
2738 (C "Comment" - text)
2739 (CA "Charset" root simpletext)
2740 (CP "Copyright" game simpletext)
2741 (CR "Circle" - list point)
2742 (DD "Dim points" - elist point) ; (inherit)
2743 (DM "Even position" - double)
2744 (DO "Doubtful" move none)
2745 (DT "Date" game simpletext)
2746 (EV "Event" game simpletext)
2747 (FF "Fileformat" root [number (1 . 4)])
2748 (FG "Figure" - (or none (number . simpletext)))
2749 (GB "Good for Black" - double)
2750 (GC "Game comment" game text)
2751 (GM "Game" root [number (1 . 20)])
2752 (GN "Game name" game simpletext)
2753 (GW "Good for White" - double)
2754 (HA "Handicap" game number) ; (Go)
2755 (HO "Hotspot" - double)
2756 (IP "Initial pos." game simpletext) ; (LOA)
2757 (IT "Interesting" move none)
2758 (IY "Invert Y-axis" game simpletext) ; (LOA)
2759 (KM "Komi" game real) ; (Go)
2760 (KO "Ko" move none)
2761 (LB "Label" - list (point . simpletext))
2762 (LN "Line" - list (point . point))
2763 (MA "Mark" - list point)
2764 (MN "set move number" move number)
2765 (N "Nodename" - simpletext)
2766 (OB "OtStones Black" move number)
2767 (ON "Opening" game text)
2768 (OT "Overtime" game simpletext)
2769 (OW "OtStones White" move number)
2770 (PB "Player Black" game simpletext)
2771 (PC "Place" game simpletext)
2772 (PL "Player to play" setup color)
2773 (PM "Print move mode" - number) ; (inherit)
2774 (PW "Player White" game simpletext)
2775 (RE "Result" game simpletext)
2776 (RO "Round" game simpletext)
2777 (RU "Rules" game simpletext)
2778 (SE "Markup" - point) ; (LOA)
2779 (SL "Selected" - list point)
2780 (SO "Source" game simpletext)
2781 (SQ "Square" - list point)
2782 (ST "Style" root [number (0 . 3)])
2783 (SU "Setup type" game simpletext) ; (LOA)
2784 (SZ "Size" root (or number (number . number)))
2785 (TB "Territory Black" - elist point) ; (Go)
2786 (TE "Tesuji" move double)
2787 (TM "Timelimit" game real)
2788 (TR "Triangle" - list point)
2789 (TW "Territory White" - elist point) ; (Go)
2790 (UC "Unclear pos" - double)
2791 (US "User" game simpletext)
2792 (V "Value" - real)
2793 (VW "View" - elist point) ; (inherit)
2794 (W "White" move move)
2795 (WL "White time left" move real)
2796 (WR "White rank" game simpletext)
2797 (WT "White team" game simpletext)
2798 (LT "Lose on time" setup simpletext))
2799 ;; r4-specific notes
2800 ;; - changed: DT FG LB RE RU SZ
2801 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2802 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2803
2804 (defun gnugo/sgf-create (file-or-data &optional data-p)
2805 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2806 FILE-OR-DATA is a file name or SGF[4] data.
2807 Optional arg DATA-P non-nil means FILE-OR-DATA is
2808 a string containing SGF[4] data.
2809 A collection is a list of gametrees, each a vector of four elements:
2810
2811 ENDS -- a vector of node lists, with shared tails
2812 (last element of all the lists is the root node)
2813
2814 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2815 have a move number of the previous \"move\" node (or zero)
2816
2817 ROOT -- the root node"
2818 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2819 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2820 (put 'gnugo/sgf-*r4-properties* :keywords
2821 (mapcar (lambda (full)
2822 (cons (car full)
2823 (intern (format ":%s" (car full)))))
2824 gnugo/sgf-*r4-properties*))))
2825 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2826 (put 'gnugo/sgf-*r4-properties* :specs
2827 (mapcar (lambda (full)
2828 (cons (car full) (cdddr full)))
2829 gnugo/sgf-*r4-properties*))))
2830 SZ)
2831 (cl-labels
2832 ((sw () (skip-chars-forward " \t\n"))
2833 (x (end preserve-whitespace)
2834 (let ((beg (point))
2835 (endp (case end
2836 (:end (lambda (char) (= ?\] char)))
2837 (:mid (lambda (char) (= ?\: char)))
2838 (t (lambda (char) (or (= ?\: char)
2839 (= ?\] char))))))
2840 c)
2841 (while (not (funcall endp (setq c (following-char))))
2842 (cond ((= ?\\ c)
2843 (delete-char 1)
2844 (if (eolp)
2845 (kill-line 1)
2846 (forward-char 1)))
2847 ((unless preserve-whitespace
2848 (looking-at "\\s-+"))
2849 (delete-region (point) (match-end 0))
2850 (insert " "))
2851 (t (forward-char 1))))
2852 (buffer-substring-no-properties beg (point))))
2853 (one (type end) (let ((s (progn
2854 (forward-char 1)
2855 (x end (eq 'text type)))))
2856 (case type
2857 ((stone point move)
2858 ;; blech, begone bu"tt"-ugly blatherings
2859 ;; (but bide brobdingnagian boards)...
2860 (if (and (string= "tt" s)
2861 SZ
2862 (>= 19 SZ))
2863 ""
2864 s))
2865 ((simpletext color) s)
2866 ((number real double) (string-to-number s))
2867 ((text) s)
2868 ((none) "")
2869 (t (error "Unhandled type: %S" type)))))
2870 (val (spec) (cond ((symbolp spec)
2871 (one spec :end))
2872 ((vectorp spec)
2873 ;; todo: check range here.
2874 (one (aref spec 0) :end))
2875 ((eq 'or (car spec))
2876 (let ((v (one (cadr spec) t)))
2877 (if (= ?\] (following-char))
2878 v
2879 (forward-char 1)
2880 ;; todo: this assumes `spec' has the form
2881 ;; (or foo (foo . bar))
2882 ;; i.e., foo is not rescanned. e.g., `SZ'.
2883 ;; probably this assumption is consistent
2884 ;; w/ the SGF authors' desire to make the
2885 ;; parsing easy, but you never know...
2886 (cons v (one (cdaddr spec) :end)))))
2887 (t (cons (one (car spec) :mid)
2888 (one (cdr spec) :end)))))
2889 (short (who) (when (eobp)
2890 (error "Unexpected EOF while reading %s" who)))
2891 (atvalp () (= ?\[ (following-char)))
2892 (PROP () (let (name spec ltype)
2893 (sw) (short 'property)
2894 (when (looking-at "[A-Z]")
2895 (setq name (read (current-buffer))
2896 spec (cdr (assq name specs)))
2897 (sw)
2898 (cons
2899 (cdr (assq name keywords))
2900 (prog1 (if (= 1 (length spec))
2901 (val (car spec))
2902 (unless (memq (setq ltype (car spec))
2903 '(elist list))
2904 (error "Bad spec: %S" spec))
2905 (if (and (eq 'elist ltype) (sw)
2906 (not (atvalp)))
2907 nil
2908 (let ((type (cadr spec))
2909 mo ls)
2910 (while (and (sw) (atvalp)
2911 (setq mo (val type)))
2912 (push mo ls)
2913 (forward-char 1))
2914 (forward-char -1)
2915 (nreverse ls))))
2916 (forward-char 1))))))
2917 (morep () (and (sw) (not (eobp))))
2918 (seek (c) (and (morep) (= c (following-char))))
2919 (seek-into (c) (when (seek c)
2920 (forward-char 1)
2921 t))
2922 (NODE () (when (seek-into ?\;)
2923 (loop with prop
2924 while (setq prop (PROP))
2925 collect (progn
2926 (when (eq :SZ (car prop))
2927 (setq SZ (cdr prop)))
2928 prop))))
2929 (TREE (parent mnum)
2930 (let ((ls parent)
2931 prev node)
2932 (seek-into ?\()
2933 (while (seek ?\;)
2934 (setq prev (car ls)
2935 node (NODE))
2936 (puthash node (+ (if (gnugo--move-prop node)
2937 1
2938 0)
2939 (gethash prev mnum 0))
2940 mnum)
2941 (push node
2942 ls))
2943 (prog1
2944 (if (not (seek ?\())
2945 ;; singular
2946 (list ls)
2947 ;; multiple
2948 (loop while (seek ?\()
2949 append (TREE ls mnum)))
2950 (seek-into ?\))))))
2951 (with-temp-buffer
2952 (if (not data-p)
2953 (insert-file-contents file-or-data)
2954 (insert file-or-data)
2955 (goto-char (point-min)))
2956 (loop while (morep)
2957 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2958 (ends (TREE nil mnum))
2959 (root (car (last (car ends)))))
2960 (vector (apply 'vector ends)
2961 mnum
2962 root)))))))
2963
2964 (defun gnugo/sgf-write-file (collection filename)
2965 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2966 (me (cons "gnugo.el" gnugo-version))
2967 (specs (mapcar (lambda (full)
2968 (cons (intern (format ":%s" (car full)))
2969 (cdddr full)))
2970 gnugo/sgf-*r4-properties*))
2971 p name v spec)
2972 (cl-labels
2973 ((esc (composed fmt arg)
2974 (mapconcat (lambda (c)
2975 (case c
2976 ;; ‘?\[’ is not strictly required
2977 ;; but neither is it forbidden.
2978 ((?\[ ?\] ?\\) (format "\\%c" c))
2979 (?: (concat (if composed "\\" "") ":"))
2980 (t (string c))))
2981 (string-to-list (format fmt arg))
2982 ""))
2983 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2984 (>>two (v) (insert "["
2985 (esc t "%s" (car v))
2986 ":"
2987 (esc t "%s" (cdr v))
2988 "]"))
2989 (>>nl () (cond ((memq name aft-newline-appreciated)
2990 (insert "\n"))
2991 ((< 60 (current-column))
2992 (save-excursion
2993 (goto-char p)
2994 (insert "\n")))))
2995 (>>prop (prop)
2996 (setq p (point)
2997 name (car prop)
2998 v (cdr prop))
2999 (insert (substring (symbol-name name) 1))
3000 (cond ((not v))
3001 ((and (consp v)
3002 (setq spec (cdr (assq name specs)))
3003 (memq (car spec)
3004 '(list elist)))
3005 (>>nl)
3006 (let ((>> (if (consp (cadr spec))
3007 #'>>two
3008 #'>>one)))
3009 (dolist (little-v v)
3010 (setq p (point))
3011 (funcall >> little-v)
3012 (>>nl))))
3013 ((consp v)
3014 (>>two v) (>>nl))
3015 (t
3016 (>>one v) (>>nl))))
3017 (>>node (node)
3018 (loop initially (insert ";")
3019 for prop in node
3020 do (>>prop prop)))
3021 (>>tree (tree)
3022 (unless (zerop (current-column))
3023 (newline))
3024 (insert "(")
3025 (dolist (x tree)
3026 (funcall (if (gnugo--nodep x)
3027 #'>>node
3028 #'>>tree)
3029 x))
3030 (insert ")")))
3031 (with-temp-buffer
3032 (dolist (tree collection)
3033 ;; take responsibility for our actions
3034 (gnugo--set-root-prop :AP me tree)
3035 ;; write it out
3036 (let ((ht (gnugo--mkht))
3037 (leaves (append (gnugo--tree-ends tree) nil)))
3038 (cl-flet
3039 ((hang (stack)
3040 (loop
3041 with rh ; rectified history
3042 with bp ; branch point
3043 for node in stack
3044 until (setq bp (gethash node ht))
3045 do (puthash node
3046 (push node rh) ; good for now: ½τ
3047 ht)
3048 finally return
3049 (if (not bp)
3050 ;; first run: main line
3051 rh
3052 ;; subsequent runs: grafts (value discarded)
3053 (setcdr bp (nconc
3054 ;; Maintain order of ‘leaves’.
3055 (let ((was (cdr bp)))
3056 (if (gnugo--nodep (car was))
3057 (list was)
3058 was))
3059 (list rh)))))))
3060 (setq tree (hang (pop leaves)))
3061 (mapc #'hang leaves)
3062 (>>tree tree))))
3063 (newline)
3064 (write-file filename)))))
3065
3066 ;;; gnugo.el ends here