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