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