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