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