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