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 'ascii-art-to-unicode) ; for `aa2u'
79 (require 'time-date) ; for `time-subtract'
81 ;;;---------------------------------------------------------------------------
84 (defconst gnugo-version "2.3.1"
85 "Version of gnugo.el currently loaded.
86 This follows a MAJOR.MINOR.PATCH scheme.")
88 ;;;---------------------------------------------------------------------------
89 ;;; Variables for the uninquisitive programmer
91 (defvar gnugo-program "gnugo"
92 "Command to start an external program that speaks GTP, such as \"gnugo\".
93 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
94 the command `gnugo' will prefix OPTIONS in its default offering when it
95 queries you for additional options. It is an error for \"--mode\" to appear
98 For more information on GTP and GNU Go, feel free to visit:
99 http://www.gnu.org/software/gnugo")
101 (defvar gnugo-board-mode-map nil
102 "Keymap for GNUGO Board mode.")
104 (defvar gnugo-board-mode-hook nil
105 "Hook run when entering GNUGO Board mode.")
107 (defvar gnugo-inhibit-refresh nil
108 "Used in `gnugo-post-move-hook'.")
110 (defvar gnugo-post-move-hook nil
111 "Normal hook run after a move and before the board is refreshed.
112 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
113 (setq gnugo-inhibit-refresh t)
114 Initially, when `run-hooks' is called, the current buffer is the GNUGO
115 Board buffer of the game. Hook functions that switch buffers must take
116 care not to call (directly or indirectly through some other function)
117 `gnugo-put' or `gnugo-get' after the switch.")
119 (defvar gnugo-animation-string
120 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
121 (concat jam jam jam jam jam
122 ;; "SECRET MESSAGE HERE"
123 blink blink blink blink blink blink blink blink
124 ;; Playing go is like fighting ignorance: when you think you have
125 ;; surrounded something by knowing it very well it often turns
126 ;; out that in the time you spent deepening this understanding,
127 ;; other areas of ignorance have surrounded you.
128 spin spin spin spin spin spin spin spin spin
129 ;; Playing go is not like fighting ignorance: what one person
130 ;; knows many people may come to know; knowledge does not build
131 ;; solely move by move. Wisdom, on the other hand...
133 "String whose individual characters are used for animation.
134 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
135 render the stones in their respective result groups as the first character
136 in the string, then the next, and so on.")
138 (defvar gnugo-mode-line "~b ~w :~m :~u"
139 "A `mode-line-format'-compliant value for GNUGO Board mode.
140 If a single string, the following special escape sequences are
141 replaced with their associated information:
142 ~b,~w black,white captures (a number)
143 ~p current player (black or white)
145 ~t time waiting for the current move
146 ~u time taken for the Ultimate (most recent) move
147 The times are in seconds, or \"-\" if that information is not available.
148 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
150 (defvar gnugo-X-face 'font-lock-string-face
151 "Name of face to use for X (black) stones.")
153 (defvar gnugo-O-face 'font-lock-builtin-face
154 "Name of face to use for O (white) stones.")
156 (defvar gnugo-grid-face 'default
157 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
159 ;;;---------------------------------------------------------------------------
160 ;;; Variables for the inquisitive programmer
162 (defconst gnugo-font-lock-keywords
163 '(("X" . gnugo-X-face)
164 ("O" . gnugo-O-face))
165 "Font lock keywords for `gnugo-board-mode'.")
167 (defvar gnugo-option-history nil)
169 (defvar gnugo-state nil) ; hint: C-c C-p
172 (defvar gnugo-xpms nil))
174 ;;;---------------------------------------------------------------------------
175 ;;; Support functions
177 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
178 (compare-strings s1 beg1 nil s2 beg2 nil))
180 (defun gnugo-put (key value)
181 "Associate move/game/board-specific property KEY with VALUE.
183 There are many properties, each named by a keyword, that record and control
184 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
185 of properties, stored in the hash table `gnugo-state'. Here we document
186 some of the more stable properties. You may wish to use them as part of
187 a `gnugo-post-move-hook' function, for example. Be careful to preserve
188 the current buffer as `gnugo-state' is made into a buffer-local variable.
189 NOTE: In the following, \"see foo\" actually means \"see foo source or
190 you may never really understand to any degree of personal satisfaction\".
192 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
194 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
196 :game-over -- nil until game over at which time its value is set to
197 the alist `((live GROUP ...) (dead GROUP ...))'
199 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
200 a simple list of one or more gametrees, updated in
201 conjunction w/ :sgf-gametree and :monkey
203 :sgf-gametree -- one of the gametrees in :sgf-collection
205 :monkey -- vector of three elements:
206 MEM, a pointer to one of the branches in the gametree;
207 BIDX, the index of the \"current branch\"; and
208 COUNT, the number of moves from the beginning of the game
210 :gnugo-color -- either \"black\" or \"white\"
214 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
217 :black-captures -- these are strings since gnugo.el doesn't do anything
218 :white-captures w/ the information besides display it in the mode line;
219 gory details in functions `gnugo-propertize-board-buffer'
220 and `gnugo-merge-showboard-results' (almost more effort
221 than they are worth!)
223 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
224 `gnugo-toggle-image-display' and `gnugo-refresh',
225 as well as gnugo-xpms.el (available elsewhere)
227 :all-yy -- list of 46 keywords used as the `category' text property
228 (so that their plists, typically w/ property `display' or
229 `do-not-display') are consulted by the Emacs display engine;
230 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
231 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
233 :lparen-ov -- overlays shuffled about to indicate the last move; only
234 :rparen-ov one is used when displaying using images
236 :last-user-bpos -- board position; keep the hapless human happy
238 As things stabilize probably more info will be added to this docstring."
240 (puthash key value gnugo-state))
242 (defun gnugo-get (key)
243 "Return the move/game/board-specific value for KEY.
245 (gethash key gnugo-state))
247 (defun gnugo-describe-internal-properties ()
248 "Pretty-print `gnugo-state' properties in another buffer.
249 Handle the big, slow-to-render, and/or uninteresting ones specially."
251 (let ((buf (current-buffer))
252 (d (gnugo-get :diamond))
253 (acc (loop for key being the hash-keys of gnugo-state
254 using (hash-values val)
258 (format "hash: %X (%d images)"
264 (let ((mem (aref val 0)))
269 (switch-to-buffer (get-buffer-create
270 (format "%s*GNUGO Board Properties*"
271 (gnugo-get :diamond))))
274 (setq truncate-lines t)
276 (let ((standard-output (current-buffer)))
278 (goto-char (point-min))
279 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
283 (while (re-search-forward rx (point-max) t)
284 (let ((pos (get-text-property (string-to-number (match-string 1))
285 'gnugo-position buf)))
286 (delete-region (+ 2 (match-beginning 0)) (point))
287 (insert (format " %S" pos))))))
288 (message "%d properties" (length acc))))
290 (defun gnugo-board-buffer-p (&optional buffer)
291 "Return non-nil if BUFFER is a GNUGO Board buffer."
292 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
294 (defun gnugo-board-user-play-ok-p (&optional buffer)
295 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
296 (with-current-buffer (or buffer (current-buffer))
297 (and gnugo-state (not (gnugo-get :waitingp)))))
299 (defsubst gnugo--blackp (string)
300 (string= "black" string))
302 (defun gnugo-other (color)
303 (if (gnugo--blackp color) "white" "black"))
305 (defun gnugo-gate (&optional in-progress-p)
306 (unless (gnugo-board-buffer-p)
307 (user-error "Wrong buffer -- try M-x gnugo"))
308 (unless (gnugo-get :proc)
309 (user-error "No \"gnugo\" process!"))
310 (when (gnugo-get :waitingp)
311 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
312 (gnugo-get :user-color)))
313 (when (and (gnugo-get :game-over) in-progress-p)
314 (user-error "Sorry, game over")))
316 (defun gnugo-sentinel (proc string)
317 (let ((status (process-status proc)))
318 (when (memq status '(exit signal))
319 (let ((buf (process-buffer proc)))
320 (when (buffer-live-p buf)
321 (with-current-buffer buf
322 (setq mode-line-process
324 (propertize (car (split-string string))
325 'face 'font-lock-warning-face)
327 (when (eq proc (gnugo-get :proc))
328 (gnugo-put :proc nil))))))))
330 (defun gnugo--begin-exchange (proc filter line)
331 (declare (indent 2)) ; good time, for a rime
332 ; nice style, for a wile...
333 (set-process-filter proc filter)
334 (process-send-string proc line)
335 (process-send-string proc "\n"))
337 (defun gnugo--q (fmt &rest args)
338 "Send formatted command \"FMT ARGS...\"; wait for / return response.
339 The response is a string whose first two characters indicate the
340 status of the command. See also `gnugo-query'."
341 (when (gnugo-get :waitingp)
342 (user-error "Sorry, still waiting for %s to play"
343 (gnugo-get :gnugo-color)))
344 (let ((proc (gnugo-get :proc)))
345 (process-put proc :incomplete t)
346 (process-put proc :srs "") ; synchronous return stash
347 (gnugo--begin-exchange
348 proc (lambda (proc string)
349 (let ((full (concat (process-get proc :srs)
351 (process-put proc :srs full)
352 (unless (numberp (gnugo--compare-strings
353 full (max 0 (- (length full)
356 (process-put proc :incomplete nil))))
359 (apply #'format fmt args)))
360 (while (process-get proc :incomplete)
361 (accept-process-output proc 30))
362 (prog1 (substring (process-get proc :srs) 0 -2)
363 (process-put proc :srs ""))))
365 (defun gnugo-query (message-format &rest args)
366 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
367 Return a string that omits the first two characters (corresponding
368 to the status indicator in the Go Text Protocol). Use this function
369 when you are sure the command cannot fail."
370 (substring (apply 'gnugo--q message-format args)
373 (defun gnugo-lsquery (message-format &rest args)
374 (split-string (apply 'gnugo-query message-format args)))
376 (defun gnugo--root-node (&optional tree)
377 (gnugo/sgf-root-node (or tree (gnugo-get :sgf-gametree))))
379 (defsubst gnugo--root-prop (prop &optional tree)
380 (cdr (assq prop (gnugo--root-node tree))))
382 (defun gnugo--set-root-prop (prop value &optional tree)
383 (let* ((root (gnugo--root-node tree))
384 (cur (assq prop root)))
387 (push (cons prop value)
388 (cdr (last root))))))
390 (defun gnugo-goto-pos (pos)
391 "Move point to board position POS, a letter-number string."
392 (goto-char (point-min))
393 (forward-line (- (1+ (gnugo-get :SZ))
394 (string-to-number (substring pos 1))))
396 (forward-char (+ (if (= 32 (following-char)) 1 2)
397 (* 2 (- (let ((letter (aref pos 0)))
403 (defun gnugo-f (frag)
404 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
406 (defun gnugo-yang (c)
407 (cdr (assq c '((?+ . hoshi)
409 (?X . (bmoku . bpmoku))
410 (?O . (wmoku . wpmoku))))))
412 (defun gnugo-yy (yin yang &optional momentaryp)
413 (gnugo-f (format "%d-%s"
414 yin (cond ((and (consp yang) momentaryp) (cdr yang))
415 ((consp yang) (car yang))
418 (defun gnugo-toggle-image-display ()
419 (unless (and (fboundp 'display-images-p) (display-images-p))
420 (user-error "Display does not support images, sorry"))
421 (require 'gnugo-xpms)
422 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
423 (user-error "Could not load `gnugo-xpms', sorry"))
424 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
425 (unless (eq fresh (gnugo-get :xpms))
426 (gnugo-put :xpms fresh)
427 (gnugo-put :all-yy nil)))
428 (let* ((new (not (gnugo-get :display-using-images)))
429 (act (if new 'display 'do-not-display)))
431 (setcar (symbol-plist yy) act))
432 (or (gnugo-get :all-yy)
434 (prog1 (mapcar (lambda (ent)
436 (yy (gnugo-yy (cdr k) (car k))))
437 (setplist yy `(not-yet ,(cdr ent)))
440 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
442 (gnugo-put :w-imul (car imul))
443 (gnugo-put :h-imul (cdr imul)))))))
444 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
445 (gnugo-put :highlight-last-move-spec
448 (get (gnugo-yy (get-text-property p 'gnugo-yin)
449 (get-text-property p 'gnugo-yang)
453 (gnugo-get :default-highlight-last-move-spec)))
454 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
455 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
456 (mapc 'delete-overlay (cdar group))
457 (setcdr (car group) nil))
458 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
459 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
460 (gnugo-put :display-using-images new)))
462 (defun gnugo-toggle-grid ()
463 "Turn the grid around the board on or off."
465 (funcall (if (memq :nogrid buffer-invisibility-spec)
466 'remove-from-invisibility-spec
467 'add-to-invisibility-spec)
469 (save-excursion (gnugo-refresh)))
471 (defun gnugo-propertize-board-buffer ()
473 (insert (substring (gnugo--q "showboard") 3))
474 (let* ((grid-props (list 'invisible :nogrid
475 'font-lock-face gnugo-grid-face))
476 (%gpad (gnugo-f 'gpad))
477 (%gspc (gnugo-f 'gspc))
478 (%lpad (gnugo-f 'lpad))
479 (%rpad (gnugo-f 'rpad))
480 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
481 (size (gnugo-get :SZ))
482 (size-string (number-to-string size)))
483 (goto-char (point-min))
484 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
485 (skip-chars-forward " ")
486 (put-text-property (1- (point)) (point) 'category %gpad)
487 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
489 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
490 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
491 (let* ((row (match-string-no-properties 1))
493 (other-edge (+ edge (* 2 size) -1))
494 (right-empty (+ other-edge (length row) 1))
495 (top-p (string= size-string row))
496 (bot-p (string= "1" row)))
497 (let* ((nL (- edge 1 (length size-string)))
499 (ov (make-overlay nL nR (current-buffer) t)))
500 (add-text-properties nL nR grid-props)
501 ;; We redundantly set `invisible' in the overlay to workaround
502 ;; a display bug whereby text *following* the overlaid text is
503 ;; displayed with the face of the overlaid text, but only when
504 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
505 ;; This has something to do w/ the bletcherous `before-string'.
506 (overlay-put ov 'invisible :nogrid)
507 (overlay-put ov 'category %lpad))
508 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
510 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
511 (truncate (- p edge) 2))
513 (yin (let ((A-p (= edge p))
514 (Z-p (= (1- other-edge) p)))
515 (cond ((and top-p A-p) 1)
524 (yang (gnugo-yang (char-after p))))
525 (add-text-properties p (1+ p)
535 (gnugo-position gnugo-yin))))
536 (unless (= (1- other-edge) p)
537 (add-text-properties (1+ p) (+ 2 p) ispc-props)
538 (put-text-property p (+ 2 p) 'intangible ival)))
539 (add-text-properties (1+ other-edge) right-empty grid-props)
540 (goto-char right-empty)
541 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
542 (let ((prop (if (string= "WH" (match-string 1))
545 (beg (match-beginning 2))
547 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
548 (gnugo-put prop (match-string-no-properties 2))))
550 (put-text-property right-empty (point) 'category %rpad)
552 (add-text-properties (1- (point)) (point-max) grid-props)
553 (skip-chars-forward " ")
554 (put-text-property (1- (point)) (point) 'category %gpad)
555 (put-text-property (point) (progn (end-of-line) (point))
558 (defun gnugo-merge-showboard-results ()
559 (let ((aft (substring (gnugo--q "showboard") 3))
560 (adj 1) ; string to buffer position adjustment
562 (sync "[0-9]* stones$")
563 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
564 ;; restrictive a condition that fails in the case of:
567 ;; ... WHITE has captured 1 stones
570 ;; ... WHITE has captured 14 stones
573 ;; where the after count has more digits than the before count,
574 ;; but shares the same leading digits. In this case, the result
575 ;; of `compare-strings' points to the SPC following the before
576 ;; count (indicated by caret in this example).
578 (bef (buffer-substring-no-properties (point-min) (point-max)))
579 (bef-start 0) (bef-idx 0)
580 (aft-start 0) (aft-idx 0)
581 aft-sync-backtrack mis inc cut new very-strange)
582 (while (numberp (setq mis (gnugo--compare-strings
585 (setq aft-sync-backtrack nil
586 inc (if (cl-minusp mis)
589 bef-idx (+ bef-start inc)
590 aft-idx (+ aft-start inc)
591 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
594 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
595 (let ((peek (1- aft-idx)))
596 (while (not (= 32 (aref aft peek)))
597 (setq peek (1- peek)))
598 (setq aft-sync-backtrack (1+ peek))))
602 (if aft-sync-backtrack
603 (- aft-sync-backtrack aft-idx)
606 (if aft-sync-backtrack
607 (let* ((asb aft-sync-backtrack)
608 (l-p (get-text-property cut :gnugo-cf))
611 (keep (text-properties-at cut)))
612 (setq new (substring aft asb (string-match " " aft asb)))
613 (plist-put keep :gnugo-cf (cons (length new) capprop))
614 (gnugo-put capprop new)
615 (delete-char old-len)
616 (insert (apply 'propertize new keep))
617 (incf adj (- (length new) old-len)))
618 (setq new (aref aft aft-idx))
619 (insert-and-inherit (char-to-string new))
620 (let ((yin (get-text-property cut 'gnugo-yin))
621 (yang (gnugo-yang new)))
622 (add-text-properties cut (1+ cut)
626 ,(gnugo-yy yin yang))))
628 ;; do this last to avoid complications w/ font lock
629 ;; (this also means we cannot include `intangible' in `front-sticky')
630 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
631 (put-text-property cut (1+ cut) 'intangible very-strange))))))
633 (defsubst gnugo--move-prop (node)
637 (defun gnugo--as-pos-func (size)
638 (lexical-let ((size size))
643 (let ((col (aref cc 0)))
645 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
646 (- size (- (aref cc 1) ?a))))))))
648 (defun gnugo-move-history (&optional rsel)
649 "Determine and return the game's move history.
650 Optional arg RSEL controls side effects and return value.
651 If nil, display the history in the echo area as \"(N moves)\"
652 followed by the space-separated list of moves. When called
653 interactively with a prefix arg (i.e., RSEL is `(4)'), display
654 similarly, but suffix with the mover (either \":B\" or \":W\").
655 If RSEL is the symbol `car' return the most-recent move; if
656 `cadr', the next-to-most-recent move; if `count' the number of
657 moves thus far; if `two' the last two moves as a list, oldest last.
659 For all other values of RSEL, do nothing and return nil."
661 (let* ((monkey (gnugo-get :monkey))
662 (mem (aref monkey 0))
663 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
667 ((as-pos-maybe (x) (if (string= "resign" x)
670 (next (byp) (when (setq node (pop mem)
671 mprop (gnugo--move-prop node))
672 (setq move (as-pos-maybe (cdr mprop)))
674 (format "%s%s" move (car mprop))
678 (tell () (message "(%d moves) %s"
680 (mapconcat 'identity (nreverse acc) " ")))
681 (finish (byp) (while mem (next byp)) (tell)))
686 (`cadr (nn) (car (nn)))
687 (`count (aref monkey 2))
691 (defun gnugo-frolic-in-the-leaves ()
692 "Display the game tree in a *GNUGO Frolic* buffer.
693 This looks something like:
696 2 W -- K10 K10 K10 K10
715 with 0, 1, ... N (in this case N is 3) in the header line
716 to indicate the branches. Branch 0 is the \"main line\".
717 Point (* in this example) indicates the current position,
718 and moves not actually on the game tree (e.g., E7, branch 3)
719 are dimmed. The buffer is in View minor mode."
721 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
723 ;; todo: use defface once we finally succumb to ‘customize’
724 (dimmed-node-face (list :inherit 'default
725 :foreground "gray50"))
726 (tree (gnugo-get :sgf-gametree))
727 (seen (make-hash-table :test 'eq))
728 (soil (make-hash-table :test 'eq))
729 (width (length tree))
730 (lanes (number-sequence 0 (1- width)))
731 (monkey (gnugo-get :monkey))
732 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
733 (at (car (aref monkey 0)))
734 (bidx (aref monkey 1))
735 (max-move-num (aref monkey 2))
736 (eert (make-vector width nil))
742 (propertize s 'face face))
743 (fsi (fmt &rest args)
744 (insert (apply 'format fmt args))))
746 (let ((order (make-hash-table :test 'eq))
747 (monkey-on-main-line (zerop bidx))
749 ;; monkey knows a lot
750 (loop with move-num = (1+ max-move-num)
752 for node in (aref monkey 0)
753 do (puthash node bidx seen)
754 if (gnugo--move-prop node)
757 (puthash node (decf move-num) order))
759 (unless monkey-on-main-line
760 (setq fixup (apply 'vector acc)))
761 (aset eert bidx acc)))
762 ;; but monkey does not know everything
766 with (bef acc node fork cur)
767 for ls on (aref tree bx)
768 do (if (setq node (car ls)
772 (push other (gethash node soil))))
773 (let ((move-num (gethash node order)))
775 (assert (and (not monkey-on-main-line)
778 while (< bx (on old))
779 do (puthash old bx seen))
780 (when (< move-num (length fixup))
781 (link (aref fixup move-num))))
783 (when (setq bef (copy-sequence (aref eert fork)))
784 (setcdr (nthcdr (1- move-num) bef)
786 (aset eert bx (or bef acc))
788 (puthash node (incf move-num)
790 (setq max-move-num (max max-move-num
794 (puthash node bx seen)
795 (when (gnugo--move-prop node)
799 (switch-to-buffer buf)
802 (buffer-disable-undo)
804 (setq header-line-format
805 (concat (make-string 11 ?\s)
806 (mapconcat (lambda (n)
812 from 1 upto max-move-num
816 initially (fsi "%3d %s -- "
817 n (aref ["W" "B"] (logand 1 n)))
819 do (let* ((node (pop (aref eert bx)))
822 (s (cond ((not node) "")
823 ((not (setq move (gnugo--move-prop node))) "-")
824 (t (funcall as-pos (cdr move))))))
825 ;; todo: move this into "breathe in"
826 (when (and ok (setq br (gethash node soil)))
827 (setq br (delq bx (mapcar #'on br)))
828 (when (and br (car (aref eert bx)))
830 ;; do not point w/ a fist
832 (push (cons bx (sort br '<))
835 (cond ((and (eq at node)
838 (setq finish (point)))
839 (emph s (list :inherit 'default
840 :foreground (frame-parameter
841 nil 'cursor-color))))
843 (emph s dimmed-node-face))
846 (when (progn (newline)
847 (setq forks (nreverse forks)))
848 (let* ((margin (make-string 11 ?\s))
849 (count (length forks))
850 (heads (mapcar #'car forks))
851 (tails (mapcar #'cdr forks)))
853 ((spaced (lanes func)
854 (mapconcat func lanes " "))
855 ;; live to play ~ ~ ()
856 ;; play to learn (+) (-) . o O
857 ;; learn to live --ttn .M. _____U
858 (dashed (lanes func) ;;; _____ ^^^^
859 (mapconcat func lanes "-----"))
861 (spaced lanes (lambda (bx)
865 (pad-unless (condition)
876 do (let* ((one (car ls))
879 (mapcar 'car (cdr ls))
881 (apply 'append (mapcar 'cdr bef))))
884 (end (car (last ord))))
886 ((also (b e) (cnxn (number-sequence b e)
891 (pad-unless (zerop beg))
892 (dashed (number-sequence beg end)
894 (cond ((memq bx ord) "+")
897 (pad-unless (>= end width))
898 (also (1+ end) (1- width))
901 (edge (apply 'append tails))
902 ;; NB: This requires ascii-art-to-unicode.el 1.5 or later.
903 (aa2u (line-beginning-position
904 (- (1+ (length forks))))
908 (recenter (- (count-lines (line-beginning-position) (point-max)))))
911 (defun gnugo-boss-is-near ()
912 "Do `bury-buffer' until the current one is not a GNU Board."
914 (while (gnugo-board-buffer-p)
917 (defsubst gnugo--passp (string)
918 (string= "PASS" string))
920 (defsubst gnugo--no-regrets (monkey tree)
921 (eq (aref tree (aref monkey 1))
924 (defun gnugo-note (property value &optional mogrifyp)
926 (let ((sz (gnugo-get :SZ)))
928 ((mog (pos) (if (gnugo--passp pos)
930 (let* ((col (aref pos 0))
931 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
932 (two (+ ?a (- sz (string-to-number
933 (substring pos 1))))))
934 (format "%c%c" one two)))))
935 (setq value (if (consp value)
938 (let* ((pair (cons property value))
940 (monkey (gnugo-get :monkey))
941 (mem (aref monkey 0)))
942 (if (memq property '(:B :W))
943 (let ((tree (gnugo-get :sgf-gametree))
944 (bidx (aref monkey 1)))
945 ;; Detect déjà-vu. That is, when placing "A", avoid:
951 ;; (such "variations" do not actually vary!) in favor of:
957 ;; This presumes ‘bidx’ is 0 (main line) and that
958 ;; all growth should occur on the main line.
961 (rotatef (aref tree bidx)
965 with count = (length tree)
968 ;; Start with latest / highest likelihood for hit.
969 ;; todo: prune unfeasible candidates
970 from 0 above (- count)
971 if (setq bx (mod i count)
973 ;; todo: early termination based on move number
974 (loop for m on (aref tree bx)
977 (when (equal pair (assoc property (car m)))
984 ;; (message "déjà-vu! %d follows %d" bidx bx)
991 ;; (message "new %d" bidx)
992 (unless (gnugo--no-regrets monkey tree)
993 ;; <grumble grumble> SGF sez "move" node in the root
994 ;; position of a (sub-)gametree is "bad style". :-/
995 (let ((where (memq tree (gnugo-get :sgf-collection))))
996 (setq tree (apply 'vector (append tree (list mem))))
998 (gnugo-put :sgf-gametree tree)
999 (setcar where tree)))
1001 (aset tree bidx mem))))
1002 (setf (aref monkey 0) mem)
1003 (incf (aref monkey 2)))
1004 (setcdr (last (car mem)) fruit))))
1006 (defun gnugo-close-game (end-time resign)
1007 (gnugo-put :game-end-time end-time)
1008 (let ((now (or end-time (current-time))))
1009 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1011 (gnugo-put :game-over
1012 (if (or (eq t resign)
1013 (and (stringp resign)
1014 (string-match "[BW][+][Rr]esign" resign)))
1016 ((ls (color) (mapcar
1021 (gnugo-query "worm_stones %s" color)
1023 (let ((live (append (ls "black") (ls "white"))))
1026 (let ((dd (gnugo-query "dragon_data"))
1027 (start 0) mem color ent live dead)
1028 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1030 (setq mem (match-string 1 dd)
1031 color (match-string 2 dd)
1033 ent (cons (list color)
1034 (sort (gnugo-lsquery "dragon_stones %s" mem)
1036 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1038 (if (match-string 2 dd)
1041 (setq start (match-end 0)))
1045 (defun gnugo--unclose-game ()
1046 (dolist (prop '(:game-over ; all those in -close-game
1049 (gnugo-put prop nil))
1050 (let* ((root (gnugo--root-node))
1051 (cur (assq :RE root)))
1053 (assert (not (eq cur (car root))) nil
1054 ":RE at head of root node: %S"
1058 (defun gnugo-push-move (userp move)
1059 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
1060 (start (gnugo-get :waiting-start))
1061 (now (current-time))
1062 (resignp (string= "resign" move))
1063 (passp (gnugo--passp move))
1064 (head (gnugo-move-history 'car))
1065 (onep (and head (gnugo--passp head)))
1066 (donep (or resignp (and onep passp))))
1068 (gnugo-merge-showboard-results))
1069 (gnugo-put :last-mover color)
1071 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1072 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
1074 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1076 (gnugo-close-game now resignp))
1077 (gnugo-put :waiting-start (and (not donep) now))
1080 (defun gnugo-venerate (yin yang)
1081 (let* ((fg-yy (gnugo-yy yin yang))
1082 (fg-disp (or (get fg-yy 'display)
1083 (get fg-yy 'do-not-display)))
1084 (fg-data (plist-get (cdr fg-disp) :data))
1085 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1086 (bg-disp (or (get bg-yy 'display)
1087 (get bg-yy 'do-not-display)))
1088 (bg-data (plist-get (cdr bg-disp) :data))
1092 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1093 (setq start (match-end 0))
1094 (string-to-number (match-string 1 s)))))
1095 (while (and (not (cl-minusp ncolors))
1096 (string-match ",\n" s start))
1097 (setq start (match-end 0)
1098 ncolors (1- ncolors)))
1099 (string-match "\"" s start)
1101 (new (copy-sequence fg-data))
1102 (lx (length fg-data))
1103 (sx (funcall bop fg-data))
1104 (sb (funcall bop bg-data))
1105 (color-key (aref new sx))) ; blech, heuristic
1107 (when (and (not (= color-key (aref new sx)))
1108 (cl-plusp (random 4)))
1109 (aset new sx (aref bg-data sb)))
1112 (create-image new 'xpm t :ascent 'center)))
1114 (defun gnugo-refresh (&optional nocache)
1115 "Update GNUGO Board buffer display.
1116 While a game is in progress, parenthesize the last-played stone (no parens
1117 for pass). If the buffer is currently displayed in the selected window,
1118 recenter the board (presuming there is extra space in the window). Update
1119 the mode line. Lastly, move point to the last position played by the user,
1120 if that move was not a pass.
1122 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1123 be slow. (This should normally be unnecessary; specify it only if the display
1124 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1127 (when (and nocache (not (gnugo-get :waitingp)))
1128 (gnugo-propertize-board-buffer))
1129 (let* ((last-mover (gnugo-get :last-mover))
1130 (other (gnugo-other last-mover))
1131 (move (gnugo-move-history 'car))
1132 (game-over (gnugo-get :game-over))
1136 (let ((l-ov (gnugo-get :lparen-ov))
1137 (r-ov (gnugo-get :rparen-ov)))
1138 (if (member move '("PASS" "resign"))
1139 (mapc 'delete-overlay (list l-ov r-ov))
1140 (gnugo-goto-pos move)
1142 (hspec (gnugo-get :highlight-last-move-spec))
1143 (display-value (nth 0 hspec))
1144 (l-offset (nth 1 hspec))
1145 (l-new-pos (+ p l-offset))
1146 (r-action (nth 2 hspec)))
1147 (overlay-put l-ov 'display
1148 (if (functionp display-value)
1149 (funcall display-value p)
1151 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1153 (funcall r-action r-ov)
1154 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1156 (rename-buffer (concat (gnugo-get :diamond)
1158 (format "%s(game over)"
1159 (if (string= move "resign")
1160 (concat move "ation ")
1162 (format "%s(%s to play)"
1163 (if move (concat move " ") "")
1167 (let ((live (cdr (assq 'live game-over)))
1168 (dead (cdr (assq 'dead game-over)))
1170 (unless (eq game-over (get-text-property 1 'game-over))
1171 (dolist (group (append live dead))
1172 (dolist (pos (cdr group))
1173 (gnugo-goto-pos pos)
1175 (put-text-property p (1+ p) 'group group)))
1176 (put-text-property 1 2 'game-over game-over))
1177 (dolist (group live)
1178 (when (setq pall (cdar group))
1179 (mapc 'delete-overlay pall)
1180 (setcdr (car group) nil)))
1181 (dolist (group dead)
1182 (unless (cdar group)
1183 (let (ov pall c (color (caar group)))
1184 (setq c (if (gnugo--blackp color) "x" "o"))
1185 (dolist (pos (cdr group))
1186 (gnugo-goto-pos pos)
1187 (setq p (point) ov (make-overlay p (1+ p)))
1190 (if (gnugo-get :display-using-images)
1191 ;; respect the dead individually; it takes more time
1192 ;; but that's not a problem (for them)
1193 (gnugo-venerate (get-text-property p 'gnugo-yin)
1194 (gnugo-yang (aref (upcase c) 0)))
1195 (propertize c 'face 'font-lock-warning-face)))
1197 (setcdr (car group) pall))))))
1199 (when (setq window (get-buffer-window (current-buffer)))
1200 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1201 (size (gnugo-get :SZ))
1202 (under10p (< size 10))
1203 (h (- (truncate (- (window-height window)
1204 (* size (gnugo-get :hmul))
1208 (edges (window-edges window))
1209 (right-w-edge (nth 2 edges))
1210 (avail-width (- right-w-edge (nth 0 edges)))
1211 (wmul (gnugo-get :wmul))
1212 (imagesp (symbol-plist (gnugo-f 'ispc)))
1213 (w (/ (- avail-width
1218 2 ; between board and grid
1223 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1224 `(display ,(make-string h 10))
1225 '(invisible :nogrid)))
1230 (cond (imagesp (+ (* 0.5 wmul)
1236 (gspc . ,(when imagesp
1240 ;; DWR: image width alone => OBOE!
1242 ;; NB: ‘(* wmul cw)’ is the same
1243 ;; as ‘(car (image-size ... t))’.
1244 (let ((cw (frame-char-width)))
1245 (/ (+ 1.0 (* wmul cw))
1248 (lpad . ,(let ((d `(display (space :align-to ,w))))
1249 ;; We distinguish between these cases to
1250 ;; workaround a display bug whereby the
1251 ;; `before-string' is omitted entirely (not
1252 ;; rendered) when interacting w/ the text
1253 ;; mode last-move left-paren for moves in
1257 ,(apply 'propertize " " d))
1260 (space :align-to ,(1- avail-width))))))
1261 (setplist (gnugo-f (car pair)) (cdr pair)))))
1263 (let ((cur (gnugo-get :mode-line)))
1264 (unless (equal cur gnugo-mode-line)
1265 (setq cur gnugo-mode-line)
1266 (gnugo-put :mode-line cur)
1267 (gnugo-put :mode-line-form
1268 (cond ((stringp cur)
1269 (setq cur (copy-sequence cur))
1271 (while (setq cut (string-match "~[bwpmtu]" cur))
1273 (setq c (aref cur (incf cut)))
1276 `(,(intern (format "squig-%c" c))
1278 (?b '(or (gnugo-get :black-captures) 0))
1279 (?w '(or (gnugo-get :white-captures) 0))
1280 (?p '(gnugo-other (gnugo-get :last-mover)))
1281 (?t '(let ((ws (gnugo-get :waiting-start)))
1283 (cadr (time-since ws))
1285 (?u '(or (gnugo-get :last-waiting) "-"))
1286 (?m '(gnugo-move-history 'count))))
1288 `(let ,(delete-dups (copy-sequence acc))
1289 (format ,cur ,@(reverse (mapcar 'car acc))))))
1291 (let ((form (gnugo-get :mode-line-form)))
1292 (setq mode-line-process
1294 ;; this dynamicism is nice but excessive in its wantonness
1295 ;;- `(" [" (:eval ,form) "]")
1296 ;; this dynamicism is ok because the user triggers it
1297 (list (format " [%s]" (eval form))))))
1298 (force-mode-line-update))
1300 (when (setq last (gnugo-get :last-user-bpos))
1301 (gnugo-goto-pos last))))
1303 ;;;---------------------------------------------------------------------------
1304 ;;; Game play actions
1306 (defun gnugo-get-move-insertion-filter (proc string)
1307 (with-current-buffer (process-buffer proc)
1308 (let* ((so-far (gnugo-get :get-move-string))
1309 (full (gnugo-put :get-move-string (concat so-far string))))
1310 (when (string-match "^= \\(.+\\)\n\n" full)
1311 (let ((pos-or-pass (match-string 1 full)))
1312 (gnugo-put :get-move-string nil)
1313 (gnugo-put :waitingp nil)
1314 (gnugo-push-move nil pos-or-pass)
1315 (let ((buf (current-buffer)))
1316 (let (gnugo-inhibit-refresh)
1317 (run-hooks 'gnugo-post-move-hook)
1318 (unless gnugo-inhibit-refresh
1319 (with-current-buffer buf
1320 (gnugo-refresh))))))))))
1322 (defun gnugo-get-move (color)
1323 (gnugo-put :waitingp t)
1324 (gnugo--begin-exchange
1325 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1326 (concat "genmove " color))
1327 (accept-process-output))
1329 (defun gnugo-cleanup ()
1330 (when (gnugo-board-buffer-p)
1331 (unless (zerop (buffer-size))
1332 (message "Thank you for playing GNU Go."))
1334 (setplist sym nil) ; "...is next to fordliness." --Huxley
1335 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1336 ;; No worries, things will be Much Better w/ structs, RSN...
1338 (append (gnugo-get :all-yy)
1347 (setq gnugo-state nil)))
1349 (defun gnugo-position ()
1350 (or (get-text-property (point) 'gnugo-position)
1351 (user-error "Not a proper position point")))
1353 (defun gnugo-move ()
1354 "Make a move on the GNUGO Board buffer.
1355 The position is computed from current point.
1356 Signal error if done out-of-turn or if game-over.
1357 To start a game try M-x gnugo."
1360 (let* ((buf (current-buffer))
1361 (pos (gnugo-position))
1362 (move (format "play %s %s" (gnugo-get :user-color) pos))
1363 (accept (gnugo--q move)))
1364 (unless (= ?= (aref accept 0))
1365 (user-error "%s" accept))
1366 (gnugo-push-move t pos) ; value always nil for non-pass move
1367 (let (gnugo-inhibit-refresh)
1368 (run-hooks 'gnugo-post-move-hook)
1369 (unless gnugo-inhibit-refresh
1370 (with-current-buffer buf
1372 (with-current-buffer buf
1373 (gnugo-get-move (gnugo-get :gnugo-color)))))
1375 (defun gnugo-mouse-move (e)
1376 "Do `gnugo-move' at mouse location."
1379 (when (looking-at "[.+]")
1382 (defun gnugo-pass ()
1383 "Make a pass on the GNUGO Board buffer.
1384 Signal error if done out-of-turn or if game-over.
1385 To start a game try M-x gnugo."
1388 (let ((accept (gnugo--q "play %s PASS" (gnugo-get :user-color))))
1389 (unless (= ?= (aref accept 0))
1390 (user-error "%s" accept)))
1391 (let ((donep (gnugo-push-move t "PASS"))
1392 (buf (current-buffer)))
1393 (let (gnugo-inhibit-refresh)
1394 (run-hooks 'gnugo-post-move-hook)
1395 (unless gnugo-inhibit-refresh
1396 (with-current-buffer buf
1399 (with-current-buffer buf
1400 (gnugo-get-move (gnugo-get :gnugo-color))))))
1402 (defun gnugo-mouse-pass (e)
1403 "Do `gnugo-pass' at mouse location."
1408 (defun gnugo-resign ()
1411 (if (not (y-or-n-p "Resign? "))
1412 (message "(not resigning)")
1413 (gnugo-push-move t "resign")
1416 (defun gnugo-animate-group (w/d)
1417 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1418 (let* ((pos (gnugo-position))
1419 (orig-b-m-p (buffer-modified-p))
1421 (unless (memq (following-char) '(?X ?O))
1422 (user-error "No stone at %s" pos))
1423 (setq blurb (message "Computing %s stones ..." w/d)
1424 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1425 (message "%s %s in group." blurb (length stones))
1426 (setplist (gnugo-f 'anim) nil)
1427 (let* ((spec (if (gnugo-get :display-using-images)
1428 (loop with yin = (get-text-property (point) 'gnugo-yin)
1429 with yang = (gnugo-yang (following-char))
1430 with up = (get (gnugo-yy yin yang t) 'display)
1431 with dn = (get (gnugo-yy yin yang) 'display)
1432 for n below (length gnugo-animation-string)
1433 collect (if (zerop (logand 1 n))
1435 (split-string gnugo-animation-string "" t)))
1437 (ovs (save-excursion
1438 (mapcar (lambda (pos)
1439 (gnugo-goto-pos pos)
1441 (ov (make-overlay p (1+ p))))
1442 (overlay-put ov 'category (gnugo-f 'anim))
1443 (overlay-put ov 'priority most-positive-fixnum)
1446 (setplist (gnugo-f 'anim) (cons 'display cell))
1447 (while (and (cdr spec) ; let last linger lest levity lost
1448 (sit-for 0.08675309)) ; jenny jenny i got your number...
1449 (setcar cell (setq spec (cdr spec)))
1450 ;; Force redisplay of overlays.
1451 (set-buffer-modified-p orig-b-m-p))
1453 (mapc 'delete-overlay ovs)
1456 (defun gnugo-display-group-data (command buffer-name)
1457 (message "Computing %s ..." command)
1458 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1459 (switch-to-buffer buffer-name)
1462 (message "Computing %s ... done." command))
1464 (defun gnugo-worm-stones ()
1465 "In the GNUGO Board buffer, animate \"worm\" at current position.
1466 Signal error if done out-of-turn or if game-over.
1467 See variable `gnugo-animation-string' for customization."
1470 (gnugo-animate-group 'worm))
1472 (defun gnugo-worm-data ()
1473 "Display in another buffer data from \"worm\" at current position.
1474 Signal error if done out-of-turn or if game-over."
1477 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1479 (defun gnugo-dragon-stones ()
1480 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1481 Signal error if done out-of-turn or if game-over.
1482 See variable `gnugo-animation-string' for customization."
1485 (gnugo-animate-group 'dragon))
1487 (defun gnugo-dragon-data ()
1488 "Display in another buffer data from \"dragon\" at current position.
1489 Signal error if done out-of-turn or if game-over."
1492 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1494 (defun gnugo-toggle-dead-group ()
1495 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1496 The group is selected from current position (point). Signal error if
1497 not in game-over or if there is no group at that position.
1499 In the context of GNU Go, a group is called a \"dragon\" and may be
1500 composed of more than one \"worm\" (set of directly-connected stones).
1501 It is unclear to the gnugo.el author whether or not GNU Go supports
1502 - considering worms as groups in their own right; and
1503 - toggling group aliveness via GTP.
1504 Due to these uncertainties, this command is only half complete; the
1505 changes you may see in Emacs are not propagated to the gnugo subprocess.
1506 Thus, GTP commands like `final_score' may give unexpected results.
1508 If you are able to expose via GTP `change_dragon_status' in utils.c,
1509 you may consider modifying the `gnugo-toggle-dead-group' source code
1510 to enable full functionality."
1512 (let ((game-over (or (gnugo-get :game-over)
1513 (user-error "Sorry, game still in play")))
1514 (group (or (get-text-property (point) 'group)
1515 (user-error "No stone at that position")))
1516 (now (current-time)))
1517 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1519 (let ((live (assq 'live game-over))
1520 (dead (assq 'dead game-over))
1522 (if (memq group live)
1523 (setq bef live now dead)
1524 (setq bef dead now live))
1525 (setcdr bef (delq group (cdr bef)))
1526 (setcdr now (cons group (cdr now)))
1527 ;; disabled permanently -- too wrong
1531 (let ((color (caar group)))
1532 (dolist (stone (cdr group))
1533 (gnugo-query "play %s %s" color stone)))))
1536 ;; drastic (and wrong -- clobbers capture info, etc)
1537 (gnugo-query "clear_board")
1538 (mapc #'populate (cdr live)))))
1539 ;; here is the desired interface (to be enabled Some Day)
1541 (gnugo-query "change_dragon_status %s %s"
1542 (cadr group) (if (eq now live)
1548 (defun gnugo-estimate-score ()
1549 "Display estimated score of a game of GNU Go.
1550 Output includes number of stones on the board and number of stones
1551 captured by each player, and the estimate of who has the advantage (and
1552 by how many stones)."
1554 (message "Est.score ...")
1555 (let ((black (length (gnugo-lsquery "list_stones black")))
1556 (white (length (gnugo-lsquery "list_stones white")))
1557 (black-captures (gnugo-query "captures black"))
1558 (white-captures (gnugo-query "captures white"))
1559 (est (gnugo-query "estimate_score")))
1560 ;; might as well update this
1561 (gnugo-put :black-captures black-captures)
1562 (gnugo-put :white-captures white-captures)
1563 (message "Est.score ... B %s %s | W %s %s | %s"
1564 black black-captures white white-captures est)))
1566 (defun gnugo-write-sgf-file (filename)
1567 "Save the game history to FILENAME (even if unfinished).
1568 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1569 (interactive "FWrite game as SGF file: ")
1570 (when (and (file-exists-p filename)
1571 (not (y-or-n-p "File exists. Continue? ")))
1572 (user-error "Not writing %s" filename))
1573 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1574 (set-buffer-modified-p nil))
1576 (defun gnugo--who-is-who (wait play samep)
1577 (message "GNU Go %splays as %s, you as %s (%s)"
1578 (if samep "" "now ")
1581 "NOTE: this is a switch!")))
1583 (defsubst gnugo--nodep (x)
1584 (keywordp (caar x)))
1586 (defsubst gnugo--SZ! (size)
1587 (gnugo-put :SZ size))
1589 (defun gnugo-read-sgf-file (filename)
1590 "Load the first game tree from FILENAME, a file in SGF format."
1591 (interactive "fSGF file to load: ")
1592 (when (file-directory-p filename)
1593 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1594 (let (ans play wait samep coll tree)
1595 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1596 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1597 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1598 (expand-file-name filename)))
1600 (user-error "%s" ans))
1601 (setq play (substring ans 2)
1602 wait (gnugo-other play)
1603 samep (string= (gnugo-get :user-color) play))
1604 (gnugo-put :last-mover wait)
1606 (gnugo-put :gnugo-color wait)
1607 (gnugo-put :user-color play))
1608 (setq coll (gnugo/sgf-read-file filename)
1609 tree (nth (let ((n (length coll)))
1613 ;; (let* ((q (format "Which game? (1-%d)" n))
1614 ;; (choice (1- (read-number q 1))))
1615 ;; (if (and (< -1 choice) (< choice n))
1617 ;; (message "(Selecting the first game)")
1619 ;; but this is what we use (for now) to accomodate
1620 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1622 (message "(Selecting the first game)"))
1625 (gnugo-put :sgf-collection coll)
1626 (gnugo-put :sgf-gametree tree)
1627 ;; This is deliberately undocumented for now.
1628 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1629 (let* ((mem (aref tree 0))
1632 (vector mem 0 (loop for node in mem
1633 count (gnugo--move-prop node))))
1634 (gnugo-put :game-over
1636 (or (gnugo--root-prop :RE tree)
1637 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1639 (when (and game-over
1640 ;; (maybe) todo: user var to inhibit (can be slow)
1642 (gnugo-close-game nil game-over)))
1644 (set-buffer-modified-p nil)
1645 (gnugo--who-is-who wait play samep)))
1647 (defun gnugo-magic-undo (spec &optional noalt keep)
1648 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1649 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1650 check that the position is occupied by a stone of the user's color,
1651 and if so, remove moves from the history until that position is clear.
1652 If SPEC is a positive number, remove exactly that many moves from the
1653 history, signaling an error if the history is exhausted before finishing.
1654 If SPEC Is 0 (zero), remove either one or two moves,
1655 so that you are to play next.
1656 If SPEC is not recognized, signal \"bad spec\" error.
1658 Refresh the board for each move undone. If (in the case where SPEC is
1659 a number) after finishing, the color to play is not the user's color,
1660 schedule a move by GNU Go.
1662 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1663 turn to play. Optional second arg NOALT non-nil inhibits this.
1665 Optional third arg KEEP non-nil means do not prune the undone moves
1666 from the gametree, such that they become a sub-gametree (variation)
1670 (user-color (gnugo-get :user-color))
1671 (monkey (gnugo-get :monkey))
1672 (tree (gnugo-get :sgf-gametree))
1673 (remorseful (not (gnugo--no-regrets monkey tree)))
1675 (cond ((numberp spec)
1676 (setq n (if (zerop spec)
1677 (if (string= user-color (gnugo-get :last-mover))
1681 done (lambda () (zerop n))))
1682 ((string-match "^[a-z]" spec)
1683 (let ((pos (upcase spec)))
1684 (setq done `(lambda ()
1685 (gnugo-goto-pos ,pos)
1686 (memq (following-char) '(?. ?+))))
1687 (when (funcall done)
1688 (user-error "%s already clear" pos))
1689 (when (= (save-excursion
1690 (gnugo-goto-pos pos)
1692 (if (gnugo--blackp user-color)
1695 (user-error "%s not occupied by %s" pos user-color))))
1696 (t (user-error "Bad spec: %S" spec)))
1697 (when (gnugo-get :game-over)
1698 (gnugo--unclose-game))
1699 (while (not (funcall done))
1700 (setq ans (gnugo--q "undo"))
1701 (unless (= ?= (aref ans 0))
1702 (user-error "%s" ans))
1703 (decf (aref monkey 2))
1704 (pop (aref monkey 0))
1705 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1706 (gnugo-merge-showboard-results) ; all
1707 (gnugo-refresh) ; this
1709 (redisplay)) ; eye candy
1710 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1712 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1713 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1715 (gnugo-get :center-position)))
1717 (unless (or keep remorseful)
1718 (aset tree (aref monkey 1) (aref monkey 0)))
1719 (when (and ulastp (not noalt))
1720 (gnugo-get-move (gnugo-get :gnugo-color))))))
1722 (defun gnugo-undo-one-move (&optional me-next)
1723 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1724 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1725 Prefix arg ME-NEXT means to arrange for you to play
1726 the color of the next move (and GNU Go the opposite).
1727 This is useful after loading an SGF file whose last
1728 move was done by the color you prefer to play:
1729 \\[gnugo-read-sgf-file] FILENAME RET
1730 C-u \\[gnugo-undo-one-move]
1732 See also `gnugo-undo-two-moves'."
1735 (gnugo-magic-undo 1 t)
1737 (let* ((wait (gnugo-get :last-mover))
1738 (play (gnugo-other wait)))
1739 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
1740 (gnugo-put :user-color play)
1741 (gnugo-put :gnugo-color wait))))
1743 (defun gnugo-undo-two-moves ()
1744 "Undo a pair of moves (GNU Go's and yours).
1745 However, if you are the last mover, undo only one move.
1746 Regardless, after undoing, it is your turn to play again."
1749 (gnugo-magic-undo 0))
1751 (defun gnugo-oops (&optional position)
1752 "Like `gnugo-undo-two-moves', but keep the undone moves.
1753 The kept moves become a sub-gametree (variation) when play resumes.
1754 Prefix arg means, instead, undo repeatedly up to and including
1755 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1758 (gnugo-magic-undo (if position
1763 (defun gnugo-display-final-score ()
1764 "Display final score and other info in another buffer (when game over).
1765 If the game is still ongoing, Emacs asks if you wish to stop play (by
1766 making sure two \"pass\" moves are played consecutively, if necessary).
1767 Also, add the `:RE' SGF property to the root node of the game tree."
1769 (let ((game-over (gnugo-get :game-over)))
1770 (unless (or game-over
1771 (and (not (gnugo-get :waitingp))
1772 (y-or-n-p "Game still in play. Stop play now? ")))
1773 (user-error "Sorry, game still in play"))
1777 (message "Playing PASS for %s ..."
1778 (gnugo-get (if userp :user-color :gnugo-color)))
1780 (gnugo-push-move userp "PASS")))
1785 (let ((b= " Black = ")
1787 (res (when (string= "resign" (gnugo-move-history 'car))
1788 (gnugo-get :last-mover)))
1792 (format "%s wins.\n"
1793 (substring (if (= ?b (aref res 0)) w= b=)
1795 "The game is over.\n"
1796 (format "Resignation by %s.\n" res))
1797 result (concat (upcase (substring (gnugo-other res) 0 1))
1799 (message "Computing final score ...")
1800 (let* ((g-over (gnugo-get :game-over))
1801 (live (cdr (assq 'live g-over)))
1802 (dead (cdr (assq 'dead g-over)))
1803 (seed (gnugo-get :scoring-seed))
1804 (terr-q (format "final_status_list %%s_territory %d" seed))
1807 (b-terr (length (gnugo-lsquery terr-q "black")))
1808 (w-terr (length (gnugo-lsquery terr-q "white")))
1809 (b-capt (string-to-number (gnugo-get :black-captures)))
1810 (w-capt (string-to-number (gnugo-get :white-captures)))
1811 (komi (gnugo--root-prop :KM)))
1812 (setq blurb (list "The game is over. Final score:\n")
1813 result (gnugo-query "final_score %d" seed))
1814 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1815 (dolist (group live)
1816 (incf (if (gnugo--blackp (caar group))
1819 (length (cdr group))))
1820 (dolist (group dead)
1821 (incf (if (gnugo--blackp (caar group))
1824 (length (cdr group))))
1825 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1826 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1827 w-terr terr komi 'komi (+ w-terr komi))
1830 (dolist (group dead)
1831 (incf (if (gnugo--blackp (caar group))
1834 (* 2 (length (cdr group)))))
1835 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1840 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1844 (+ w-terr w-capt komi))
1846 (push (if (string= "0" result)
1847 "The game is a draw.\n"
1848 (format "%s wins by %s.\n"
1849 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1850 (substring result 2)))
1852 (message "Computing final score ... done")))
1854 (let ((beg (gnugo-get :game-start-time))
1855 (end (gnugo-get :game-end-time)))
1859 ((yep (pretty moment)
1860 (push (format-time-string
1861 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
1864 (yep "Game start" beg)
1866 (setq blurb (apply 'concat (nreverse blurb)))
1867 (gnugo--set-root-prop :RE result)
1868 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1872 (defun gnugo-quit ()
1873 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1874 If the game is not over, ask for confirmation first."
1876 (if (or (gnugo-get :game-over)
1877 (y-or-n-p "Quit? "))
1879 (message "(not quitting)")))
1881 (defun gnugo-leave-me-alone ()
1882 "Kill the current buffer unconditionally."
1886 (defun gnugo-fancy-undo (count)
1887 "Rewind the game tree in various ways.
1888 Prefix arg COUNT means to undo that many moves.
1889 Otherwise, undo repeatedly up to and including the move
1890 which placed the stone at point."
1893 ;; TODO: Move this into `gnugo-magic-undo' proper.
1894 (cond ((numberp count) count)
1895 ((consp count) (car count))
1896 (t (gnugo-position)))))
1898 (defun gnugo-toggle-image-display-command () ; ugh
1899 "Toggle use of images to display the board, then refresh."
1901 (gnugo-toggle-image-display)
1902 (save-excursion (gnugo-refresh)))
1904 (defun gnugo-describe-position ()
1905 "Display the board position under cursor in the echo area."
1907 (message "%s" (gnugo-position)))
1909 (defun gnugo-switch-to-another ()
1910 "Switch to another GNU Go game buffer (if any)."
1912 (loop for buf in (cdr (buffer-list))
1913 if (gnugo-board-buffer-p buf)
1916 (switch-to-buffer buf))
1917 finally do (message "(only one)")))
1919 ;;;---------------------------------------------------------------------------
1920 ;;; Command properties and gnugo-command
1922 ;; GTP commands entered by the user are never issued directly to GNU Go;
1923 ;; instead, their behavior and output are controlled by the property
1924 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1925 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1927 ;; :full -- completely interpret the command string; the value is a
1928 ;; func that takes the list of words derived from splitting the
1929 ;; command string (minus the command) and handles everything.
1931 ;; :output -- either a keyword specifying the preferred output method:
1932 ;; :message -- show output in minibuffer
1933 ;; :discard -- sometimes you just don't care;
1934 ;; or a function that takes one arg, the output string, and
1935 ;; handles it completely. default is to switch to buffer
1936 ;; "*gnugo command output*" if the output has a newline,
1937 ;; otherwise use `message'.
1939 ;; :post-thunk -- run after output processing (at the very end).
1941 (defun gnugo-command (command)
1942 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1943 Output and Emacs behavior depend on which command is given (some
1944 commands are handled completely by Emacs w/o using the subprocess;
1945 some commands have their output displayed in specially prepared
1946 buffers or in the echo area; some commands are instrumented to do
1947 gnugo.el-specific housekeeping).
1949 For example, for the command \"help\", Emacs visits the
1950 GTP command reference info page.
1952 NOTE: At this time, GTP command handling specification is still
1953 incomplete. Thus, some commands WILL confuse gnugo.el."
1954 (interactive "sCommand: ")
1955 (if (string= "" command)
1956 (message "(no command given)")
1957 (let* ((split (split-string command))
1958 (cmd (intern (car split)))
1959 (spec (get cmd :gnugo-gtp-command-spec))
1960 (full (plist-get spec :full)))
1962 (funcall full (cdr split))
1963 (message "Doing %s ..." command)
1964 (let* ((ans (gnugo--q command))
1965 (where (plist-get spec :output)))
1966 (if (string-match "unknown.command" ans)
1968 (cond ((functionp where) (funcall where ans))
1969 ((eq :discard where) (message ""))
1970 ((or (eq :message where)
1971 (not (string-match "\n" ans)))
1973 (t (switch-to-buffer "*gnugo command output*")
1976 (message "Doing %s ... done." command)))
1977 (let ((thunk (plist-get spec :post-thunk)))
1978 (when thunk (funcall thunk)))))))))
1980 ;;;---------------------------------------------------------------------------
1981 ;;; Major mode for interacting with a GNUGO subprocess
1983 (put 'gnugo-board-mode 'mode-class 'special)
1984 (defun gnugo-board-mode ()
1985 "Major mode for playing GNU Go.
1986 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1987 In this mode, keys do not self insert.
1989 \\{gnugo-board-mode-map}"
1990 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1991 (buffer-disable-undo) ; todo: undo undo undoing
1992 (kill-all-local-variables)
1993 (use-local-map gnugo-board-mode-map)
1994 (set (make-local-variable 'font-lock-defaults)
1995 '(gnugo-font-lock-keywords t))
1996 (setq major-mode 'gnugo-board-mode
1997 mode-name "GNUGO Board"
1999 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2000 (set (make-local-variable 'gnugo-state)
2001 (make-hash-table :size (1- 42) :test 'eq))
2002 (add-to-invisibility-spec :nogrid)
2003 (mapc (lambda (prop)
2004 (gnugo-put prop nil)) ; todo: separate display/game aspects;
2005 '(:game-over ; move latter to func `gnugo'
2012 :display-using-images
2016 (let ((name (if (string-match "[ ]" gnugo-program)
2017 (let ((p (substring gnugo-program 0 (match-beginning 0)))
2018 (o (substring gnugo-program (match-end 0)))
2019 (h (or (car gnugo-option-history) "")))
2020 (when (string-match "--mode" o)
2021 (user-error "Found \"--mode\" in `gnugo-program'"))
2022 (when (and o (cl-plusp (length o))
2023 h (cl-plusp (length o))
2024 (or (< (length h) (length o))
2025 (not (string= (substring h 0 (length o))
2027 (push (concat o " " h) gnugo-option-history))
2030 (args (read-string "GNU Go options: "
2031 (car gnugo-option-history)
2032 'gnugo-option-history))
2034 board-size user-color handicap komi minus-l infile)
2035 (loop for (var default opt &optional rx)
2036 in '((board-size 19 "--boardsize")
2037 (user-color "black" "--color" "\\(black\\|white\\)")
2038 (handicap 0 "--handicap")
2040 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2041 (infile nil "--infile" "[ ]*[^ ]+"))
2043 (or (when (string-match opt args)
2044 (let ((start (match-end 0)) s)
2045 (string-match (or rx "[0-9.]+") args start)
2046 (setq s (match-string 0 args))
2047 (if rx s (string-to-number s))))
2049 (gnugo-put :user-color user-color)
2050 (let ((proc-args (split-string args)))
2051 (gnugo-put :proc-args proc-args)
2052 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2053 (current-buffer) name
2054 "--mode" "gtp" "--quiet"
2056 (set-process-sentinel proc 'gnugo-sentinel)
2057 ;; Emacs is too protective sometimes, blech.
2058 (set-process-query-on-exit-flag proc nil)
2059 (when (or minus-l infile)
2061 in '((board-size "query_boardsize")
2063 (handicap "get_handicap"))
2064 do (set prop (string-to-number (gnugo-query q)))))
2065 (gnugo-put :diamond (substring (process-name proc) 5))
2066 (gnugo-put :gnugo-color (gnugo-other user-color))
2067 (gnugo-put :highlight-last-move-spec
2068 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2069 (gnugo-put :lparen-ov (make-overlay 1 1))
2070 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
2071 (overlay-put ov 'display ")")
2073 (let ((tree (vector (list (list '(:FF . 4) '(:GM . 1))))))
2074 (gnugo-put :sgf-gametree tree)
2075 (gnugo-put :sgf-collection (list tree))
2076 (gnugo-put :monkey (vector (aref tree 0) 0 0)))
2077 (gnugo--SZ! board-size)
2078 (loop with gb = (gnugo--blackp (gnugo-other user-color))
2079 for (property value &optional mogrifyp) in
2081 (:DT ,(format-time-string "%Y-%m-%d"))
2082 (:RU ,(if (string-match "--chinese-rules" args)
2085 (:AP ("gnugo.el" . ,gnugo-version))
2087 (,(if gb :PW :PB) ,(user-full-name))
2088 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
2089 ,@(when (not (zerop handicap))
2091 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
2093 do (gnugo-note property value mogrifyp)))
2094 (gnugo-put :waiting-start (current-time))
2097 (run-hooks 'gnugo-board-mode-hook)
2100 ;;;---------------------------------------------------------------------------
2104 (defun gnugo (&optional new-game)
2105 "Run gnugo in a buffer, or resume a game in progress.
2106 Prefix arg means skip the game-in-progress check and start a new
2108 \\<gnugo-board-mode-map>
2109 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2111 You are queried for additional command-line options (Emacs supplies
2112 \"--mode gtp --quiet\" automatically). Here is a list of options
2113 that gnugo.el understands and handles specially:
2115 --boardsize num Set the board size to use (5--19)
2116 --color <color> Choose your color ('black' or 'white')
2117 --handicap <num> Set the number of handicap stones (0--9)
2119 If there is already a game in progress you may resume it instead of
2120 starting a new one. See `gnugo-board-mode' documentation for more info."
2122 (let* ((all (let (acc)
2123 (dolist (buf (buffer-list))
2124 (when (gnugo-board-buffer-p buf)
2125 (push (cons (buffer-name buf) buf) acc)))
2128 (if (and (not new-game)
2130 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2131 (if (= 1 n) "" "s"))))
2136 (let ((sel (completing-read "Which one? " all nil t)))
2137 (if (string= "" sel)
2139 (assoc sel all))))))
2140 ;; set up a new board
2142 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2143 (gnugo-goto-pos (format "A%d" half))
2144 (forward-char (* 2 (1- half)))
2145 (gnugo-put :last-user-bpos
2146 (gnugo-put :center-position
2147 (get-text-property (point) 'gnugo-position))))
2149 (gnugo-put :game-start-time (current-time))
2150 (let ((g (gnugo-get :gnugo-color))
2151 (n (or (gnugo--root-prop :HA) 0))
2152 (u (gnugo-get :user-color)))
2153 (gnugo-put :last-mover g)
2154 (when (or (and (gnugo--blackp u) (< 1 n))
2155 (and (gnugo--blackp g) (< n 2)))
2156 (gnugo-put :last-mover u)
2158 (gnugo-get-move g))))))
2160 ;;;---------------------------------------------------------------------------
2161 ;;; Load-time actions
2163 (unless gnugo-board-mode-map
2164 (setq gnugo-board-mode-map (make-sparse-keymap))
2165 (suppress-keymap gnugo-board-mode-map)
2166 (mapc (lambda (pair)
2167 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2168 '(("?" . describe-mode)
2169 ("\C-m" . gnugo-move)
2172 ("R" . gnugo-resign)
2174 ("Q" . gnugo-leave-me-alone)
2175 ("U" . gnugo-fancy-undo)
2176 ("\M-u" . gnugo-undo-one-move)
2177 ("u" . gnugo-undo-two-moves)
2178 ("\C-?" . gnugo-undo-two-moves)
2180 ("\C-l" . gnugo-refresh)
2181 ("\M-_" . gnugo-boss-is-near)
2182 ("_" . gnugo-boss-is-near)
2183 ("h" . gnugo-move-history)
2184 ("L" . gnugo-frolic-in-the-leaves)
2185 ("i" . gnugo-toggle-image-display-command)
2186 ("w" . gnugo-worm-stones)
2187 ("W" . gnugo-worm-data)
2188 ("d" . gnugo-dragon-stones)
2189 ("D" . gnugo-dragon-data)
2190 ("t" . gnugo-toggle-dead-group)
2191 ("g" . gnugo-toggle-grid)
2192 ("!" . gnugo-estimate-score)
2193 (":" . gnugo-command)
2194 (";" . gnugo-command)
2195 ("=" . gnugo-describe-position)
2196 ("s" . gnugo-write-sgf-file)
2197 ("\C-x\C-s" . gnugo-write-sgf-file)
2198 ("\C-x\C-w" . gnugo-write-sgf-file)
2199 ("l" . gnugo-read-sgf-file)
2200 ("F" . gnugo-display-final-score)
2201 ("A" . gnugo-switch-to-another)
2203 ([(down-mouse-1)] . gnugo-mouse-move)
2204 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2205 ([(down-mouse-3)] . gnugo-mouse-pass)
2206 ;; delving into the curiosities
2207 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2209 (unless (get 'help :gnugo-gtp-command-spec)
2211 ((sget (x) (get x :gnugo-gtp-command-spec))
2212 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2213 (plist-put (sget cmd) prop val)))
2214 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2217 (jam cmd (car ls) (cadr ls))
2218 (setq ls (cddr ls)))))))
2219 (cl-macrolet ((deffull (who &body body)
2220 (declare (indent 1))
2221 `(defgtp ',who :full (lambda (sel)
2225 (info "(gnugo)GTP command reference")
2226 (when sel (setq sel (intern (car sel))))
2227 (let (buffer-read-only pad cur spec output found)
2229 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2230 (goto-char (point-min))
2232 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2235 (setq pad (make-string (- (match-beginning 1)
2236 (match-beginning 0))
2240 (get (setq cur (intern (match-string 1)))
2241 :gnugo-gtp-command-spec))
2243 (note "handles this command completely"))
2244 (when (setq output (plist-get spec :output))
2245 (if (functionp output)
2246 (note "handles the output specially")
2248 (:discard (note "discards the output"))
2249 (:message (note "displays the output in the echo area")))))
2251 (setq found (match-beginning 0))))))
2252 (cond (found (goto-char found))
2254 (t (message "(no such command: %s)" sel)))))
2256 (deffull final_score
2257 (gnugo-display-final-score))
2263 :post-thunk (lambda ()
2264 (gnugo--unclose-game)
2265 (gnugo-put :last-mover nil)
2267 (gnugo--SZ! (string-to-number
2269 "query_boardsize")))
2273 (gnugo-read-sgf-file (car sel)))
2275 (deffull (undo gg-undo)
2279 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2280 (t (car sel)))))))))
2285 ;;;---------------------------------------------------------------------------
2286 ;;; The remainder of this file defines a simplified SGF-handling library.
2287 ;;; When/if it should start to attain generality, it should be split off into
2288 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2289 ;;; "gnugo/" prefix.
2291 (defconst gnugo/sgf-*r4-properties*
2292 '((AB "Add Black" setup list stone)
2293 (AE "Add Empty" game list point)
2294 (AN "Annotation" game simpletext)
2295 (AP "Application" root (simpletext . simpletext))
2296 (AR "Arrow" - list (point . point))
2297 (AS "Who adds stones" - simpletext) ; (LOA)
2298 (AW "Add White" setup list stone)
2299 (B "Black" move move)
2300 (BL "Black time left" move real)
2301 (BM "Bad move" move double)
2302 (BR "Black rank" game simpletext)
2303 (BT "Black team" game simpletext)
2304 (C "Comment" - text)
2305 (CA "Charset" root simpletext)
2306 (CP "Copyright" game simpletext)
2307 (CR "Circle" - list point)
2308 (DD "Dim points" - elist point) ; (inherit)
2309 (DM "Even position" - double)
2310 (DO "Doubtful" move none)
2311 (DT "Date" game simpletext)
2312 (EV "Event" game simpletext)
2313 (FF "Fileformat" root [number (1 . 4)])
2314 (FG "Figure" - (or none (number . simpletext)))
2315 (GB "Good for Black" - double)
2316 (GC "Game comment" game text)
2317 (GM "Game" root [number (1 . 20)])
2318 (GN "Game name" game simpletext)
2319 (GW "Good for White" - double)
2320 (HA "Handicap" game number) ; (Go)
2321 (HO "Hotspot" - double)
2322 (IP "Initial pos." game simpletext) ; (LOA)
2323 (IT "Interesting" move none)
2324 (IY "Invert Y-axis" game simpletext) ; (LOA)
2325 (KM "Komi" game real) ; (Go)
2327 (LB "Label" - list (point . simpletext))
2328 (LN "Line" - list (point . point))
2329 (MA "Mark" - list point)
2330 (MN "set move number" move number)
2331 (N "Nodename" - simpletext)
2332 (OB "OtStones Black" move number)
2333 (ON "Opening" game text)
2334 (OT "Overtime" game simpletext)
2335 (OW "OtStones White" move number)
2336 (PB "Player Black" game simpletext)
2337 (PC "Place" game simpletext)
2338 (PL "Player to play" setup color)
2339 (PM "Print move mode" - number) ; (inherit)
2340 (PW "Player White" game simpletext)
2341 (RE "Result" game simpletext)
2342 (RO "Round" game simpletext)
2343 (RU "Rules" game simpletext)
2344 (SE "Markup" - point) ; (LOA)
2345 (SL "Selected" - list point)
2346 (SO "Source" game simpletext)
2347 (SQ "Square" - list point)
2348 (ST "Style" root [number (0 . 3)])
2349 (SU "Setup type" game simpletext) ; (LOA)
2350 (SZ "Size" root (or number (number . number)))
2351 (TB "Territory Black" - elist point) ; (Go)
2352 (TE "Tesuji" move double)
2353 (TM "Timelimit" game real)
2354 (TR "Triangle" - list point)
2355 (TW "Territory White" - elist point) ; (Go)
2356 (UC "Unclear pos" - double)
2357 (US "User" game simpletext)
2359 (VW "View" - elist point) ; (inherit)
2360 (W "White" move move)
2361 (WL "White time left" move real)
2362 (WR "White rank" game simpletext)
2363 (WT "White team" game simpletext)
2364 (LT "Lose on time" setup simpletext))
2365 ;; r4-specific notes
2366 ;; - changed: DT FG LB RE RU SZ
2367 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2368 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2370 (defun gnugo/sgf-root-node (tree)
2371 (car (last (aref tree
2372 ;; Any bidx is fine, but we choose the last one since
2373 ;; usually the main line (bidx 0) is the longest.
2374 ;; Ugh, heuristics for the sake of performance. :-/
2375 (1- (length tree))))))
2377 (defun gnugo/sgf-read-file (filename)
2378 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2379 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2380 (put 'gnugo/sgf-*r4-properties* :keywords
2381 (mapcar (lambda (full)
2383 (intern (format ":%s" (car full)))))
2384 gnugo/sgf-*r4-properties*))))
2385 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2386 (put 'gnugo/sgf-*r4-properties* :specs
2387 (mapcar (lambda (full)
2388 (cons (car full) (cdddr full)))
2389 gnugo/sgf-*r4-properties*))))
2392 ((sw () (skip-chars-forward " \t\n"))
2393 (x (end) (let ((beg (point))
2395 (:end (lambda (char) (= ?\] char)))
2396 (:mid (lambda (char) (= ?\: char)))
2397 (t (lambda (char) (or (= ?\: char)
2400 (while (not (funcall endp (setq c (following-char))))
2406 ((looking-at "\\s-+")
2407 (delete-region (point) (match-end 0))
2409 (t (forward-char 1))))
2410 (buffer-substring-no-properties beg (point))))
2411 (one (type end) (let ((s (progn
2416 ;; blech, begone bu"tt"-ugly blatherings
2417 ;; (but bide brobdingnagian boards)...
2418 (if (and (string= "tt" s)
2423 ((simpletext color) s)
2424 ((number real double) (string-to-number s))
2427 (t (error "Unhandled type: %S" type)))))
2428 (val (spec) (cond ((symbolp spec)
2431 ;; todo: check range here.
2432 (one (aref spec 0) :end))
2433 ((eq 'or (car spec))
2434 (let ((v (one (cadr spec) t)))
2435 (if (= ?\] (following-char))
2438 ;; todo: this assumes `spec' has the form
2439 ;; (or foo (foo . bar))
2440 ;; i.e., foo is not rescanned. e.g., `SZ'.
2441 ;; probably this assumption is consistent
2442 ;; w/ the SGF authors' desire to make the
2443 ;; parsing easy, but you never know...
2444 (cons v (one (cdaddr spec) :end)))))
2445 (t (cons (one (car spec) :mid)
2446 (one (cdr spec) :end)))))
2447 (short (who) (when (eobp)
2448 (error "Unexpected EOF while reading %s" who)))
2449 (atvalp () (= ?\[ (following-char)))
2450 (PROP () (let (name spec ltype)
2451 (sw) (short 'property)
2452 (when (looking-at "[A-Z]")
2453 (setq name (read (current-buffer))
2454 spec (cdr (assq name specs)))
2457 (cdr (assq name keywords))
2458 (prog1 (if (= 1 (length spec))
2460 (unless (memq (setq ltype (car spec))
2462 (error "Bad spec: %S" spec))
2463 (if (and (eq 'elist ltype) (sw)
2466 (let ((type (cadr spec))
2468 (while (and (sw) (atvalp)
2469 (setq mo (val type)))
2474 (forward-char 1))))))
2475 (morep () (and (sw) (not (eobp))))
2476 (seek (c) (and (morep) (= c (following-char))))
2477 (seek-into (c) (when (seek c)
2480 (NODE () (when (seek-into ?\;)
2482 while (setq prop (PROP))
2484 (when (eq :SZ (car prop))
2485 (setq SZ (cdr prop)))
2492 (push (setq node (NODE))
2497 (loop while (seek ?\()
2503 (insert-file-contents filename)
2505 collect (apply 'vector (TREE nil)))))))
2507 (defun gnugo/sgf-hang-from-root (tree)
2508 (let ((ht (make-hash-table :test 'eq))
2509 (leaves (append tree nil)))
2513 with rh ; rectified history
2514 with bp ; branch point
2516 until (setq bp (gethash node ht))
2518 (push node rh) ; good for now: ½τ
2522 ;; first run: main line
2524 ;; subsequent runs: grafts (value discarded)
2526 ;; Maintain order of ‘leaves’.
2527 (let ((was (cdr bp)))
2528 (if (gnugo--nodep (car was))
2532 (setq tree (hang (pop leaves)))
2533 (mapc #'hang leaves)
2536 (defun gnugo/sgf-write-file (collection filename)
2537 ;; take responsibility for our actions
2538 (let ((me (cons "gnugo.el" gnugo-version)))
2539 (dolist (tree collection)
2540 (gnugo--set-root-prop :AP me tree)))
2542 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2543 (specs (mapcar (lambda (full)
2544 (cons (intern (format ":%s" (car full)))
2546 gnugo/sgf-*r4-properties*))
2548 ;; todo: escape special chars for `text' and `simpletext'.
2550 ((>>one (v) (insert (format "[%s]" v)))
2551 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2552 (>>nl () (cond ((memq name aft-newline-appreciated)
2554 ((< 60 (current-column))
2562 (insert (substring (symbol-name name) 1))
2565 (setq spec (cdr (assq name specs)))
2569 (let ((>> (if (consp (cadr spec))
2572 (dolist (little-v v)
2574 (funcall >> little-v)
2581 (loop initially (insert ";")
2585 (unless (zerop (current-column))
2589 (funcall (if (gnugo--nodep x)
2595 (dolist (tree collection)
2596 (>>tree (gnugo/sgf-hang-from-root tree)))
2598 (write-file filename)))))
2600 ;;; gnugo.el ends here