1 ;;; gnugo.el --- play GNU Go in a buffer
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
26 ;; This file provides the command `gnugo' which allows you to play the game of
27 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
28 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
29 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
30 ;; Go" to refer to the process object created by running the external program.
32 ;; At the start of a new game, you can pass additional command-line arguments
33 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
34 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
35 ;; both komi and handicap.
37 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
38 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
39 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
40 ;; back through an arbitrary stone that you played, place the cursor on a
41 ;; stone and type `U' (note: uppercase). Other keybindings are described in
42 ;; the `gnugo-board-mode' documentation, which you may view with the command
43 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
44 ;; the last move and who is currently to play. Capture counts and other info
45 ;; are shown on the mode line immediately following the major mode name.
47 ;; While GNU Go is pondering its next move, certain commands that rely on its
48 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
49 ;; is normal. When it is your turn again you may retry the command. In the
50 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
51 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
53 ;; If GNU Go should crash during a game the mode line will show "no process".
54 ;; Please report the event to the GNU Go maintainers so that they can improve
58 ;; Meta-Playing (aka Customizing)
59 ;; ------------------------------
61 ;; Customization is presently limited to
62 ;; vars: `gnugo-program'
63 ;; `gnugo-animation-string'
65 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
67 ;; normal hooks: `gnugo-board-mode-hook'
68 ;; `gnugo-post-move-hook'
69 ;; and the keymap: `gnugo-board-mode-map'
71 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
72 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
77 (eval-when-compile (require 'cl)) ; use the source luke!
78 (require 'time-date) ; for `time-subtract'
80 ;;;---------------------------------------------------------------------------
83 (defconst gnugo-version "2.3.1"
84 "Version of gnugo.el currently loaded.
85 This follows a MAJOR.MINOR.PATCH scheme.")
87 ;;;---------------------------------------------------------------------------
88 ;;; Variables for the uninquisitive programmer
90 (defvar gnugo-program "gnugo"
91 "Command to start an external program that speaks GTP, such as \"gnugo\".
92 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
93 the command `gnugo' will prefix OPTIONS in its default offering when it
94 queries you for additional options. It is an error for \"--mode\" to appear
97 For more information on GTP and GNU Go, feel free to visit:
98 http://www.gnu.org/software/gnugo")
100 (defvar gnugo-board-mode-map nil
101 "Keymap for GNUGO Board mode.")
103 (defvar gnugo-board-mode-hook nil
104 "Hook run when entering GNUGO Board mode.")
106 (defvar gnugo-inhibit-refresh nil
107 "Used in `gnugo-post-move-hook'.")
109 (defvar gnugo-post-move-hook nil
110 "Normal hook run after a move and before the board is refreshed.
111 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
112 (setq gnugo-inhibit-refresh t)
113 Initially, when `run-hooks' is called, the current buffer is the GNUGO
114 Board buffer of the game. Hook functions that switch buffers must take
115 care not to call (directly or indirectly through some other function)
116 `gnugo-put' or `gnugo-get' after the switch.")
118 (defvar gnugo-animation-string
119 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
120 (concat jam jam jam jam jam
121 ;; "SECRET MESSAGE HERE"
122 blink blink blink blink blink blink blink blink
123 ;; Playing go is like fighting ignorance: when you think you have
124 ;; surrounded something by knowing it very well it often turns
125 ;; out that in the time you spent deepening this understanding,
126 ;; other areas of ignorance have surrounded you.
127 spin spin spin spin spin spin spin spin spin
128 ;; Playing go is not like fighting ignorance: what one person
129 ;; knows many people may come to know; knowledge does not build
130 ;; solely move by move. Wisdom, on the other hand...
132 "String whose individual characters are used for animation.
133 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
134 render the stones in their respective result groups as the first character
135 in the string, then the next, and so on.")
137 (defvar gnugo-mode-line "~b ~w :~m :~u"
138 "A `mode-line-format'-compliant value for GNUGO Board mode.
139 If a single string, the following special escape sequences are
140 replaced with their associated information:
141 ~b,~w black,white captures (a number)
142 ~p current player (black or white)
144 ~t time waiting for the current move
145 ~u time taken for the Ultimate (most recent) move
146 The times are in seconds, or \"-\" if that information is not available.
147 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
149 (defvar gnugo-X-face 'font-lock-string-face
150 "Name of face to use for X (black) stones.")
152 (defvar gnugo-O-face 'font-lock-builtin-face
153 "Name of face to use for O (white) stones.")
155 (defvar gnugo-grid-face 'default
156 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
158 ;;;---------------------------------------------------------------------------
159 ;;; Variables for the inquisitive programmer
161 (defconst gnugo-font-lock-keywords
162 '(("X" . gnugo-X-face)
163 ("O" . gnugo-O-face))
164 "Font lock keywords for `gnugo-board-mode'.")
166 (defvar gnugo-option-history nil)
168 (defvar gnugo-state nil) ; hint: C-c C-p
171 (defvar gnugo-xpms nil))
173 ;;;---------------------------------------------------------------------------
174 ;;; Support functions
176 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
177 (compare-strings s1 beg1 nil s2 beg2 nil))
179 (defun gnugo-put (key value)
180 "Associate move/game/board-specific property KEY with VALUE.
182 There are many properties, each named by a keyword, that record and control
183 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
184 of properties, stored in the hash table `gnugo-state'. Here we document
185 some of the more stable properties. You may wish to use them as part of
186 a `gnugo-post-move-hook' function, for example. Be careful to preserve
187 the current buffer as `gnugo-state' is made into a buffer-local variable.
188 NOTE: In the following, \"see foo\" actually means \"see foo source or
189 you may never really understand to any degree of personal satisfaction\".
191 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
193 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
195 :game-over -- nil until game over at which time its value is set to
196 the alist `((live GROUP ...) (dead GROUP ...))'
198 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
199 a simple list of one or more gametrees, updated in
200 conjunction w/ :sgf-gametree and :monkey
202 :sgf-gametree -- one of the gametrees in :sgf-collection
204 :monkey -- vector of three elements:
205 MEM, a pointer to one of the branches in the gametree;
206 BIDX, the index of the \"current branch\"; and
207 COUNT, the number of moves from the beginning of the game
209 :gnugo-color -- either \"black\" or \"white\"
213 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
216 :black-captures -- these are strings since gnugo.el doesn't do anything
217 :white-captures w/ the information besides display it in the mode line;
218 gory details in functions `gnugo-propertize-board-buffer'
219 and `gnugo-merge-showboard-results' (almost more effort
220 than they are worth!)
222 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
223 `gnugo-toggle-image-display' and `gnugo-refresh',
224 as well as gnugo-xpms.el (available elsewhere)
226 :all-yy -- list of 46 keywords used as the `category' text property
227 (so that their plists, typically w/ property `display' or
228 `do-not-display') are consulted by the Emacs display engine;
229 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
230 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
232 :lparen-ov -- overlays shuffled about to indicate the last move; only
233 :rparen-ov one is used when displaying using images
235 :last-user-bpos -- board position; keep the hapless human happy
237 As things stabilize probably more info will be added to this docstring."
239 (puthash key value gnugo-state))
241 (defun gnugo-get (key)
242 "Return the move/game/board-specific value for KEY.
244 (gethash key gnugo-state))
246 (defun gnugo-describe-internal-properties ()
247 "Pretty-print `gnugo-state' properties in another buffer.
248 Handle the big, slow-to-render, and/or uninteresting ones specially."
250 (let ((buf (current-buffer))
251 (d (gnugo-get :diamond))
252 (acc (loop for key being the hash-keys of gnugo-state
253 using (hash-values val)
257 (format "hash: %X (%d images)"
263 (let ((mem (aref val 0)))
268 (switch-to-buffer (get-buffer-create
269 (format "%s*GNUGO Board Properties*"
270 (gnugo-get :diamond))))
273 (setq truncate-lines t)
275 (let ((standard-output (current-buffer)))
277 (goto-char (point-min))
278 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
282 (while (re-search-forward rx (point-max) t)
283 (let ((pos (get-text-property (string-to-number (match-string 1))
284 'gnugo-position buf)))
285 (delete-region (+ 2 (match-beginning 0)) (point))
286 (insert (format " %S" pos))))))
287 (message "%d properties" (length acc))))
289 (defun gnugo-board-buffer-p (&optional buffer)
290 "Return non-nil if BUFFER is a GNUGO Board buffer."
291 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
293 (defun gnugo-board-user-play-ok-p (&optional buffer)
294 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
295 (with-current-buffer (or buffer (current-buffer))
296 (and gnugo-state (not (gnugo-get :waitingp)))))
298 (defsubst gnugo--blackp (string)
299 (string= "black" string))
301 (defun gnugo-other (color)
302 (if (gnugo--blackp color) "white" "black"))
304 (defun gnugo-gate (&optional in-progress-p)
305 (unless (gnugo-board-buffer-p)
306 (user-error "Wrong buffer -- try M-x gnugo"))
307 (unless (gnugo-get :proc)
308 (user-error "No \"gnugo\" process!"))
309 (when (gnugo-get :waitingp)
310 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
311 (gnugo-get :user-color)))
312 (when (and (gnugo-get :game-over) in-progress-p)
313 (user-error "Sorry, game over")))
315 (defun gnugo-sentinel (proc string)
316 (let ((status (process-status proc)))
317 (when (memq status '(exit signal))
318 (let ((buf (process-buffer proc)))
319 (when (buffer-live-p buf)
320 (with-current-buffer buf
321 (setq mode-line-process
323 (propertize (car (split-string string))
324 'face 'font-lock-warning-face)
326 (when (eq proc (gnugo-get :proc))
327 (gnugo-put :proc nil))))))))
329 (defun gnugo--begin-exchange (proc filter line)
330 (declare (indent 2)) ; good time, for a rime
331 ; nice style, for a wile...
332 (set-process-filter proc filter)
333 (process-send-string proc line)
334 (process-send-string proc "\n"))
336 (defun gnugo--q (fmt &rest args)
337 "Send formatted command \"FMT ARGS...\"; wait for / return response.
338 The response is a string whose first two characters indicate the
339 status of the command. See also `gnugo-query'."
340 (when (gnugo-get :waitingp)
341 (user-error "Sorry, still waiting for %s to play"
342 (gnugo-get :gnugo-color)))
343 (let ((proc (gnugo-get :proc)))
344 (process-put proc :incomplete t)
345 (process-put proc :srs "") ; synchronous return stash
346 (gnugo--begin-exchange
347 proc (lambda (proc string)
348 (let ((full (concat (process-get proc :srs)
350 (process-put proc :srs full)
351 (unless (numberp (gnugo--compare-strings
352 full (max 0 (- (length full)
355 (process-put proc :incomplete nil))))
358 (apply #'format fmt args)))
359 (while (process-get proc :incomplete)
360 (accept-process-output proc 30))
361 (prog1 (substring (process-get proc :srs) 0 -2)
362 (process-put proc :srs ""))))
364 (defun gnugo-query (message-format &rest args)
365 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
366 Return a string that omits the first two characters (corresponding
367 to the status indicator in the Go Text Protocol). Use this function
368 when you are sure the command cannot fail."
369 (substring (apply 'gnugo--q message-format args)
372 (defun gnugo-lsquery (message-format &rest args)
373 (split-string (apply 'gnugo-query message-format args)))
375 (defun gnugo--root-node (&optional tree)
376 (gnugo/sgf-root-node (or tree (gnugo-get :sgf-gametree))))
378 (defsubst gnugo--root-prop (prop &optional tree)
379 (cdr (assq prop (gnugo--root-node tree))))
381 (defun gnugo--set-root-prop (prop value &optional tree)
382 (let* ((root (gnugo--root-node tree))
383 (cur (assq prop root)))
386 (push (cons prop value)
387 (cdr (last root))))))
389 (defun gnugo-goto-pos (pos)
390 "Move point to board position POS, a letter-number string."
391 (goto-char (point-min))
392 (forward-line (- (1+ (gnugo-get :SZ))
393 (string-to-number (substring pos 1))))
395 (forward-char (+ (if (= 32 (following-char)) 1 2)
396 (* 2 (- (let ((letter (aref pos 0)))
402 (defun gnugo-f (frag)
403 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
405 (defun gnugo-yang (c)
406 (cdr (assq c '((?+ . hoshi)
408 (?X . (bmoku . bpmoku))
409 (?O . (wmoku . wpmoku))))))
411 (defun gnugo-yy (yin yang &optional momentaryp)
412 (gnugo-f (format "%d-%s"
413 yin (cond ((and (consp yang) momentaryp) (cdr yang))
414 ((consp yang) (car yang))
417 (defun gnugo-toggle-image-display ()
418 (unless (and (fboundp 'display-images-p) (display-images-p))
419 (user-error "Display does not support images, sorry"))
420 (require 'gnugo-xpms)
421 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
422 (user-error "Could not load `gnugo-xpms', sorry"))
423 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
424 (unless (eq fresh (gnugo-get :xpms))
425 (gnugo-put :xpms fresh)
426 (gnugo-put :all-yy nil)))
427 (let* ((new (not (gnugo-get :display-using-images)))
428 (act (if new 'display 'do-not-display)))
430 (setcar (symbol-plist yy) act))
431 (or (gnugo-get :all-yy)
433 (prog1 (mapcar (lambda (ent)
435 (yy (gnugo-yy (cdr k) (car k))))
436 (setplist yy `(not-yet ,(cdr ent)))
439 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
441 (gnugo-put :w-imul (car imul))
442 (gnugo-put :h-imul (cdr imul)))))))
443 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
444 (gnugo-put :highlight-last-move-spec
447 (get (gnugo-yy (get-text-property p 'gnugo-yin)
448 (get-text-property p 'gnugo-yang)
452 (gnugo-get :default-highlight-last-move-spec)))
453 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
454 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
455 (mapc 'delete-overlay (cdar group))
456 (setcdr (car group) nil))
457 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
458 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
459 (gnugo-put :display-using-images new)))
461 (defun gnugo-toggle-grid ()
462 "Turn the grid around the board on or off."
464 (funcall (if (memq :nogrid buffer-invisibility-spec)
465 'remove-from-invisibility-spec
466 'add-to-invisibility-spec)
468 (save-excursion (gnugo-refresh)))
470 (defun gnugo-propertize-board-buffer ()
472 (insert (substring (gnugo--q "showboard") 3))
473 (let* ((grid-props (list 'invisible :nogrid
474 'font-lock-face gnugo-grid-face))
475 (%gpad (gnugo-f 'gpad))
476 (%gspc (gnugo-f 'gspc))
477 (%lpad (gnugo-f 'lpad))
478 (%rpad (gnugo-f 'rpad))
479 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
480 (size (gnugo-get :SZ))
481 (size-string (number-to-string size)))
482 (goto-char (point-min))
483 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
484 (skip-chars-forward " ")
485 (put-text-property (1- (point)) (point) 'category %gpad)
486 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
488 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
489 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
490 (let* ((row (match-string-no-properties 1))
492 (other-edge (+ edge (* 2 size) -1))
493 (right-empty (+ other-edge (length row) 1))
494 (top-p (string= size-string row))
495 (bot-p (string= "1" row)))
496 (let* ((nL (- edge 1 (length size-string)))
498 (ov (make-overlay nL nR (current-buffer) t)))
499 (add-text-properties nL nR grid-props)
500 ;; We redundantly set `invisible' in the overlay to workaround
501 ;; a display bug whereby text *following* the overlaid text is
502 ;; displayed with the face of the overlaid text, but only when
503 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
504 ;; This has something to do w/ the bletcherous `before-string'.
505 (overlay-put ov 'invisible :nogrid)
506 (overlay-put ov 'category %lpad))
507 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
509 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
510 (truncate (- p edge) 2))
512 (yin (let ((A-p (= edge p))
513 (Z-p (= (1- other-edge) p)))
514 (cond ((and top-p A-p) 1)
523 (yang (gnugo-yang (char-after p))))
524 (add-text-properties p (1+ p)
534 (gnugo-position gnugo-yin))))
535 (unless (= (1- other-edge) p)
536 (add-text-properties (1+ p) (+ 2 p) ispc-props)
537 (put-text-property p (+ 2 p) 'intangible ival)))
538 (add-text-properties (1+ other-edge) right-empty grid-props)
539 (goto-char right-empty)
540 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
541 (let ((prop (if (string= "WH" (match-string 1))
544 (beg (match-beginning 2))
546 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
547 (gnugo-put prop (match-string-no-properties 2))))
549 (put-text-property right-empty (point) 'category %rpad)
551 (add-text-properties (1- (point)) (point-max) grid-props)
552 (skip-chars-forward " ")
553 (put-text-property (1- (point)) (point) 'category %gpad)
554 (put-text-property (point) (progn (end-of-line) (point))
557 (defun gnugo-merge-showboard-results ()
558 (let ((aft (substring (gnugo--q "showboard") 3))
559 (adj 1) ; string to buffer position adjustment
561 (sync "[0-9]* stones$")
562 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
563 ;; restrictive a condition that fails in the case of:
566 ;; ... WHITE has captured 1 stones
569 ;; ... WHITE has captured 14 stones
572 ;; where the after count has more digits than the before count,
573 ;; but shares the same leading digits. In this case, the result
574 ;; of `compare-strings' points to the SPC following the before
575 ;; count (indicated by caret in this example).
577 (bef (buffer-substring-no-properties (point-min) (point-max)))
578 (bef-start 0) (bef-idx 0)
579 (aft-start 0) (aft-idx 0)
580 aft-sync-backtrack mis inc cut new very-strange)
581 (while (numberp (setq mis (gnugo--compare-strings
584 (setq aft-sync-backtrack nil
585 inc (if (cl-minusp mis)
588 bef-idx (+ bef-start inc)
589 aft-idx (+ aft-start inc)
590 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
593 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
594 (let ((peek (1- aft-idx)))
595 (while (not (= 32 (aref aft peek)))
596 (setq peek (1- peek)))
597 (setq aft-sync-backtrack (1+ peek))))
601 (if aft-sync-backtrack
602 (- aft-sync-backtrack aft-idx)
605 (if aft-sync-backtrack
606 (let* ((asb aft-sync-backtrack)
607 (l-p (get-text-property cut :gnugo-cf))
610 (keep (text-properties-at cut)))
611 (setq new (substring aft asb (string-match " " aft asb)))
612 (plist-put keep :gnugo-cf (cons (length new) capprop))
613 (gnugo-put capprop new)
614 (delete-char old-len)
615 (insert (apply 'propertize new keep))
616 (incf adj (- (length new) old-len)))
617 (setq new (aref aft aft-idx))
618 (insert-and-inherit (char-to-string new))
619 (let ((yin (get-text-property cut 'gnugo-yin))
620 (yang (gnugo-yang new)))
621 (add-text-properties cut (1+ cut)
625 ,(gnugo-yy yin yang))))
627 ;; do this last to avoid complications w/ font lock
628 ;; (this also means we cannot include `intangible' in `front-sticky')
629 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
630 (put-text-property cut (1+ cut) 'intangible very-strange))))))
632 (defsubst gnugo--move-prop (node)
636 (defun gnugo-move-history (&optional rsel)
637 "Determine and return the game's move history.
638 Optional arg RSEL controls side effects and return value.
639 If nil, display the history in the echo area as \"(N moves)\"
640 followed by the space-separated list of moves. When called
641 interactively with a prefix arg (i.e., RSEL is `(4)'), display
642 similarly, but suffix with the mover (either \":B\" or \":W\").
643 If RSEL is the symbol `car' return the most-recent move; if
644 `cadr', the next-to-most-recent move; if `count' the number of
645 moves thus far; if `two' the last two moves as a list, oldest last.
647 For all other values of RSEL, do nothing and return nil."
649 (let* ((monkey (gnugo-get :monkey))
650 (mem (aref monkey 0))
651 (size (gnugo-get :SZ))
655 ((as-pos (cc) (if (string= "" cc)
657 (setq col (aref cc 0))
659 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
660 (- size (- (aref cc 1) ?a)))))
661 (as-pos-maybe (x) (if (string= "resign" x)
664 (next (byp) (when (setq node (pop mem)
665 mprop (gnugo--move-prop node))
666 (setq move (as-pos-maybe (cdr mprop)))
668 (format "%s%s" move (car mprop))
672 (tell () (message "(%d moves) %s"
674 (mapconcat 'identity (nreverse acc) " ")))
675 (finish (byp) (while mem (next byp)) (tell)))
680 (`cadr (nn) (car (nn)))
681 (`count (aref monkey 2))
685 (defun gnugo-boss-is-near ()
686 "Do `bury-buffer' until the current one is not a GNU Board."
688 (while (gnugo-board-buffer-p)
691 (defsubst gnugo--passp (string)
692 (string= "PASS" string))
694 (defsubst gnugo--no-regrets (monkey tree)
695 (eq (aref tree (aref monkey 1))
698 (defun gnugo-note (property value &optional mogrifyp)
700 (let ((sz (gnugo-get :SZ)))
702 ((mog (pos) (if (gnugo--passp pos)
704 (let* ((col (aref pos 0))
705 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
706 (two (+ ?a (- sz (string-to-number
707 (substring pos 1))))))
708 (format "%c%c" one two)))))
709 (setq value (if (consp value)
712 (let* ((pair (cons property value))
714 (monkey (gnugo-get :monkey))
715 (mem (aref monkey 0)))
716 (if (memq property '(:B :W))
717 (let ((tree (gnugo-get :sgf-gametree))
718 (bidx (aref monkey 1)))
719 ;; Detect déjà-vu. That is, when placing "A", avoid:
725 ;; (such "variations" do not actually vary!) in favor of:
731 ;; This presumes ‘bidx’ is 0 (main line) and that
732 ;; all growth should occur on the main line.
735 (rotatef (aref tree bidx)
739 with count = (length tree)
742 ;; Start with latest / highest likelihood for hit.
743 ;; todo: prune unfeasible candidates
744 from 0 above (- count)
745 if (setq bx (mod i count)
747 ;; todo: early termination based on move number
748 (loop for m on (aref tree bx)
751 (when (equal pair (assoc property (car m)))
758 ;; (message "déjà-vu! %d follows %d" bidx bx)
765 ;; (message "new %d" bidx)
766 (unless (gnugo--no-regrets monkey tree)
767 ;; <grumble grumble> SGF sez "move" node in the root
768 ;; position of a (sub-)gametree is "bad style". :-/
769 (let ((where (memq tree (gnugo-get :sgf-collection))))
770 (setq tree (apply 'vector (append tree (list mem))))
772 (gnugo-put :sgf-gametree tree)
773 (setcar where tree)))
775 (aset tree bidx mem))))
776 (setf (aref monkey 0) mem)
777 (incf (aref monkey 2)))
778 (setcdr (last (car mem)) fruit))))
780 (defun gnugo-close-game (end-time resign)
781 (gnugo-put :game-end-time end-time)
782 (let ((now (or end-time (current-time))))
783 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
785 (gnugo-put :game-over
786 (if (or (eq t resign)
787 (and (stringp resign)
788 (string-match "[BW][+][Rr]esign" resign)))
795 (gnugo-query "worm_stones %s" color)
797 (let ((live (append (ls "black") (ls "white"))))
800 (let ((dd (gnugo-query "dragon_data"))
801 (start 0) mem color ent live dead)
802 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
804 (setq mem (match-string 1 dd)
805 color (match-string 2 dd)
807 ent (cons (list color)
808 (sort (gnugo-lsquery "dragon_stones %s" mem)
810 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
812 (if (match-string 2 dd)
815 (setq start (match-end 0)))
819 (defun gnugo--unclose-game ()
820 (dolist (prop '(:game-over ; all those in -close-game
823 (gnugo-put prop nil))
824 (let* ((root (gnugo--root-node))
825 (cur (assq :RE root)))
827 (assert (not (eq cur (car root))) nil
828 ":RE at head of root node: %S"
832 (defun gnugo-push-move (userp move)
833 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
834 (start (gnugo-get :waiting-start))
836 (resignp (string= "resign" move))
837 (passp (gnugo--passp move))
838 (head (gnugo-move-history 'car))
839 (onep (and head (gnugo--passp head)))
840 (donep (or resignp (and onep passp))))
842 (gnugo-merge-showboard-results))
843 (gnugo-put :last-mover color)
845 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
846 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
848 (gnugo-put :last-waiting (cadr (time-subtract now start))))
850 (gnugo-close-game now resignp))
851 (gnugo-put :waiting-start (and (not donep) now))
854 (defun gnugo-venerate (yin yang)
855 (let* ((fg-yy (gnugo-yy yin yang))
856 (fg-disp (or (get fg-yy 'display)
857 (get fg-yy 'do-not-display)))
858 (fg-data (plist-get (cdr fg-disp) :data))
859 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
860 (bg-disp (or (get bg-yy 'display)
861 (get bg-yy 'do-not-display)))
862 (bg-data (plist-get (cdr bg-disp) :data))
866 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
867 (setq start (match-end 0))
868 (string-to-number (match-string 1 s)))))
869 (while (and (not (cl-minusp ncolors))
870 (string-match ",\n" s start))
871 (setq start (match-end 0)
872 ncolors (1- ncolors)))
873 (string-match "\"" s start)
875 (new (copy-sequence fg-data))
876 (lx (length fg-data))
877 (sx (funcall bop fg-data))
878 (sb (funcall bop bg-data))
879 (color-key (aref new sx))) ; blech, heuristic
881 (when (and (not (= color-key (aref new sx)))
882 (cl-plusp (random 4)))
883 (aset new sx (aref bg-data sb)))
886 (create-image new 'xpm t :ascent 'center)))
888 (defun gnugo-refresh (&optional nocache)
889 "Update GNUGO Board buffer display.
890 While a game is in progress, parenthesize the last-played stone (no parens
891 for pass). If the buffer is currently displayed in the selected window,
892 recenter the board (presuming there is extra space in the window). Update
893 the mode line. Lastly, move point to the last position played by the user,
894 if that move was not a pass.
896 Prefix arg NOCACHE requests complete reconstruction of the display, which may
897 be slow. (This should normally be unnecessary; specify it only if the display
898 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
901 (when (and nocache (not (gnugo-get :waitingp)))
902 (gnugo-propertize-board-buffer))
903 (let* ((last-mover (gnugo-get :last-mover))
904 (other (gnugo-other last-mover))
905 (move (gnugo-move-history 'car))
906 (game-over (gnugo-get :game-over))
910 (let ((l-ov (gnugo-get :lparen-ov))
911 (r-ov (gnugo-get :rparen-ov)))
912 (if (member move '("PASS" "resign"))
913 (mapc 'delete-overlay (list l-ov r-ov))
914 (gnugo-goto-pos move)
916 (hspec (gnugo-get :highlight-last-move-spec))
917 (display-value (nth 0 hspec))
918 (l-offset (nth 1 hspec))
919 (l-new-pos (+ p l-offset))
920 (r-action (nth 2 hspec)))
921 (overlay-put l-ov 'display
922 (if (functionp display-value)
923 (funcall display-value p)
925 (move-overlay l-ov l-new-pos (1+ l-new-pos))
927 (funcall r-action r-ov)
928 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
930 (rename-buffer (concat (gnugo-get :diamond)
932 (format "%s(game over)"
933 (if (string= move "resign")
934 (concat move "ation ")
936 (format "%s(%s to play)"
937 (if move (concat move " ") "")
941 (let ((live (cdr (assq 'live game-over)))
942 (dead (cdr (assq 'dead game-over)))
944 (unless (eq game-over (get-text-property 1 'game-over))
945 (dolist (group (append live dead))
946 (dolist (pos (cdr group))
949 (put-text-property p (1+ p) 'group group)))
950 (put-text-property 1 2 'game-over game-over))
952 (when (setq pall (cdar group))
953 (mapc 'delete-overlay pall)
954 (setcdr (car group) nil)))
957 (let (ov pall c (color (caar group)))
958 (setq c (if (gnugo--blackp color) "x" "o"))
959 (dolist (pos (cdr group))
961 (setq p (point) ov (make-overlay p (1+ p)))
964 (if (gnugo-get :display-using-images)
965 ;; respect the dead individually; it takes more time
966 ;; but that's not a problem (for them)
967 (gnugo-venerate (get-text-property p 'gnugo-yin)
968 (gnugo-yang (aref (upcase c) 0)))
969 (propertize c 'face 'font-lock-warning-face)))
971 (setcdr (car group) pall))))))
973 (when (setq window (get-buffer-window (current-buffer)))
974 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
975 (size (gnugo-get :SZ))
976 (under10p (< size 10))
977 (h (- (truncate (- (window-height window)
978 (* size (gnugo-get :hmul))
982 (edges (window-edges window))
983 (right-w-edge (nth 2 edges))
984 (avail-width (- right-w-edge (nth 0 edges)))
985 (wmul (gnugo-get :wmul))
986 (imagesp (symbol-plist (gnugo-f 'ispc)))
992 2 ; between board and grid
997 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
998 `(display ,(make-string h 10))
999 '(invisible :nogrid)))
1004 (cond (imagesp (+ (* 0.5 wmul)
1010 (gspc . ,(when imagesp
1014 ;; DWR: image width alone => OBOE!
1016 ;; NB: ‘(* wmul cw)’ is the same
1017 ;; as ‘(car (image-size ... t))’.
1018 (let ((cw (frame-char-width)))
1019 (/ (+ 1.0 (* wmul cw))
1022 (lpad . ,(let ((d `(display (space :align-to ,w))))
1023 ;; We distinguish between these cases to
1024 ;; workaround a display bug whereby the
1025 ;; `before-string' is omitted entirely (not
1026 ;; rendered) when interacting w/ the text
1027 ;; mode last-move left-paren for moves in
1031 ,(apply 'propertize " " d))
1034 (space :align-to ,(1- avail-width))))))
1035 (setplist (gnugo-f (car pair)) (cdr pair)))))
1037 (let ((cur (gnugo-get :mode-line)))
1038 (unless (equal cur gnugo-mode-line)
1039 (setq cur gnugo-mode-line)
1040 (gnugo-put :mode-line cur)
1041 (gnugo-put :mode-line-form
1042 (cond ((stringp cur)
1043 (setq cur (copy-sequence cur))
1045 (while (setq cut (string-match "~[bwpmtu]" cur))
1047 (setq c (aref cur (incf cut)))
1050 `(,(intern (format "squig-%c" c))
1052 (?b '(or (gnugo-get :black-captures) 0))
1053 (?w '(or (gnugo-get :white-captures) 0))
1054 (?p '(gnugo-other (gnugo-get :last-mover)))
1055 (?t '(let ((ws (gnugo-get :waiting-start)))
1057 (cadr (time-since ws))
1059 (?u '(or (gnugo-get :last-waiting) "-"))
1060 (?m '(gnugo-move-history 'count))))
1062 `(let ,(delete-dups (copy-sequence acc))
1063 (format ,cur ,@(reverse (mapcar 'car acc))))))
1065 (let ((form (gnugo-get :mode-line-form)))
1066 (setq mode-line-process
1068 ;; this dynamicism is nice but excessive in its wantonness
1069 ;;- `(" [" (:eval ,form) "]")
1070 ;; this dynamicism is ok because the user triggers it
1071 (list (format " [%s]" (eval form))))))
1072 (force-mode-line-update))
1074 (when (setq last (gnugo-get :last-user-bpos))
1075 (gnugo-goto-pos last))))
1077 ;;;---------------------------------------------------------------------------
1078 ;;; Game play actions
1080 (defun gnugo-get-move-insertion-filter (proc string)
1081 (with-current-buffer (process-buffer proc)
1082 (let* ((so-far (gnugo-get :get-move-string))
1083 (full (gnugo-put :get-move-string (concat so-far string))))
1084 (when (string-match "^= \\(.+\\)\n\n" full)
1085 (let ((pos-or-pass (match-string 1 full)))
1086 (gnugo-put :get-move-string nil)
1087 (gnugo-put :waitingp nil)
1088 (gnugo-push-move nil pos-or-pass)
1089 (let ((buf (current-buffer)))
1090 (let (gnugo-inhibit-refresh)
1091 (run-hooks 'gnugo-post-move-hook)
1092 (unless gnugo-inhibit-refresh
1093 (with-current-buffer buf
1094 (gnugo-refresh))))))))))
1096 (defun gnugo-get-move (color)
1097 (gnugo-put :waitingp t)
1098 (gnugo--begin-exchange
1099 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1100 (concat "genmove " color))
1101 (accept-process-output))
1103 (defun gnugo-cleanup ()
1104 (when (gnugo-board-buffer-p)
1105 (unless (zerop (buffer-size))
1106 (message "Thank you for playing GNU Go."))
1108 (setplist sym nil) ; "...is next to fordliness." --Huxley
1109 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1110 ;; No worries, things will be Much Better w/ structs, RSN...
1112 (append (gnugo-get :all-yy)
1121 (setq gnugo-state nil)))
1123 (defun gnugo-position ()
1124 (or (get-text-property (point) 'gnugo-position)
1125 (user-error "Not a proper position point")))
1127 (defun gnugo-move ()
1128 "Make a move on the GNUGO Board buffer.
1129 The position is computed from current point.
1130 Signal error if done out-of-turn or if game-over.
1131 To start a game try M-x gnugo."
1134 (let* ((buf (current-buffer))
1135 (pos (gnugo-position))
1136 (move (format "play %s %s" (gnugo-get :user-color) pos))
1137 (accept (gnugo--q move)))
1138 (unless (= ?= (aref accept 0))
1139 (user-error "%s" accept))
1140 (gnugo-push-move t pos) ; value always nil for non-pass move
1141 (let (gnugo-inhibit-refresh)
1142 (run-hooks 'gnugo-post-move-hook)
1143 (unless gnugo-inhibit-refresh
1144 (with-current-buffer buf
1146 (with-current-buffer buf
1147 (gnugo-get-move (gnugo-get :gnugo-color)))))
1149 (defun gnugo-mouse-move (e)
1150 "Do `gnugo-move' at mouse location."
1153 (when (looking-at "[.+]")
1156 (defun gnugo-pass ()
1157 "Make a pass on the GNUGO Board buffer.
1158 Signal error if done out-of-turn or if game-over.
1159 To start a game try M-x gnugo."
1162 (let ((accept (gnugo--q "play %s PASS" (gnugo-get :user-color))))
1163 (unless (= ?= (aref accept 0))
1164 (user-error "%s" accept)))
1165 (let ((donep (gnugo-push-move t "PASS"))
1166 (buf (current-buffer)))
1167 (let (gnugo-inhibit-refresh)
1168 (run-hooks 'gnugo-post-move-hook)
1169 (unless gnugo-inhibit-refresh
1170 (with-current-buffer buf
1173 (with-current-buffer buf
1174 (gnugo-get-move (gnugo-get :gnugo-color))))))
1176 (defun gnugo-mouse-pass (e)
1177 "Do `gnugo-pass' at mouse location."
1182 (defun gnugo-resign ()
1185 (if (not (y-or-n-p "Resign? "))
1186 (message "(not resigning)")
1187 (gnugo-push-move t "resign")
1190 (defun gnugo-animate-group (w/d)
1191 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1192 (let* ((pos (gnugo-position))
1193 (orig-b-m-p (buffer-modified-p))
1195 (unless (memq (following-char) '(?X ?O))
1196 (user-error "No stone at %s" pos))
1197 (setq blurb (message "Computing %s stones ..." w/d)
1198 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1199 (message "%s %s in group." blurb (length stones))
1200 (setplist (gnugo-f 'anim) nil)
1201 (let* ((spec (if (gnugo-get :display-using-images)
1202 (loop with yin = (get-text-property (point) 'gnugo-yin)
1203 with yang = (gnugo-yang (following-char))
1204 with up = (get (gnugo-yy yin yang t) 'display)
1205 with dn = (get (gnugo-yy yin yang) 'display)
1206 for n below (length gnugo-animation-string)
1207 collect (if (zerop (logand 1 n))
1209 (split-string gnugo-animation-string "" t)))
1211 (ovs (save-excursion
1212 (mapcar (lambda (pos)
1213 (gnugo-goto-pos pos)
1215 (ov (make-overlay p (1+ p))))
1216 (overlay-put ov 'category (gnugo-f 'anim))
1217 (overlay-put ov 'priority most-positive-fixnum)
1220 (setplist (gnugo-f 'anim) (cons 'display cell))
1221 (while (and (cdr spec) ; let last linger lest levity lost
1222 (sit-for 0.08675309)) ; jenny jenny i got your number...
1223 (setcar cell (setq spec (cdr spec)))
1224 ;; Force redisplay of overlays.
1225 (set-buffer-modified-p orig-b-m-p))
1227 (mapc 'delete-overlay ovs)
1230 (defun gnugo-display-group-data (command buffer-name)
1231 (message "Computing %s ..." command)
1232 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1233 (switch-to-buffer buffer-name)
1236 (message "Computing %s ... done." command))
1238 (defun gnugo-worm-stones ()
1239 "In the GNUGO Board buffer, animate \"worm\" at current position.
1240 Signal error if done out-of-turn or if game-over.
1241 See variable `gnugo-animation-string' for customization."
1244 (gnugo-animate-group 'worm))
1246 (defun gnugo-worm-data ()
1247 "Display in another buffer data from \"worm\" at current position.
1248 Signal error if done out-of-turn or if game-over."
1251 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1253 (defun gnugo-dragon-stones ()
1254 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1255 Signal error if done out-of-turn or if game-over.
1256 See variable `gnugo-animation-string' for customization."
1259 (gnugo-animate-group 'dragon))
1261 (defun gnugo-dragon-data ()
1262 "Display in another buffer data from \"dragon\" at current position.
1263 Signal error if done out-of-turn or if game-over."
1266 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1268 (defun gnugo-toggle-dead-group ()
1269 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1270 The group is selected from current position (point). Signal error if
1271 not in game-over or if there is no group at that position.
1273 In the context of GNU Go, a group is called a \"dragon\" and may be
1274 composed of more than one \"worm\" (set of directly-connected stones).
1275 It is unclear to the gnugo.el author whether or not GNU Go supports
1276 - considering worms as groups in their own right; and
1277 - toggling group aliveness via GTP.
1278 Due to these uncertainties, this command is only half complete; the
1279 changes you may see in Emacs are not propagated to the gnugo subprocess.
1280 Thus, GTP commands like `final_score' may give unexpected results.
1282 If you are able to expose via GTP `change_dragon_status' in utils.c,
1283 you may consider modifying the `gnugo-toggle-dead-group' source code
1284 to enable full functionality."
1286 (let ((game-over (or (gnugo-get :game-over)
1287 (user-error "Sorry, game still in play")))
1288 (group (or (get-text-property (point) 'group)
1289 (user-error "No stone at that position")))
1290 (now (current-time)))
1291 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1293 (let ((live (assq 'live game-over))
1294 (dead (assq 'dead game-over))
1296 (if (memq group live)
1297 (setq bef live now dead)
1298 (setq bef dead now live))
1299 (setcdr bef (delq group (cdr bef)))
1300 (setcdr now (cons group (cdr now)))
1301 ;; disabled permanently -- too wrong
1305 (let ((color (caar group)))
1306 (dolist (stone (cdr group))
1307 (gnugo-query "play %s %s" color stone)))))
1310 ;; drastic (and wrong -- clobbers capture info, etc)
1311 (gnugo-query "clear_board")
1312 (mapc #'populate (cdr live)))))
1313 ;; here is the desired interface (to be enabled Some Day)
1315 (gnugo-query "change_dragon_status %s %s"
1316 (cadr group) (if (eq now live)
1322 (defun gnugo-estimate-score ()
1323 "Display estimated score of a game of GNU Go.
1324 Output includes number of stones on the board and number of stones
1325 captured by each player, and the estimate of who has the advantage (and
1326 by how many stones)."
1328 (message "Est.score ...")
1329 (let ((black (length (gnugo-lsquery "list_stones black")))
1330 (white (length (gnugo-lsquery "list_stones white")))
1331 (black-captures (gnugo-query "captures black"))
1332 (white-captures (gnugo-query "captures white"))
1333 (est (gnugo-query "estimate_score")))
1334 ;; might as well update this
1335 (gnugo-put :black-captures black-captures)
1336 (gnugo-put :white-captures white-captures)
1337 (message "Est.score ... B %s %s | W %s %s | %s"
1338 black black-captures white white-captures est)))
1340 (defun gnugo-write-sgf-file (filename)
1341 "Save the game history to FILENAME (even if unfinished).
1342 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1343 (interactive "FWrite game as SGF file: ")
1344 (when (and (file-exists-p filename)
1345 (not (y-or-n-p "File exists. Continue? ")))
1346 (user-error "Not writing %s" filename))
1347 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1348 (set-buffer-modified-p nil))
1350 (defun gnugo--who-is-who (wait play samep)
1351 (message "GNU Go %splays as %s, you as %s (%s)"
1352 (if samep "" "now ")
1355 "NOTE: this is a switch!")))
1357 (defsubst gnugo--nodep (x)
1358 (keywordp (caar x)))
1360 (defsubst gnugo--SZ! (size)
1361 (gnugo-put :SZ size))
1363 (defun gnugo-read-sgf-file (filename)
1364 "Load the first game tree from FILENAME, a file in SGF format."
1365 (interactive "fSGF file to load: ")
1366 (when (file-directory-p filename)
1367 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1368 (let (ans play wait samep coll tree)
1369 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1370 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1371 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1372 (expand-file-name filename)))
1374 (user-error "%s" ans))
1375 (setq play (substring ans 2)
1376 wait (gnugo-other play)
1377 samep (string= (gnugo-get :user-color) play))
1378 (gnugo-put :last-mover wait)
1380 (gnugo-put :gnugo-color wait)
1381 (gnugo-put :user-color play))
1382 (setq coll (gnugo/sgf-read-file filename)
1383 tree (nth (let ((n (length coll)))
1387 ;; (let* ((q (format "Which game? (1-%d)" n))
1388 ;; (choice (1- (read-number q 1))))
1389 ;; (if (and (< -1 choice) (< choice n))
1391 ;; (message "(Selecting the first game)")
1393 ;; but this is what we use (for now) to accomodate
1394 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1396 (message "(Selecting the first game)"))
1399 (gnugo-put :sgf-collection coll)
1400 (gnugo-put :sgf-gametree tree)
1401 ;; This is deliberately undocumented for now.
1402 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1403 (let* ((mem (aref tree 0))
1406 (vector mem 0 (loop for node in mem
1407 count (gnugo--move-prop node))))
1408 (gnugo-put :game-over
1410 (or (gnugo--root-prop :RE tree)
1411 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1413 (when (and game-over
1414 ;; (maybe) todo: user var to inhibit (can be slow)
1416 (gnugo-close-game nil game-over)))
1418 (set-buffer-modified-p nil)
1419 (gnugo--who-is-who wait play samep)))
1421 (defun gnugo-magic-undo (spec &optional noalt keep)
1422 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1423 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1424 check that the position is occupied by a stone of the user's color,
1425 and if so, remove moves from the history until that position is clear.
1426 If SPEC is a positive number, remove exactly that many moves from the
1427 history, signaling an error if the history is exhausted before finishing.
1428 If SPEC Is 0 (zero), remove either one or two moves,
1429 so that you are to play next.
1430 If SPEC is not recognized, signal \"bad spec\" error.
1432 Refresh the board for each move undone. If (in the case where SPEC is
1433 a number) after finishing, the color to play is not the user's color,
1434 schedule a move by GNU Go.
1436 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1437 turn to play. Optional second arg NOALT non-nil inhibits this.
1439 Optional third arg KEEP non-nil means do not prune the undone moves
1440 from the gametree, such that they become a sub-gametree (variation)
1444 (user-color (gnugo-get :user-color))
1445 (monkey (gnugo-get :monkey))
1446 (tree (gnugo-get :sgf-gametree))
1447 (remorseful (not (gnugo--no-regrets monkey tree)))
1449 (cond ((numberp spec)
1450 (setq n (if (zerop spec)
1451 (if (string= user-color (gnugo-get :last-mover))
1455 done (lambda () (zerop n))))
1456 ((string-match "^[a-z]" spec)
1457 (let ((pos (upcase spec)))
1458 (setq done `(lambda ()
1459 (gnugo-goto-pos ,pos)
1460 (memq (following-char) '(?. ?+))))
1461 (when (funcall done)
1462 (user-error "%s already clear" pos))
1463 (when (= (save-excursion
1464 (gnugo-goto-pos pos)
1466 (if (gnugo--blackp user-color)
1469 (user-error "%s not occupied by %s" pos user-color))))
1470 (t (user-error "Bad spec: %S" spec)))
1471 (when (gnugo-get :game-over)
1472 (gnugo--unclose-game))
1473 (while (not (funcall done))
1474 (setq ans (gnugo--q "undo"))
1475 (unless (= ?= (aref ans 0))
1476 (user-error "%s" ans))
1477 (decf (aref monkey 2))
1478 (pop (aref monkey 0))
1479 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1480 (gnugo-merge-showboard-results) ; all
1481 (gnugo-refresh) ; this
1483 (redisplay)) ; eye candy
1484 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1486 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1487 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1489 (gnugo-get :center-position)))
1491 (unless (or keep remorseful)
1492 (aset tree (aref monkey 1) (aref monkey 0)))
1493 (when (and ulastp (not noalt))
1494 (gnugo-get-move (gnugo-get :gnugo-color))))))
1496 (defun gnugo-undo-one-move (&optional me-next)
1497 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1498 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1499 Prefix arg ME-NEXT means to arrange for you to play
1500 the color of the next move (and GNU Go the opposite).
1501 This is useful after loading an SGF file whose last
1502 move was done by the color you prefer to play:
1503 \\[gnugo-read-sgf-file] FILENAME RET
1504 C-u \\[gnugo-undo-one-move]
1506 See also `gnugo-undo-two-moves'."
1509 (gnugo-magic-undo 1 t)
1511 (let* ((wait (gnugo-get :last-mover))
1512 (play (gnugo-other wait)))
1513 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
1514 (gnugo-put :user-color play)
1515 (gnugo-put :gnugo-color wait))))
1517 (defun gnugo-undo-two-moves ()
1518 "Undo a pair of moves (GNU Go's and yours).
1519 However, if you are the last mover, undo only one move.
1520 Regardless, after undoing, it is your turn to play again."
1523 (gnugo-magic-undo 0))
1525 (defun gnugo-oops (&optional position)
1526 "Like `gnugo-undo-two-moves', but keep the undone moves.
1527 The kept moves become a sub-gametree (variation) when play resumes.
1528 Prefix arg means, instead, undo repeatedly up to and including
1529 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1532 (gnugo-magic-undo (if position
1537 (defun gnugo-display-final-score ()
1538 "Display final score and other info in another buffer (when game over).
1539 If the game is still ongoing, Emacs asks if you wish to stop play (by
1540 making sure two \"pass\" moves are played consecutively, if necessary).
1541 Also, add the `:RE' SGF property to the root node of the game tree."
1543 (let ((game-over (gnugo-get :game-over)))
1544 (unless (or game-over
1545 (and (not (gnugo-get :waitingp))
1546 (y-or-n-p "Game still in play. Stop play now? ")))
1547 (user-error "Sorry, game still in play"))
1551 (message "Playing PASS for %s ..."
1552 (gnugo-get (if userp :user-color :gnugo-color)))
1554 (gnugo-push-move userp "PASS")))
1559 (let ((b= " Black = ")
1561 (res (when (string= "resign" (gnugo-move-history 'car))
1562 (gnugo-get :last-mover)))
1566 (format "%s wins.\n"
1567 (substring (if (= ?b (aref res 0)) w= b=)
1569 "The game is over.\n"
1570 (format "Resignation by %s.\n" res))
1571 result (concat (upcase (substring (gnugo-other res) 0 1))
1573 (message "Computing final score ...")
1574 (let* ((g-over (gnugo-get :game-over))
1575 (live (cdr (assq 'live g-over)))
1576 (dead (cdr (assq 'dead g-over)))
1577 (seed (gnugo-get :scoring-seed))
1578 (terr-q (format "final_status_list %%s_territory %d" seed))
1581 (b-terr (length (gnugo-lsquery terr-q "black")))
1582 (w-terr (length (gnugo-lsquery terr-q "white")))
1583 (b-capt (string-to-number (gnugo-get :black-captures)))
1584 (w-capt (string-to-number (gnugo-get :white-captures)))
1585 (komi (gnugo--root-prop :KM)))
1586 (setq blurb (list "The game is over. Final score:\n")
1587 result (gnugo-query "final_score %d" seed))
1588 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1589 (dolist (group live)
1590 (incf (if (gnugo--blackp (caar group))
1593 (length (cdr group))))
1594 (dolist (group dead)
1595 (incf (if (gnugo--blackp (caar group))
1598 (length (cdr group))))
1599 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1600 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1601 w-terr terr komi 'komi (+ w-terr komi))
1604 (dolist (group dead)
1605 (incf (if (gnugo--blackp (caar group))
1608 (* 2 (length (cdr group)))))
1609 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1614 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1618 (+ w-terr w-capt komi))
1620 (push (if (string= "0" result)
1621 "The game is a draw.\n"
1622 (format "%s wins by %s.\n"
1623 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1624 (substring result 2)))
1626 (message "Computing final score ... done")))
1628 (let ((beg (gnugo-get :game-start-time))
1629 (end (gnugo-get :game-end-time)))
1633 ((yep (pretty moment)
1634 (push (format-time-string
1635 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
1638 (yep "Game start" beg)
1640 (setq blurb (apply 'concat (nreverse blurb)))
1641 (gnugo--set-root-prop :RE result)
1642 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1646 (defun gnugo-quit ()
1647 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1648 If the game is not over, ask for confirmation first."
1650 (if (or (gnugo-get :game-over)
1651 (y-or-n-p "Quit? "))
1653 (message "(not quitting)")))
1655 (defun gnugo-leave-me-alone ()
1656 "Kill the current buffer unconditionally."
1660 (defun gnugo-fancy-undo (count)
1661 "Rewind the game tree in various ways.
1662 Prefix arg COUNT means to undo that many moves.
1663 Otherwise, undo repeatedly up to and including the move
1664 which placed the stone at point."
1667 ;; TODO: Move this into `gnugo-magic-undo' proper.
1668 (cond ((numberp count) count)
1669 ((consp count) (car count))
1670 (t (gnugo-position)))))
1672 (defun gnugo-toggle-image-display-command () ; ugh
1673 "Toggle use of images to display the board, then refresh."
1675 (gnugo-toggle-image-display)
1676 (save-excursion (gnugo-refresh)))
1678 (defun gnugo-describe-position ()
1679 "Display the board position under cursor in the echo area."
1681 (message "%s" (gnugo-position)))
1683 (defun gnugo-switch-to-another ()
1684 "Switch to another GNU Go game buffer (if any)."
1686 (loop for buf in (cdr (buffer-list))
1687 if (gnugo-board-buffer-p buf)
1690 (switch-to-buffer buf))
1691 finally do (message "(only one)")))
1693 ;;;---------------------------------------------------------------------------
1694 ;;; Command properties and gnugo-command
1696 ;; GTP commands entered by the user are never issued directly to GNU Go;
1697 ;; instead, their behavior and output are controlled by the property
1698 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1699 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1701 ;; :full -- completely interpret the command string; the value is a
1702 ;; func that takes the list of words derived from splitting the
1703 ;; command string (minus the command) and handles everything.
1705 ;; :output -- either a keyword specifying the preferred output method:
1706 ;; :message -- show output in minibuffer
1707 ;; :discard -- sometimes you just don't care;
1708 ;; or a function that takes one arg, the output string, and
1709 ;; handles it completely. default is to switch to buffer
1710 ;; "*gnugo command output*" if the output has a newline,
1711 ;; otherwise use `message'.
1713 ;; :post-thunk -- run after output processing (at the very end).
1715 (defun gnugo-command (command)
1716 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1717 Output and Emacs behavior depend on which command is given (some
1718 commands are handled completely by Emacs w/o using the subprocess;
1719 some commands have their output displayed in specially prepared
1720 buffers or in the echo area; some commands are instrumented to do
1721 gnugo.el-specific housekeeping).
1723 For example, for the command \"help\", Emacs visits the
1724 GTP command reference info page.
1726 NOTE: At this time, GTP command handling specification is still
1727 incomplete. Thus, some commands WILL confuse gnugo.el."
1728 (interactive "sCommand: ")
1729 (if (string= "" command)
1730 (message "(no command given)")
1731 (let* ((split (split-string command))
1732 (cmd (intern (car split)))
1733 (spec (get cmd :gnugo-gtp-command-spec))
1734 (full (plist-get spec :full)))
1736 (funcall full (cdr split))
1737 (message "Doing %s ..." command)
1738 (let* ((ans (gnugo--q command))
1739 (where (plist-get spec :output)))
1740 (if (string-match "unknown.command" ans)
1742 (cond ((functionp where) (funcall where ans))
1743 ((eq :discard where) (message ""))
1744 ((or (eq :message where)
1745 (not (string-match "\n" ans)))
1747 (t (switch-to-buffer "*gnugo command output*")
1750 (message "Doing %s ... done." command)))
1751 (let ((thunk (plist-get spec :post-thunk)))
1752 (when thunk (funcall thunk)))))))))
1754 ;;;---------------------------------------------------------------------------
1755 ;;; Major mode for interacting with a GNUGO subprocess
1757 (put 'gnugo-board-mode 'mode-class 'special)
1758 (defun gnugo-board-mode ()
1759 "Major mode for playing GNU Go.
1760 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1761 In this mode, keys do not self insert.
1763 \\{gnugo-board-mode-map}"
1764 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1765 (buffer-disable-undo) ; todo: undo undo undoing
1766 (kill-all-local-variables)
1767 (use-local-map gnugo-board-mode-map)
1768 (set (make-local-variable 'font-lock-defaults)
1769 '(gnugo-font-lock-keywords t))
1770 (setq major-mode 'gnugo-board-mode
1771 mode-name "GNUGO Board"
1773 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1774 (set (make-local-variable 'gnugo-state)
1775 (make-hash-table :size (1- 42) :test 'eq))
1776 (add-to-invisibility-spec :nogrid)
1777 (mapc (lambda (prop)
1778 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1779 '(:game-over ; move latter to func `gnugo'
1786 :display-using-images
1790 (let ((name (if (string-match "[ ]" gnugo-program)
1791 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1792 (o (substring gnugo-program (match-end 0)))
1793 (h (or (car gnugo-option-history) "")))
1794 (when (string-match "--mode" o)
1795 (user-error "Found \"--mode\" in `gnugo-program'"))
1796 (when (and o (cl-plusp (length o))
1797 h (cl-plusp (length o))
1798 (or (< (length h) (length o))
1799 (not (string= (substring h 0 (length o))
1801 (push (concat o " " h) gnugo-option-history))
1804 (args (read-string "GNU Go options: "
1805 (car gnugo-option-history)
1806 'gnugo-option-history))
1808 board-size user-color handicap komi minus-l infile)
1809 (loop for (var default opt &optional rx)
1810 in '((board-size 19 "--boardsize")
1811 (user-color "black" "--color" "\\(black\\|white\\)")
1812 (handicap 0 "--handicap")
1814 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1815 (infile nil "--infile" "[ ]*[^ ]+"))
1817 (or (when (string-match opt args)
1818 (let ((start (match-end 0)) s)
1819 (string-match (or rx "[0-9.]+") args start)
1820 (setq s (match-string 0 args))
1821 (if rx s (string-to-number s))))
1823 (gnugo-put :user-color user-color)
1824 (let ((proc-args (split-string args)))
1825 (gnugo-put :proc-args proc-args)
1826 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
1827 (current-buffer) name
1828 "--mode" "gtp" "--quiet"
1830 (set-process-sentinel proc 'gnugo-sentinel)
1831 ;; Emacs is too protective sometimes, blech.
1832 (set-process-query-on-exit-flag proc nil)
1833 (when (or minus-l infile)
1835 in '((board-size "query_boardsize")
1837 (handicap "get_handicap"))
1838 do (set prop (string-to-number (gnugo-query q)))))
1839 (gnugo-put :diamond (substring (process-name proc) 5))
1840 (gnugo-put :gnugo-color (gnugo-other user-color))
1841 (gnugo-put :highlight-last-move-spec
1842 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1843 (gnugo-put :lparen-ov (make-overlay 1 1))
1844 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1845 (overlay-put ov 'display ")")
1847 (let ((tree (vector (list (list '(:FF . 4) '(:GM . 1))))))
1848 (gnugo-put :sgf-gametree tree)
1849 (gnugo-put :sgf-collection (list tree))
1850 (gnugo-put :monkey (vector (aref tree 0) 0 0)))
1851 (gnugo--SZ! board-size)
1852 (loop with gb = (gnugo--blackp (gnugo-other user-color))
1853 for (property value &optional mogrifyp) in
1855 (:DT ,(format-time-string "%Y-%m-%d"))
1856 (:RU ,(if (string-match "--chinese-rules" args)
1859 (:AP ("gnugo.el" . ,gnugo-version))
1861 (,(if gb :PW :PB) ,(user-full-name))
1862 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
1863 ,@(when (not (zerop handicap))
1865 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1867 do (gnugo-note property value mogrifyp)))
1868 (gnugo-put :waiting-start (current-time))
1871 (run-hooks 'gnugo-board-mode-hook)
1874 ;;;---------------------------------------------------------------------------
1878 (defun gnugo (&optional new-game)
1879 "Run gnugo in a buffer, or resume a game in progress.
1880 Prefix arg means skip the game-in-progress check and start a new
1882 \\<gnugo-board-mode-map>
1883 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
1885 You are queried for additional command-line options (Emacs supplies
1886 \"--mode gtp --quiet\" automatically). Here is a list of options
1887 that gnugo.el understands and handles specially:
1889 --boardsize num Set the board size to use (5--19)
1890 --color <color> Choose your color ('black' or 'white')
1891 --handicap <num> Set the number of handicap stones (0--9)
1893 If there is already a game in progress you may resume it instead of
1894 starting a new one. See `gnugo-board-mode' documentation for more info."
1896 (let* ((all (let (acc)
1897 (dolist (buf (buffer-list))
1898 (when (gnugo-board-buffer-p buf)
1899 (push (cons (buffer-name buf) buf) acc)))
1902 (if (and (not new-game)
1904 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1905 (if (= 1 n) "" "s"))))
1910 (let ((sel (completing-read "Which one? " all nil t)))
1911 (if (string= "" sel)
1913 (assoc sel all))))))
1914 ;; set up a new board
1916 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
1917 (gnugo-goto-pos (format "A%d" half))
1918 (forward-char (* 2 (1- half)))
1919 (gnugo-put :last-user-bpos
1920 (gnugo-put :center-position
1921 (get-text-property (point) 'gnugo-position))))
1923 (gnugo-put :game-start-time (current-time))
1924 (let ((g (gnugo-get :gnugo-color))
1925 (n (or (gnugo--root-prop :HA) 0))
1926 (u (gnugo-get :user-color)))
1927 (gnugo-put :last-mover g)
1928 (when (or (and (gnugo--blackp u) (< 1 n))
1929 (and (gnugo--blackp g) (< n 2)))
1930 (gnugo-put :last-mover u)
1932 (gnugo-get-move g))))))
1934 ;;;---------------------------------------------------------------------------
1935 ;;; Load-time actions
1937 (unless gnugo-board-mode-map
1938 (setq gnugo-board-mode-map (make-sparse-keymap))
1939 (suppress-keymap gnugo-board-mode-map)
1940 (mapc (lambda (pair)
1941 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1942 '(("?" . describe-mode)
1943 ("\C-m" . gnugo-move)
1946 ("R" . gnugo-resign)
1948 ("Q" . gnugo-leave-me-alone)
1949 ("U" . gnugo-fancy-undo)
1950 ("\M-u" . gnugo-undo-one-move)
1951 ("u" . gnugo-undo-two-moves)
1952 ("\C-?" . gnugo-undo-two-moves)
1954 ("\C-l" . gnugo-refresh)
1955 ("\M-_" . gnugo-boss-is-near)
1956 ("_" . gnugo-boss-is-near)
1957 ("h" . gnugo-move-history)
1958 ("i" . gnugo-toggle-image-display-command)
1959 ("w" . gnugo-worm-stones)
1960 ("W" . gnugo-worm-data)
1961 ("d" . gnugo-dragon-stones)
1962 ("D" . gnugo-dragon-data)
1963 ("t" . gnugo-toggle-dead-group)
1964 ("g" . gnugo-toggle-grid)
1965 ("!" . gnugo-estimate-score)
1966 (":" . gnugo-command)
1967 (";" . gnugo-command)
1968 ("=" . gnugo-describe-position)
1969 ("s" . gnugo-write-sgf-file)
1970 ("\C-x\C-s" . gnugo-write-sgf-file)
1971 ("\C-x\C-w" . gnugo-write-sgf-file)
1972 ("l" . gnugo-read-sgf-file)
1973 ("F" . gnugo-display-final-score)
1974 ("A" . gnugo-switch-to-another)
1976 ([(down-mouse-1)] . gnugo-mouse-move)
1977 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1978 ([(down-mouse-3)] . gnugo-mouse-pass)
1979 ;; delving into the curiosities
1980 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1982 (unless (get 'help :gnugo-gtp-command-spec)
1984 ((sget (x) (get x :gnugo-gtp-command-spec))
1985 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1986 (plist-put (sget cmd) prop val)))
1987 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1990 (jam cmd (car ls) (cadr ls))
1991 (setq ls (cddr ls)))))))
1992 (cl-macrolet ((deffull (who &body body)
1993 (declare (indent 1))
1994 `(defgtp ',who :full (lambda (sel)
1998 (info "(gnugo)GTP command reference")
1999 (when sel (setq sel (intern (car sel))))
2000 (let (buffer-read-only pad cur spec output found)
2002 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2003 (goto-char (point-min))
2005 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2008 (setq pad (make-string (- (match-beginning 1)
2009 (match-beginning 0))
2013 (get (setq cur (intern (match-string 1)))
2014 :gnugo-gtp-command-spec))
2016 (note "handles this command completely"))
2017 (when (setq output (plist-get spec :output))
2018 (if (functionp output)
2019 (note "handles the output specially")
2021 (:discard (note "discards the output"))
2022 (:message (note "displays the output in the echo area")))))
2024 (setq found (match-beginning 0))))))
2025 (cond (found (goto-char found))
2027 (t (message "(no such command: %s)" sel)))))
2029 (deffull final_score
2030 (gnugo-display-final-score))
2036 :post-thunk (lambda ()
2037 (gnugo--unclose-game)
2038 (gnugo-put :last-mover nil)
2040 (gnugo--SZ! (string-to-number
2042 "query_boardsize")))
2046 (gnugo-read-sgf-file (car sel)))
2048 (deffull (undo gg-undo)
2052 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2053 (t (car sel)))))))))
2058 ;;;---------------------------------------------------------------------------
2059 ;;; The remainder of this file defines a simplified SGF-handling library.
2060 ;;; When/if it should start to attain generality, it should be split off into
2061 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2062 ;;; "gnugo/" prefix.
2064 (defconst gnugo/sgf-*r4-properties*
2065 '((AB "Add Black" setup list stone)
2066 (AE "Add Empty" game list point)
2067 (AN "Annotation" game simpletext)
2068 (AP "Application" root (simpletext . simpletext))
2069 (AR "Arrow" - list (point . point))
2070 (AS "Who adds stones" - simpletext) ; (LOA)
2071 (AW "Add White" setup list stone)
2072 (B "Black" move move)
2073 (BL "Black time left" move real)
2074 (BM "Bad move" move double)
2075 (BR "Black rank" game simpletext)
2076 (BT "Black team" game simpletext)
2077 (C "Comment" - text)
2078 (CA "Charset" root simpletext)
2079 (CP "Copyright" game simpletext)
2080 (CR "Circle" - list point)
2081 (DD "Dim points" - elist point) ; (inherit)
2082 (DM "Even position" - double)
2083 (DO "Doubtful" move none)
2084 (DT "Date" game simpletext)
2085 (EV "Event" game simpletext)
2086 (FF "Fileformat" root [number (1 . 4)])
2087 (FG "Figure" - (or none (number . simpletext)))
2088 (GB "Good for Black" - double)
2089 (GC "Game comment" game text)
2090 (GM "Game" root [number (1 . 20)])
2091 (GN "Game name" game simpletext)
2092 (GW "Good for White" - double)
2093 (HA "Handicap" game number) ; (Go)
2094 (HO "Hotspot" - double)
2095 (IP "Initial pos." game simpletext) ; (LOA)
2096 (IT "Interesting" move none)
2097 (IY "Invert Y-axis" game simpletext) ; (LOA)
2098 (KM "Komi" game real) ; (Go)
2100 (LB "Label" - list (point . simpletext))
2101 (LN "Line" - list (point . point))
2102 (MA "Mark" - list point)
2103 (MN "set move number" move number)
2104 (N "Nodename" - simpletext)
2105 (OB "OtStones Black" move number)
2106 (ON "Opening" game text)
2107 (OT "Overtime" game simpletext)
2108 (OW "OtStones White" move number)
2109 (PB "Player Black" game simpletext)
2110 (PC "Place" game simpletext)
2111 (PL "Player to play" setup color)
2112 (PM "Print move mode" - number) ; (inherit)
2113 (PW "Player White" game simpletext)
2114 (RE "Result" game simpletext)
2115 (RO "Round" game simpletext)
2116 (RU "Rules" game simpletext)
2117 (SE "Markup" - point) ; (LOA)
2118 (SL "Selected" - list point)
2119 (SO "Source" game simpletext)
2120 (SQ "Square" - list point)
2121 (ST "Style" root [number (0 . 3)])
2122 (SU "Setup type" game simpletext) ; (LOA)
2123 (SZ "Size" root (or number (number . number)))
2124 (TB "Territory Black" - elist point) ; (Go)
2125 (TE "Tesuji" move double)
2126 (TM "Timelimit" game real)
2127 (TR "Triangle" - list point)
2128 (TW "Territory White" - elist point) ; (Go)
2129 (UC "Unclear pos" - double)
2130 (US "User" game simpletext)
2132 (VW "View" - elist point) ; (inherit)
2133 (W "White" move move)
2134 (WL "White time left" move real)
2135 (WR "White rank" game simpletext)
2136 (WT "White team" game simpletext)
2137 (LT "Lose on time" setup simpletext))
2138 ;; r4-specific notes
2139 ;; - changed: DT FG LB RE RU SZ
2140 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2141 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2143 (defun gnugo/sgf-root-node (tree)
2144 (car (last (aref tree
2145 ;; Any bidx is fine, but we choose the last one since
2146 ;; usually the main line (bidx 0) is the longest.
2147 ;; Ugh, heuristics for the sake of performance. :-/
2148 (1- (length tree))))))
2150 (defun gnugo/sgf-read-file (filename)
2151 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2152 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2153 (put 'gnugo/sgf-*r4-properties* :keywords
2154 (mapcar (lambda (full)
2156 (intern (format ":%s" (car full)))))
2157 gnugo/sgf-*r4-properties*))))
2158 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2159 (put 'gnugo/sgf-*r4-properties* :specs
2160 (mapcar (lambda (full)
2161 (cons (car full) (cdddr full)))
2162 gnugo/sgf-*r4-properties*))))
2165 ((sw () (skip-chars-forward " \t\n"))
2166 (x (end) (let ((beg (point))
2168 (:end (lambda (char) (= ?\] char)))
2169 (:mid (lambda (char) (= ?\: char)))
2170 (t (lambda (char) (or (= ?\: char)
2173 (while (not (funcall endp (setq c (following-char))))
2179 ((looking-at "\\s-+")
2180 (delete-region (point) (match-end 0))
2182 (t (forward-char 1))))
2183 (buffer-substring-no-properties beg (point))))
2184 (one (type end) (let ((s (progn
2189 ;; blech, begone bu"tt"-ugly blatherings
2190 ;; (but bide brobdingnagian boards)...
2191 (if (and (string= "tt" s)
2196 ((simpletext color) s)
2197 ((number real double) (string-to-number s))
2200 (t (error "Unhandled type: %S" type)))))
2201 (val (spec) (cond ((symbolp spec)
2204 ;; todo: check range here.
2205 (one (aref spec 0) :end))
2206 ((eq 'or (car spec))
2207 (let ((v (one (cadr spec) t)))
2208 (if (= ?\] (following-char))
2211 ;; todo: this assumes `spec' has the form
2212 ;; (or foo (foo . bar))
2213 ;; i.e., foo is not rescanned. e.g., `SZ'.
2214 ;; probably this assumption is consistent
2215 ;; w/ the SGF authors' desire to make the
2216 ;; parsing easy, but you never know...
2217 (cons v (one (cdaddr spec) :end)))))
2218 (t (cons (one (car spec) :mid)
2219 (one (cdr spec) :end)))))
2220 (short (who) (when (eobp)
2221 (error "Unexpected EOF while reading %s" who)))
2222 (atvalp () (= ?\[ (following-char)))
2223 (PROP () (let (name spec ltype)
2224 (sw) (short 'property)
2225 (when (looking-at "[A-Z]")
2226 (setq name (read (current-buffer))
2227 spec (cdr (assq name specs)))
2230 (cdr (assq name keywords))
2231 (prog1 (if (= 1 (length spec))
2233 (unless (memq (setq ltype (car spec))
2235 (error "Bad spec: %S" spec))
2236 (if (and (eq 'elist ltype) (sw)
2239 (let ((type (cadr spec))
2241 (while (and (sw) (atvalp)
2242 (setq mo (val type)))
2247 (forward-char 1))))))
2248 (morep () (and (sw) (not (eobp))))
2249 (seek (c) (and (morep) (= c (following-char))))
2250 (seek-into (c) (when (seek c)
2253 (NODE () (when (seek-into ?\;)
2255 while (setq prop (PROP))
2257 (when (eq :SZ (car prop))
2258 (setq SZ (cdr prop)))
2265 (push (setq node (NODE))
2270 (loop while (seek ?\()
2276 (insert-file-contents filename)
2278 collect (apply 'vector (TREE nil)))))))
2280 (defun gnugo/sgf-hang-from-root (tree)
2281 (let ((ht (make-hash-table :test 'eq))
2282 (leaves (append tree nil)))
2286 with rh ; rectified history
2287 with bp ; branch point
2289 until (setq bp (gethash node ht))
2291 (push node rh) ; good for now: ½τ
2295 ;; first run: main line
2297 ;; subsequent runs: grafts (value discarded)
2299 ;; Maintain order of ‘leaves’.
2300 (let ((was (cdr bp)))
2301 (if (gnugo--nodep (car was))
2305 (setq tree (hang (pop leaves)))
2306 (mapc #'hang leaves)
2309 (defun gnugo/sgf-write-file (collection filename)
2310 ;; take responsibility for our actions
2311 (let ((me (cons "gnugo.el" gnugo-version)))
2312 (dolist (tree collection)
2313 (gnugo--set-root-prop :AP me tree)))
2315 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2316 (specs (mapcar (lambda (full)
2317 (cons (intern (format ":%s" (car full)))
2319 gnugo/sgf-*r4-properties*))
2321 ;; todo: escape special chars for `text' and `simpletext'.
2323 ((>>one (v) (insert (format "[%s]" v)))
2324 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2325 (>>nl () (cond ((memq name aft-newline-appreciated)
2327 ((< 60 (current-column))
2335 (insert (substring (symbol-name name) 1))
2338 (setq spec (cdr (assq name specs)))
2342 (let ((>> (if (consp (cadr spec))
2345 (dolist (little-v v)
2347 (funcall >> little-v)
2354 (loop initially (insert ";")
2358 (unless (zerop (current-column))
2362 (funcall (if (gnugo--nodep x)
2368 (dolist (tree collection)
2369 (>>tree (gnugo/sgf-hang-from-root tree)))
2371 (write-file filename)))))
2373 ;;; gnugo.el ends here