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>
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase). Other keybindings are described in
43 ;; the `gnugo-board-mode' documentation, which you may view with the command
44 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
45 ;; the last move and who is currently to play. Capture counts and other info
46 ;; are shown on the mode line immediately following the major mode name.
48 ;; While GNU Go is pondering its next move, certain commands that rely on its
49 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
50 ;; is normal. When it is your turn again you may retry the command. In the
51 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
52 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
54 ;; If GNU Go should crash during a game the mode line will show "no process".
55 ;; Please report the event to the GNU Go maintainers so that they can improve
59 ;; Meta-Playing (aka Customizing)
60 ;; ------------------------------
62 ;; Customization is presently limited to
63 ;; vars: `gnugo-program'
64 ;; `gnugo-animation-string'
66 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
68 ;; normal hooks: `gnugo-board-mode-hook'
69 ;; `gnugo-post-move-hook'
70 ;; and the keymap: `gnugo-board-mode-map'
72 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
73 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
78 (eval-when-compile (require 'cl)) ; use the source luke!
79 (require 'ascii-art-to-unicode) ; for `aa2u'
80 (require 'time-date) ; for `time-subtract'
82 ;;;---------------------------------------------------------------------------
85 (defconst gnugo-version "2.3.1"
86 "Version of gnugo.el currently loaded.
87 This follows a MAJOR.MINOR.PATCH scheme.")
89 ;;;---------------------------------------------------------------------------
90 ;;; Variables for the uninquisitive programmer
92 (defvar gnugo-program "gnugo"
93 "Command to start an external program that speaks GTP, such as \"gnugo\".
94 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
95 the command `gnugo' will prefix OPTIONS in its default offering when it
96 queries you for additional options. It is an error for \"--mode\" to appear
99 For more information on GTP and GNU Go, feel free to visit:
100 http://www.gnu.org/software/gnugo")
102 (defvar gnugo-board-mode-map nil
103 "Keymap for GNUGO Board mode.")
105 (defvar gnugo-board-mode-hook nil
106 "Hook run when entering GNUGO Board mode.")
108 (defvar gnugo-inhibit-refresh nil
109 "Used in `gnugo-post-move-hook'.")
111 (defvar gnugo-post-move-hook nil
112 "Normal hook run after a move and before the board is refreshed.
113 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
114 (setq gnugo-inhibit-refresh t)
115 Initially, when `run-hooks' is called, the current buffer is the GNUGO
116 Board buffer of the game. Hook functions that switch buffers must take
117 care not to call (directly or indirectly through some other function)
118 `gnugo-put' or `gnugo-get' after the switch.")
120 (defvar gnugo-animation-string
121 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
122 (concat jam jam jam jam jam
123 ;; "SECRET MESSAGE HERE"
124 blink blink blink blink blink blink blink blink
125 ;; Playing go is like fighting ignorance: when you think you have
126 ;; surrounded something by knowing it very well it often turns
127 ;; out that in the time you spent deepening this understanding,
128 ;; other areas of ignorance have surrounded you.
129 spin spin spin spin spin spin spin spin spin
130 ;; Playing go is not like fighting ignorance: what one person
131 ;; knows many people may come to know; knowledge does not build
132 ;; solely move by move. Wisdom, on the other hand...
134 "String whose individual characters are used for animation.
135 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
136 render the stones in their respective result groups as the first character
137 in the string, then the next, and so on.")
139 (defvar gnugo-mode-line "~b ~w :~m :~u"
140 "A `mode-line-format'-compliant value for GNUGO Board mode.
141 If a single string, the following special escape sequences are
142 replaced with their associated information:
143 ~b,~w black,white captures (a number)
144 ~p current player (black or white)
146 ~t time waiting for the current move
147 ~u time taken for the Ultimate (most recent) move
148 The times are in seconds, or \"-\" if that information is not available.
149 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
151 (defvar gnugo-X-face 'font-lock-string-face
152 "Name of face to use for X (black) stones.")
154 (defvar gnugo-O-face 'font-lock-builtin-face
155 "Name of face to use for O (white) stones.")
157 (defvar gnugo-grid-face 'default
158 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
160 ;;;---------------------------------------------------------------------------
161 ;;; Variables for the inquisitive programmer
163 (defconst gnugo-font-lock-keywords
164 '(("X" . gnugo-X-face)
165 ("O" . gnugo-O-face))
166 "Font lock keywords for `gnugo-board-mode'.")
168 (defvar gnugo-option-history nil)
170 (defvar gnugo-state nil) ; hint: C-c C-p
173 (defvar gnugo-xpms nil))
175 (defvar gnugo-frolic-parent-buffer nil)
176 (defvar gnugo-frolic-origin nil)
178 ;;;---------------------------------------------------------------------------
179 ;;; Support functions
181 (defsubst gnugo--mkht (&rest etc)
182 (apply 'make-hash-table :test 'eq etc))
184 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
185 (compare-strings s1 beg1 nil s2 beg2 nil))
187 (defun gnugo-put (key value)
188 "Associate move/game/board-specific property KEY with VALUE.
190 There are many properties, each named by a keyword, that record and control
191 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
192 of properties, stored in the hash table `gnugo-state'. Here we document
193 some of the more stable properties. You may wish to use them as part of
194 a `gnugo-post-move-hook' function, for example. Be careful to preserve
195 the current buffer as `gnugo-state' is made into a buffer-local variable.
196 NOTE: In the following, \"see foo\" actually means \"see foo source or
197 you may never really understand to any degree of personal satisfaction\".
199 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
201 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
203 :game-over -- nil until game over at which time its value is set to
204 the alist `((live GROUP ...) (dead GROUP ...))'
206 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
207 a simple list of one or more gametrees, updated in
208 conjunction w/ :sgf-gametree and :monkey
210 :sgf-gametree -- one of the gametrees in :sgf-collection
212 :monkey -- vector of two elements:
213 MEM, a pointer to one of the branches in the gametree;
214 BIDX, the index of the \"current branch\"
216 :gnugo-color -- either \"black\" or \"white\"
220 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
223 :black-captures -- these are strings since gnugo.el doesn't do anything
224 :white-captures w/ the information besides display it in the mode line;
225 gory details in functions `gnugo-propertize-board-buffer'
226 and `gnugo-merge-showboard-results' (almost more effort
227 than they are worth!)
229 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
230 `gnugo-toggle-image-display' and `gnugo-refresh',
231 as well as gnugo-xpms.el (available elsewhere)
233 :all-yy -- list of 46 keywords used as the `category' text property
234 (so that their plists, typically w/ property `display' or
235 `do-not-display') are consulted by the Emacs display engine;
236 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
237 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
239 :lparen-ov -- overlays shuffled about to indicate the last move; only
240 :rparen-ov one is used when displaying using images
242 :last-user-bpos -- board position; keep the hapless human happy
244 As things stabilize probably more info will be added to this docstring."
246 (puthash key value gnugo-state))
248 (defun gnugo-get (key)
249 "Return the move/game/board-specific value for KEY.
251 (gethash key gnugo-state))
253 (defsubst gnugo--tree-mnum (tree)
256 (defsubst gnugo--tree-ends (tree)
259 (defsubst gnugo--set-tree-ends (tree ends)
261 ;; hmm, probably unnecessary
264 (defun gnugo-describe-internal-properties ()
265 "Pretty-print `gnugo-state' properties in another buffer.
266 Handle the big, slow-to-render, and/or uninteresting ones specially."
268 (let ((buf (current-buffer))
269 (d (gnugo-get :diamond))
271 (loop for key being the hash-keys of gnugo-state
272 using (hash-values val)
276 (format "hash: %X (%d images)"
282 (list (hash-table-count
283 (gnugo--tree-mnum val))
286 (gnugo--tree-ends val)))
288 (let ((mem (aref val 0)))
293 (switch-to-buffer (get-buffer-create
294 (format "%s*GNUGO Board Properties*"
295 (gnugo-get :diamond))))
298 (setq truncate-lines t)
302 (goto-char (point-min))
303 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
307 (while (re-search-forward rx (point-max) t)
308 (let ((pos (get-text-property (string-to-number (match-string 1))
309 'gnugo-position buf)))
310 (delete-region (+ 2 (match-beginning 0)) (point))
311 (insert (format " %S" pos))))))
312 (message "%d properties" (length acc))))
314 (defun gnugo-board-buffer-p (&optional buffer)
315 "Return non-nil if BUFFER is a GNUGO Board buffer."
316 (eq 'gnugo-board-mode
319 (or buffer (current-buffer)))))
321 (defun gnugo-board-user-play-ok-p (&optional buffer)
322 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
323 (with-current-buffer (or buffer (current-buffer))
324 (and gnugo-state (not (gnugo-get :waitingp)))))
326 (defsubst gnugo--blackp (string)
327 (string= "black" string))
329 (defun gnugo-other (color)
330 (if (gnugo--blackp color) "white" "black"))
332 (defun gnugo-gate (&optional in-progress-p)
333 (unless (gnugo-board-buffer-p)
334 (user-error "Wrong buffer -- try M-x gnugo"))
335 (unless (gnugo-get :proc)
336 (user-error "No \"gnugo\" process!"))
337 (when (gnugo-get :waitingp)
338 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
339 (gnugo-get :user-color)))
340 (when (and (gnugo-get :game-over) in-progress-p)
341 (user-error "Sorry, game over")))
343 (defun gnugo-sentinel (proc string)
344 (let ((status (process-status proc)))
345 (when (memq status '(exit signal))
346 (let ((buf (process-buffer proc)))
347 (when (buffer-live-p buf)
348 (with-current-buffer buf
349 (setq mode-line-process
351 (propertize (car (split-string string))
352 'face 'font-lock-warning-face)
354 (when (eq proc (gnugo-get :proc))
355 (gnugo-put :proc nil))))))))
357 (defun gnugo--begin-exchange (proc filter line)
358 (declare (indent 2)) ; good time, for a rime
359 ; nice style, for a wile...
360 (set-process-filter proc filter)
361 (process-send-string proc line)
362 (process-send-string proc "\n"))
364 (defun gnugo--q (fmt &rest args)
365 "Send formatted command \"FMT ARGS...\"; wait for / return response.
366 The response is a string whose first two characters indicate the
367 status of the command. See also `gnugo-query'."
368 (when (gnugo-get :waitingp)
369 (user-error "Sorry, still waiting for %s to play"
370 (gnugo-get :gnugo-color)))
371 (let ((proc (gnugo-get :proc)))
372 (process-put proc :incomplete t)
373 (process-put proc :srs "") ; synchronous return stash
374 (gnugo--begin-exchange
375 proc (lambda (proc string)
376 (let ((full (concat (process-get proc :srs)
378 (process-put proc :srs full)
379 (unless (numberp (gnugo--compare-strings
380 full (max 0 (- (length full)
383 (process-put proc :incomplete nil))))
386 (apply #'format fmt args)))
387 (while (process-get proc :incomplete)
388 (accept-process-output proc 30))
389 (prog1 (substring (process-get proc :srs) 0 -2)
390 (process-put proc :srs ""))))
392 (defun gnugo-query (message-format &rest args)
393 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
394 Return a string that omits the first two characters (corresponding
395 to the status indicator in the Go Text Protocol). Use this function
396 when you are sure the command cannot fail."
397 (substring (apply 'gnugo--q message-format args)
400 (defun gnugo-lsquery (message-format &rest args)
401 (split-string (apply 'gnugo-query message-format args)))
403 (defun gnugo--root-node (&optional tree)
404 (aref (or tree (gnugo-get :sgf-gametree))
407 (defsubst gnugo--root-prop (prop &optional tree)
408 (cdr (assq prop (gnugo--root-node tree))))
410 (defun gnugo--set-root-prop (prop value &optional tree)
411 (let* ((root (gnugo--root-node tree))
412 (cur (assq prop root)))
415 (push (cons prop value)
416 (cdr (last root))))))
418 (defun gnugo-goto-pos (pos)
419 "Move point to board position POS, a letter-number string."
420 (goto-char (point-min))
421 (forward-line (- (1+ (gnugo-get :SZ))
422 (string-to-number (substring pos 1))))
424 (forward-char (+ (if (= 32 (following-char)) 1 2)
425 (* 2 (- (let ((letter (aref pos 0)))
431 (defun gnugo-f (frag)
432 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
434 (defun gnugo-yang (c)
435 (cdr (assq c '((?+ . hoshi)
437 (?X . (bmoku . bpmoku))
438 (?O . (wmoku . wpmoku))))))
440 (defun gnugo-yy (yin yang &optional momentaryp)
441 (gnugo-f (format "%d-%s"
442 yin (cond ((and (consp yang) momentaryp) (cdr yang))
443 ((consp yang) (car yang))
446 (defun gnugo-toggle-image-display ()
447 (unless (and (fboundp 'display-images-p) (display-images-p))
448 (user-error "Display does not support images, sorry"))
449 (require 'gnugo-xpms)
450 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
451 (user-error "Could not load `gnugo-xpms', sorry"))
452 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
453 (unless (eq fresh (gnugo-get :xpms))
454 (gnugo-put :xpms fresh)
455 (gnugo-put :all-yy nil)))
456 (let* ((new (not (gnugo-get :display-using-images)))
457 (act (if new 'display 'do-not-display)))
459 (setcar (symbol-plist yy) act))
460 (or (gnugo-get :all-yy)
462 (prog1 (mapcar (lambda (ent)
464 (yy (gnugo-yy (cdr k) (car k))))
465 (setplist yy `(not-yet ,(cdr ent)))
468 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
470 (gnugo-put :w-imul (car imul))
471 (gnugo-put :h-imul (cdr imul)))))))
472 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
473 (gnugo-put :highlight-last-move-spec
476 (get (gnugo-yy (get-text-property p 'gnugo-yin)
477 (get-text-property p 'gnugo-yang)
481 (gnugo-get :default-highlight-last-move-spec)))
482 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
483 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
484 (mapc 'delete-overlay (cdar group))
485 (setcdr (car group) nil))
486 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
487 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
488 (gnugo-put :display-using-images new)))
490 (defun gnugo-toggle-grid ()
491 "Turn the grid around the board on or off."
493 (funcall (if (memq :nogrid buffer-invisibility-spec)
494 'remove-from-invisibility-spec
495 'add-to-invisibility-spec)
497 (save-excursion (gnugo-refresh)))
499 (defun gnugo-propertize-board-buffer ()
501 (insert (substring (gnugo--q "showboard") 3))
502 (let* ((grid-props (list 'invisible :nogrid
503 'font-lock-face gnugo-grid-face))
504 (%gpad (gnugo-f 'gpad))
505 (%gspc (gnugo-f 'gspc))
506 (%lpad (gnugo-f 'lpad))
507 (%rpad (gnugo-f 'rpad))
508 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
509 (size (gnugo-get :SZ))
510 (size-string (number-to-string size)))
511 (goto-char (point-min))
512 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
513 (skip-chars-forward " ")
514 (put-text-property (1- (point)) (point) 'category %gpad)
515 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
517 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
518 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
519 (let* ((row (match-string-no-properties 1))
521 (other-edge (+ edge (* 2 size) -1))
522 (right-empty (+ other-edge (length row) 1))
523 (top-p (string= size-string row))
524 (bot-p (string= "1" row)))
525 (let* ((nL (- edge 1 (length size-string)))
527 (ov (make-overlay nL nR (current-buffer) t)))
528 (add-text-properties nL nR grid-props)
529 ;; We redundantly set `invisible' in the overlay to workaround
530 ;; a display bug whereby text *following* the overlaid text is
531 ;; displayed with the face of the overlaid text, but only when
532 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
533 ;; This has something to do w/ the bletcherous `before-string'.
534 (overlay-put ov 'invisible :nogrid)
535 (overlay-put ov 'category %lpad))
536 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
538 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
539 (truncate (- p edge) 2))
541 (yin (let ((A-p (= edge p))
542 (Z-p (= (1- other-edge) p)))
543 (cond ((and top-p A-p) 1)
552 (yang (gnugo-yang (char-after p))))
553 (add-text-properties p (1+ p)
563 (gnugo-position gnugo-yin))))
564 (unless (= (1- other-edge) p)
565 (add-text-properties (1+ p) (+ 2 p) ispc-props)
566 (put-text-property p (+ 2 p) 'intangible ival)))
567 (add-text-properties (1+ other-edge) right-empty grid-props)
568 (goto-char right-empty)
569 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
570 (let ((prop (if (string= "WH" (match-string 1))
573 (beg (match-beginning 2))
575 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
576 (gnugo-put prop (match-string-no-properties 2))))
578 (put-text-property right-empty (point) 'category %rpad)
580 (add-text-properties (1- (point)) (point-max) grid-props)
581 (skip-chars-forward " ")
582 (put-text-property (1- (point)) (point) 'category %gpad)
583 (put-text-property (point) (progn (end-of-line) (point))
586 (defun gnugo-merge-showboard-results ()
587 (let ((aft (substring (gnugo--q "showboard") 3))
588 (adj 1) ; string to buffer position adjustment
590 (sync "[0-9]* stones$")
591 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
592 ;; restrictive a condition that fails in the case of:
595 ;; ... WHITE has captured 1 stones
598 ;; ... WHITE has captured 14 stones
601 ;; where the after count has more digits than the before count,
602 ;; but shares the same leading digits. In this case, the result
603 ;; of `compare-strings' points to the SPC following the before
604 ;; count (indicated by caret in this example).
606 (bef (buffer-substring-no-properties (point-min) (point-max)))
607 (bef-start 0) (bef-idx 0)
608 (aft-start 0) (aft-idx 0)
609 aft-sync-backtrack mis inc cut new very-strange)
610 (while (numberp (setq mis (gnugo--compare-strings
613 (setq aft-sync-backtrack nil
614 inc (if (cl-minusp mis)
617 bef-idx (+ bef-start inc)
618 aft-idx (+ aft-start inc)
619 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
622 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
623 (let ((peek (1- aft-idx)))
624 (while (not (= 32 (aref aft peek)))
625 (setq peek (1- peek)))
626 (setq aft-sync-backtrack (1+ peek))))
630 (if aft-sync-backtrack
631 (- aft-sync-backtrack aft-idx)
634 (if aft-sync-backtrack
635 (let* ((asb aft-sync-backtrack)
636 (l-p (get-text-property cut :gnugo-cf))
639 (keep (text-properties-at cut)))
640 (setq new (substring aft asb (string-match " " aft asb)))
641 (plist-put keep :gnugo-cf (cons (length new) capprop))
642 (gnugo-put capprop new)
643 (delete-char old-len)
644 (insert (apply 'propertize new keep))
645 (incf adj (- (length new) old-len)))
646 (setq new (aref aft aft-idx))
647 (insert-and-inherit (char-to-string new))
648 (let ((yin (get-text-property cut 'gnugo-yin))
649 (yang (gnugo-yang new)))
650 (add-text-properties cut (1+ cut)
654 ,(gnugo-yy yin yang))))
656 ;; do this last to avoid complications w/ font lock
657 ;; (this also means we cannot include `intangible' in `front-sticky')
658 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
659 (put-text-property cut (1+ cut) 'intangible very-strange))))))
661 (defsubst gnugo--move-prop (node)
665 (defun gnugo--as-pos-func (size)
666 (lexical-let ((size size))
671 (let ((col (aref cc 0)))
673 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
674 (- size (- (aref cc 1) ?a))))))))
676 (defun gnugo-move-history (&optional rsel)
677 "Determine and return the game's move history.
678 Optional arg RSEL controls side effects and return value.
679 If nil, display the history in the echo area as \"(N moves)\"
680 followed by the space-separated list of moves. When called
681 interactively with a prefix arg (i.e., RSEL is `(4)'), display
682 similarly, but suffix with the mover (either \":B\" or \":W\").
683 If RSEL is the symbol `car' return the most-recent move; if
684 `cadr', the next-to-most-recent move; if `count' the number of
685 moves thus far; if `two' the last two moves as a list, oldest last.
687 For all other values of RSEL, do nothing and return nil."
689 (let* ((monkey (gnugo-get :monkey))
690 (mem (aref monkey 0))
691 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
695 ((as-pos-maybe (x) (if (string= "resign" x)
698 (next (byp) (when (setq node (pop mem)
699 mprop (gnugo--move-prop node))
700 (setq move (as-pos-maybe (cdr mprop)))
702 (format "%s%s" move (car mprop))
706 (tell () (message "(%d moves) %s"
708 (mapconcat 'identity (nreverse acc) " ")))
709 (finish (byp) (while mem (next byp)) (tell)))
714 (`cadr (nn) (car (nn)))
715 (`count (gethash (car mem) (gnugo--tree-mnum
716 (gnugo-get :sgf-gametree))))
720 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
721 "A special mode for viewing a GNUGO gametree.
722 Initially View minor mode is active.
724 \\{gnugo-frolic-mode-map}"
725 (buffer-disable-undo))
727 (defun gnugo-frolic-quit ()
728 "Kill GNUGO Frolic buffer and switch to its parent buffer."
730 (let ((bye (current-buffer)))
731 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
732 gnugo-frolic-parent-buffer))
735 (defun gnugo-frolic-return-to-origin ()
736 "Move point to the board's current position."
738 (if (not gnugo-frolic-origin)
739 (message "No origin")
740 (goto-char gnugo-frolic-origin)
741 (recenter (- (count-lines (line-beginning-position)
744 (defun gnugo-frolic-in-the-leaves ()
745 "Display the game tree in a *GNUGO Frolic* buffer.
746 This looks something like:
749 2 W -- K10 K10 K10 K10
768 with 0, 1, ... N (in this case N is 3) in the header line
769 to indicate the branches. Branch 0 is the \"main line\".
770 Point (* in this example) indicates the current position,
771 and moves not actually on the game tree (e.g., E7, branch 3)
772 are dimmed. Type \\[describe-mode] in that buffer for details."
774 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
776 (from (current-buffer))
777 ;; todo: use defface once we finally succumb to ‘customize’
778 (dimmed-node-face (list :inherit 'default
779 :foreground "gray50"))
780 (tree (gnugo-get :sgf-gametree))
781 (ends (copy-sequence (gnugo--tree-ends tree)))
782 (mnum (gnugo--tree-mnum tree))
785 (width (length ends))
786 (lanes (number-sequence 0 (1- width)))
787 (monkey (gnugo-get :monkey))
788 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
789 (at (car (aref monkey 0)))
790 (bidx (aref monkey 1))
791 (valid (map 'vector (lambda (end)
792 (gethash (car end) mnum))
794 (max-move-num (apply 'max (append valid nil)))
795 (inhibit-read-only t)
801 (propertize s 'face face))
802 (fsi (fmt &rest args)
803 (insert (apply 'format fmt args))))
809 for node in (aref ends bx)
810 do (if (setq fork (on node))
813 ;; todo: ignore non-"move" nodes
814 (eq node (car (aref ends bix))))
816 (pushnew other (gethash node soil))))
821 (puthash node bx seen))
824 (switch-to-buffer buf)
827 (setq header-line-format
828 (concat (make-string 11 ?\s)
829 (mapconcat (lambda (n)
833 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
834 (set (make-local-variable 'gnugo-state)
835 (buffer-local-value 'gnugo-state from))
838 from max-move-num downto 1
843 (goto-char (point-min))
845 n (aref ["W" "B"] (logand 1 n))))
847 do (let* ((node (unless (< (aref valid bx) n)
848 ;; todo: ignore non-"move" nodes
849 (pop (aref ends bx))))
852 (s (cond ((not node) "")
853 ((not (setq move (gnugo--move-prop node))) "-")
854 (t (funcall as-pos (cdr move))))))
855 (when (and ok (setq br (gethash node soil)))
856 (push (cons bx (sort br '<))
859 (cond ((and (eq at node)
862 (setq finish (point-marker)))
863 (emph s (list :inherit 'default
864 :foreground (frame-parameter
865 nil 'cursor-color))))
867 (emph s dimmed-node-face))
870 (when (progn (newline)
871 (setq forks (nreverse forks)))
872 (let* ((margin (make-string 11 ?\s))
873 (count (length forks))
874 (heads (mapcar #'car forks))
875 (tails (mapcar #'cdr forks)))
877 ((spaced (lanes func)
878 (mapconcat func lanes " "))
879 ;; live to play ~ ~ ()
880 ;; play to learn (+) (-) . o O
881 ;; learn to live --ttn .M. _____U
882 (dashed (lanes func) ;;; _____ ^^^^
883 (mapconcat func lanes "-----"))
885 (spaced lanes (lambda (bx)
889 (pad-unless (condition)
900 do (let* ((one (car ls))
903 (mapcar 'car (cdr ls))
905 (apply 'append (mapcar 'cdr bef))))
908 (end (car (last ord))))
910 ((also (b e) (cnxn (number-sequence b e)
915 (pad-unless (zerop beg))
916 (dashed (number-sequence beg end)
918 (cond ((memq bx ord) "+")
921 (pad-unless (>= end width))
922 (also (1+ end) (1- width))
925 (edge (apply 'append tails))
926 (aa2u (line-beginning-position
927 (- (1+ (length forks))))
930 (set (make-local-variable 'gnugo-frolic-origin) finish)
931 (gnugo-frolic-return-to-origin))))
933 (defun gnugo--awake ()
934 (let* ((tree (gnugo-get :sgf-gametree))
935 (ends (gnugo--tree-ends tree))
936 (width (length ends))
937 (monkey (gnugo-get :monkey))
938 (line (count-lines (point-min) (line-beginning-position)))
939 (col (current-column)))
940 (values tree ends width
941 monkey (aref monkey 1)
942 line col (unless (> 10 col)
943 (let ((try (/ (- col 10)
945 (unless (<= width try)
948 (defmacro gnugo--awakened (&rest body)
949 `(multiple-value-bind (tree ends width
956 (defun gnugo--swiz (direction &optional blunt)
959 (user-error "No branch here"))
960 (let* ((b (cond ((numberp blunt)
961 (unless (and (< -1 blunt)
963 (user-error "No such branch: %s" blunt))
965 (t (mod (+ direction a) width))))
966 (flit (if blunt (lambda (n)
971 (mod (+ direction n) width))))
972 (was (copy-sequence ends))
973 (new-bidx (funcall flit bidx)))
975 (assert (eq 'gnugo-board-mode major-mode))
976 (loop for bx below width
977 do (aset ends (funcall flit bx)
979 (unless (= new-bidx bidx)
980 (aset monkey 1 new-bidx))
981 (gnugo-frolic-in-the-leaves)
982 (goto-char (point-min))
984 (forward-char (+ 10 (* 6 b))))))
986 (defun gnugo-frolic-exchange-left ()
987 "Exchange the current branch with the one to its left."
991 (defun gnugo-frolic-rotate-left ()
992 "Rotate all branches left."
996 (defun gnugo-frolic-exchange-right ()
997 "Exchange the current branch with the one to its right."
1001 (defun gnugo-frolic-rotate-right ()
1002 "Rotate all branches right."
1006 (defun gnugo-frolic-set-as-main-line ()
1007 "Make the current branch the main line."
1009 (gnugo--swiz nil 0))
1011 (defun gnugo-frolic-prune-branch ()
1012 "Remove the current branch from the gametree.
1013 This fails if there is only one branch in the tree.
1014 This fails if the monkey is on the current branch
1015 \(a restriction that will probably be lifted Real Soon Now\)."
1019 (user-error "No branch here"))
1020 ;; todo: define meaningful eviction semantics; remove restriction
1022 (user-error "Cannot prune with monkey on branch"))
1024 (user-error "Cannot prune last remaining branch"))
1025 ;; A numeric line number is unreliable; branch points might vanish.
1026 ;; Hang on to something more useful, instead.
1027 (setq line (save-excursion
1028 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1030 (let* ((new (append ends nil))
1031 ;; Gratuitous ‘pop’ rv assignment avoids byte-compiler warning.
1032 (bye (pop (nthcdr a new))))
1033 (gnugo--set-tree-ends tree (apply 'vector new)))
1035 (aset monkey 1 (decf bidx)))
1037 (gnugo-frolic-in-the-leaves)
1039 (goto-char (point-min))
1040 (search-forward line)
1041 (move-to-column (+ 10 (* 6 (min a (- width 2))))))))
1043 (defun gnugo-frolic-backward-branch (&optional n)
1044 "Move backward N (default 1) branches."
1047 (move-to-column (+ 10 (* 6 (mod (- (or a width) n) width))))))
1049 (defun gnugo-frolic-forward-branch (&optional n)
1050 "Move forward N (default 1) branches."
1053 (move-to-column (+ 10 (* 6 (mod (+ (or a -1) n) width))))))
1055 (defun gnugo-boss-is-near ()
1056 "Do `bury-buffer' until the current one is not a GNU Board."
1058 (while (gnugo-board-buffer-p)
1061 (defsubst gnugo--passp (string)
1062 (string= "PASS" string))
1064 (defsubst gnugo--no-regrets (monkey ends)
1065 (eq (aref ends (aref monkey 1))
1068 (defun gnugo-note (property value &optional mogrifyp)
1070 (let ((sz (gnugo-get :SZ)))
1072 ((mog (pos) (if (gnugo--passp pos)
1074 (let* ((col (aref pos 0))
1075 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1076 (two (+ ?a (- sz (string-to-number
1077 (substring pos 1))))))
1078 (format "%c%c" one two)))))
1079 (setq value (if (consp value)
1080 (mapcar #'mog value)
1082 (let* ((pair (cons property value))
1084 (monkey (gnugo-get :monkey))
1085 (mem (aref monkey 0))
1087 (if (memq property '(:B :W))
1088 (let* ((tree (gnugo-get :sgf-gametree))
1089 (ends (gnugo--tree-ends tree))
1090 (mnum (gnugo--tree-mnum tree))
1091 (count (length ends))
1092 (tip-move-num (gethash tip mnum))
1093 (bidx (aref monkey 1)))
1094 ;; Detect déjà-vu. That is, when placing "A", avoid:
1100 ;; (such "variations" do not actually vary!) in favor of:
1106 ;; This linear search loses for multiple ‘old’ w/ "A",
1107 ;; a very unusual (but not invalid, sigh) situation.
1111 ;; Start with latest / highest likelihood for hit.
1112 ;; (See "to the right" comment, below.)
1113 from (if (gnugo--no-regrets monkey ends)
1117 if (setq bx (mod (+ bidx i) count)
1120 for m on (aref ends bx)
1121 while (< tip-move-num
1122 (gethash (setq node (car m))
1126 (when (equal pair (assoc property node))
1134 (rotatef (aref ends bidx)
1136 (setq mem previous))
1140 (unless (gnugo--no-regrets monkey ends)
1141 (gnugo--set-tree-ends
1142 tree (let ((ls (append ends nil)))
1143 ;; copy old to the right of new
1144 (push mem (nthcdr bidx ls))
1145 (apply 'vector ls))))
1146 (puthash fruit (1+ (gethash tip mnum)) mnum)
1148 (aset ends bidx mem)))
1149 (setf (aref monkey 0) mem))
1150 (setcdr (last tip) fruit))))
1152 (defun gnugo-close-game (end-time resign)
1153 (gnugo-put :game-end-time end-time)
1154 (let ((now (or end-time (current-time))))
1155 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1157 (gnugo-put :game-over
1158 (if (or (eq t resign)
1159 (and (stringp resign)
1160 (string-match "[BW][+][Rr]esign" resign)))
1162 ((ls (color) (mapcar
1167 (gnugo-query "worm_stones %s" color)
1169 (let ((live (append (ls "black") (ls "white"))))
1172 (let ((dd (gnugo-query "dragon_data"))
1173 (start 0) mem color ent live dead)
1174 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1176 (setq mem (match-string 1 dd)
1177 color (match-string 2 dd)
1179 ent (cons (list color)
1180 (sort (gnugo-lsquery "dragon_stones %s" mem)
1182 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1184 (if (match-string 2 dd)
1187 (setq start (match-end 0)))
1191 (defun gnugo--unclose-game ()
1192 (dolist (prop '(:game-over ; all those in -close-game
1195 (gnugo-put prop nil))
1196 (let* ((root (gnugo--root-node))
1197 (cur (assq :RE root)))
1199 (assert (not (eq cur (car root))) nil
1200 ":RE at head of root node: %S"
1204 (defun gnugo-push-move (userp move)
1205 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
1206 (start (gnugo-get :waiting-start))
1207 (now (current-time))
1208 (resignp (string= "resign" move))
1209 (passp (gnugo--passp move))
1210 (head (gnugo-move-history 'car))
1211 (onep (and head (gnugo--passp head)))
1212 (donep (or resignp (and onep passp))))
1214 (gnugo-merge-showboard-results))
1215 (gnugo-put :last-mover color)
1217 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1218 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
1220 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1222 (gnugo-close-game now resignp))
1223 (gnugo-put :waiting-start (and (not donep) now))
1226 (defun gnugo-venerate (yin yang)
1227 (let* ((fg-yy (gnugo-yy yin yang))
1228 (fg-disp (or (get fg-yy 'display)
1229 (get fg-yy 'do-not-display)))
1230 (fg-data (plist-get (cdr fg-disp) :data))
1231 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1232 (bg-disp (or (get bg-yy 'display)
1233 (get bg-yy 'do-not-display)))
1234 (bg-data (plist-get (cdr bg-disp) :data))
1238 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1239 (setq start (match-end 0))
1240 (string-to-number (match-string 1 s)))))
1241 (while (and (not (cl-minusp ncolors))
1242 (string-match ",\n" s start))
1243 (setq start (match-end 0)
1244 ncolors (1- ncolors)))
1245 (string-match "\"" s start)
1247 (new (copy-sequence fg-data))
1248 (lx (length fg-data))
1249 (sx (funcall bop fg-data))
1250 (sb (funcall bop bg-data))
1251 (color-key (aref new sx))) ; blech, heuristic
1253 (when (and (not (= color-key (aref new sx)))
1254 (cl-plusp (random 4)))
1255 (aset new sx (aref bg-data sb)))
1258 (create-image new 'xpm t :ascent 'center)))
1260 (defun gnugo-refresh (&optional nocache)
1261 "Update GNUGO Board buffer display.
1262 While a game is in progress, parenthesize the last-played stone (no parens
1263 for pass). If the buffer is currently displayed in the selected window,
1264 recenter the board (presuming there is extra space in the window). Update
1265 the mode line. Lastly, move point to the last position played by the user,
1266 if that move was not a pass.
1268 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1269 be slow. (This should normally be unnecessary; specify it only if the display
1270 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1273 (when (and nocache (not (gnugo-get :waitingp)))
1274 (gnugo-propertize-board-buffer))
1275 (let* ((last-mover (gnugo-get :last-mover))
1276 (other (gnugo-other last-mover))
1277 (move (gnugo-move-history 'car))
1278 (game-over (gnugo-get :game-over))
1282 (let ((l-ov (gnugo-get :lparen-ov))
1283 (r-ov (gnugo-get :rparen-ov)))
1284 (if (member move '("PASS" "resign"))
1285 (mapc 'delete-overlay (list l-ov r-ov))
1286 (gnugo-goto-pos move)
1288 (hspec (gnugo-get :highlight-last-move-spec))
1289 (display-value (nth 0 hspec))
1290 (l-offset (nth 1 hspec))
1291 (l-new-pos (+ p l-offset))
1292 (r-action (nth 2 hspec)))
1293 (overlay-put l-ov 'display
1294 (if (functionp display-value)
1295 (funcall display-value p)
1297 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1299 (funcall r-action r-ov)
1300 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1302 (rename-buffer (concat (gnugo-get :diamond)
1304 (format "%s(game over)"
1305 (if (string= move "resign")
1306 (concat move "ation ")
1308 (format "%s(%s to play)"
1309 (if move (concat move " ") "")
1313 (let ((live (cdr (assq 'live game-over)))
1314 (dead (cdr (assq 'dead game-over)))
1316 (unless (eq game-over (get-text-property 1 'game-over))
1317 (dolist (group (append live dead))
1318 (dolist (pos (cdr group))
1319 (gnugo-goto-pos pos)
1321 (put-text-property p (1+ p) 'group group)))
1322 (put-text-property 1 2 'game-over game-over))
1323 (dolist (group live)
1324 (when (setq pall (cdar group))
1325 (mapc 'delete-overlay pall)
1326 (setcdr (car group) nil)))
1327 (dolist (group dead)
1328 (unless (cdar group)
1329 (let (ov pall c (color (caar group)))
1330 (setq c (if (gnugo--blackp color) "x" "o"))
1331 (dolist (pos (cdr group))
1332 (gnugo-goto-pos pos)
1333 (setq p (point) ov (make-overlay p (1+ p)))
1336 (if (gnugo-get :display-using-images)
1337 ;; respect the dead individually; it takes more time
1338 ;; but that's not a problem (for them)
1339 (gnugo-venerate (get-text-property p 'gnugo-yin)
1340 (gnugo-yang (aref (upcase c) 0)))
1341 (propertize c 'face 'font-lock-warning-face)))
1343 (setcdr (car group) pall))))))
1345 (when (setq window (get-buffer-window (current-buffer)))
1346 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1347 (size (gnugo-get :SZ))
1348 (under10p (< size 10))
1349 (h (- (truncate (- (window-height window)
1350 (* size (gnugo-get :hmul))
1354 (edges (window-edges window))
1355 (right-w-edge (nth 2 edges))
1356 (avail-width (- right-w-edge (nth 0 edges)))
1357 (wmul (gnugo-get :wmul))
1358 (imagesp (symbol-plist (gnugo-f 'ispc)))
1359 (w (/ (- avail-width
1364 2 ; between board and grid
1369 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1370 `(display ,(make-string h 10))
1371 '(invisible :nogrid)))
1376 (cond (imagesp (+ (* 0.5 wmul)
1382 (gspc . ,(when imagesp
1386 ;; DWR: image width alone => OBOE!
1388 ;; NB: ‘(* wmul cw)’ is the same
1389 ;; as ‘(car (image-size ... t))’.
1390 (let ((cw (frame-char-width)))
1391 (/ (+ 1.0 (* wmul cw))
1394 (lpad . ,(let ((d `(display (space :align-to ,w))))
1395 ;; We distinguish between these cases to
1396 ;; workaround a display bug whereby the
1397 ;; `before-string' is omitted entirely (not
1398 ;; rendered) when interacting w/ the text
1399 ;; mode last-move left-paren for moves in
1403 ,(apply 'propertize " " d))
1406 (space :align-to ,(1- avail-width))))))
1407 (setplist (gnugo-f (car pair)) (cdr pair)))))
1409 (let ((cur (gnugo-get :mode-line)))
1410 (unless (equal cur gnugo-mode-line)
1411 (setq cur gnugo-mode-line)
1412 (gnugo-put :mode-line cur)
1413 (gnugo-put :mode-line-form
1414 (cond ((stringp cur)
1415 (setq cur (copy-sequence cur))
1417 (while (setq cut (string-match "~[bwpmtu]" cur))
1419 (setq c (aref cur (incf cut)))
1422 `(,(intern (format "squig-%c" c))
1424 (?b '(or (gnugo-get :black-captures) 0))
1425 (?w '(or (gnugo-get :white-captures) 0))
1426 (?p '(gnugo-other (gnugo-get :last-mover)))
1427 (?t '(let ((ws (gnugo-get :waiting-start)))
1429 (cadr (time-since ws))
1431 (?u '(or (gnugo-get :last-waiting) "-"))
1432 (?m '(gnugo-move-history 'count))))
1434 `(let ,(delete-dups (copy-sequence acc))
1435 (format ,cur ,@(reverse (mapcar 'car acc))))))
1437 (let ((form (gnugo-get :mode-line-form)))
1438 (setq mode-line-process
1440 ;; this dynamicism is nice but excessive in its wantonness
1441 ;;- `(" [" (:eval ,form) "]")
1442 ;; this dynamicism is ok because the user triggers it
1443 (list (format " [%s]" (eval form))))))
1444 (force-mode-line-update))
1446 (when (setq last (gnugo-get :last-user-bpos))
1447 (gnugo-goto-pos last))))
1449 ;;;---------------------------------------------------------------------------
1450 ;;; Game play actions
1452 (defun gnugo-get-move-insertion-filter (proc string)
1453 (with-current-buffer (process-buffer proc)
1454 (let* ((so-far (gnugo-get :get-move-string))
1455 (full (gnugo-put :get-move-string (concat so-far string))))
1456 (when (string-match "^= \\(.+\\)\n\n" full)
1457 (let ((pos-or-pass (match-string 1 full)))
1458 (gnugo-put :get-move-string nil)
1459 (gnugo-put :waitingp nil)
1460 (gnugo-push-move nil pos-or-pass)
1461 (let ((buf (current-buffer)))
1462 (let (gnugo-inhibit-refresh)
1463 (run-hooks 'gnugo-post-move-hook)
1464 (unless gnugo-inhibit-refresh
1465 (with-current-buffer buf
1466 (gnugo-refresh))))))))))
1468 (defun gnugo-get-move (color)
1469 (gnugo-put :waitingp t)
1470 (gnugo--begin-exchange
1471 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1472 (concat "genmove " color))
1473 (accept-process-output))
1475 (defun gnugo-cleanup ()
1476 (when (gnugo-board-buffer-p)
1477 (unless (zerop (buffer-size))
1478 (message "Thank you for playing GNU Go."))
1480 (setplist sym nil) ; "...is next to fordliness." --Huxley
1481 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1482 ;; No worries, things will be Much Better w/ structs, RSN...
1484 (append (gnugo-get :all-yy)
1493 (setq gnugo-state nil)))
1495 (defun gnugo-position ()
1496 (or (get-text-property (point) 'gnugo-position)
1497 (user-error "Not a proper position point")))
1499 (defun gnugo-move ()
1500 "Make a move on the GNUGO Board buffer.
1501 The position is computed from current point.
1502 Signal error if done out-of-turn or if game-over.
1503 To start a game try M-x gnugo."
1506 (let* ((buf (current-buffer))
1507 (pos (gnugo-position))
1508 (move (format "play %s %s" (gnugo-get :user-color) pos))
1509 (accept (gnugo--q move)))
1510 (unless (= ?= (aref accept 0))
1511 (user-error "%s" accept))
1512 (gnugo-push-move t pos) ; value always nil for non-pass move
1513 (let (gnugo-inhibit-refresh)
1514 (run-hooks 'gnugo-post-move-hook)
1515 (unless gnugo-inhibit-refresh
1516 (with-current-buffer buf
1518 (with-current-buffer buf
1519 (gnugo-get-move (gnugo-get :gnugo-color)))))
1521 (defun gnugo-mouse-move (e)
1522 "Do `gnugo-move' at mouse location."
1525 (when (looking-at "[.+]")
1528 (defun gnugo-pass ()
1529 "Make a pass on the GNUGO Board buffer.
1530 Signal error if done out-of-turn or if game-over.
1531 To start a game try M-x gnugo."
1534 (let ((accept (gnugo--q "play %s PASS" (gnugo-get :user-color))))
1535 (unless (= ?= (aref accept 0))
1536 (user-error "%s" accept)))
1537 (let ((donep (gnugo-push-move t "PASS"))
1538 (buf (current-buffer)))
1539 (let (gnugo-inhibit-refresh)
1540 (run-hooks 'gnugo-post-move-hook)
1541 (unless gnugo-inhibit-refresh
1542 (with-current-buffer buf
1545 (with-current-buffer buf
1546 (gnugo-get-move (gnugo-get :gnugo-color))))))
1548 (defun gnugo-mouse-pass (e)
1549 "Do `gnugo-pass' at mouse location."
1554 (defun gnugo-resign ()
1557 (if (not (y-or-n-p "Resign? "))
1558 (message "(not resigning)")
1559 (gnugo-push-move t "resign")
1562 (defun gnugo-animate-group (w/d)
1563 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1564 (let* ((pos (gnugo-position))
1565 (orig-b-m-p (buffer-modified-p))
1567 (unless (memq (following-char) '(?X ?O))
1568 (user-error "No stone at %s" pos))
1569 (setq blurb (message "Computing %s stones ..." w/d)
1570 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1571 (message "%s %s in group." blurb (length stones))
1572 (setplist (gnugo-f 'anim) nil)
1573 (let* ((spec (if (gnugo-get :display-using-images)
1574 (loop with yin = (get-text-property (point) 'gnugo-yin)
1575 with yang = (gnugo-yang (following-char))
1576 with up = (get (gnugo-yy yin yang t) 'display)
1577 with dn = (get (gnugo-yy yin yang) 'display)
1578 for n below (length gnugo-animation-string)
1579 collect (if (zerop (logand 1 n))
1581 (split-string gnugo-animation-string "" t)))
1583 (ovs (save-excursion
1584 (mapcar (lambda (pos)
1585 (gnugo-goto-pos pos)
1587 (ov (make-overlay p (1+ p))))
1588 (overlay-put ov 'category (gnugo-f 'anim))
1589 (overlay-put ov 'priority most-positive-fixnum)
1592 (setplist (gnugo-f 'anim) (cons 'display cell))
1593 (while (and (cdr spec) ; let last linger lest levity lost
1594 (sit-for 0.08675309)) ; jenny jenny i got your number...
1595 (setcar cell (setq spec (cdr spec)))
1596 ;; Force redisplay of overlays.
1597 (set-buffer-modified-p orig-b-m-p))
1599 (mapc 'delete-overlay ovs)
1602 (defun gnugo-display-group-data (command buffer-name)
1603 (message "Computing %s ..." command)
1604 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1605 (switch-to-buffer buffer-name)
1608 (message "Computing %s ... done." command))
1610 (defun gnugo-worm-stones ()
1611 "In the GNUGO Board buffer, animate \"worm\" at current position.
1612 Signal error if done out-of-turn or if game-over.
1613 See variable `gnugo-animation-string' for customization."
1616 (gnugo-animate-group 'worm))
1618 (defun gnugo-worm-data ()
1619 "Display in another buffer data from \"worm\" at current position.
1620 Signal error if done out-of-turn or if game-over."
1623 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1625 (defun gnugo-dragon-stones ()
1626 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1627 Signal error if done out-of-turn or if game-over.
1628 See variable `gnugo-animation-string' for customization."
1631 (gnugo-animate-group 'dragon))
1633 (defun gnugo-dragon-data ()
1634 "Display in another buffer data from \"dragon\" at current position.
1635 Signal error if done out-of-turn or if game-over."
1638 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1640 (defun gnugo-toggle-dead-group ()
1641 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1642 The group is selected from current position (point). Signal error if
1643 not in game-over or if there is no group at that position.
1645 In the context of GNU Go, a group is called a \"dragon\" and may be
1646 composed of more than one \"worm\" (set of directly-connected stones).
1647 It is unclear to the gnugo.el author whether or not GNU Go supports
1648 - considering worms as groups in their own right; and
1649 - toggling group aliveness via GTP.
1650 Due to these uncertainties, this command is only half complete; the
1651 changes you may see in Emacs are not propagated to the gnugo subprocess.
1652 Thus, GTP commands like `final_score' may give unexpected results.
1654 If you are able to expose via GTP `change_dragon_status' in utils.c,
1655 you may consider modifying the `gnugo-toggle-dead-group' source code
1656 to enable full functionality."
1658 (let ((game-over (or (gnugo-get :game-over)
1659 (user-error "Sorry, game still in play")))
1660 (group (or (get-text-property (point) 'group)
1661 (user-error "No stone at that position")))
1662 (now (current-time)))
1663 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1665 (let ((live (assq 'live game-over))
1666 (dead (assq 'dead game-over))
1668 (if (memq group live)
1669 (setq bef live now dead)
1670 (setq bef dead now live))
1671 (setcdr bef (delq group (cdr bef)))
1672 (setcdr now (cons group (cdr now)))
1673 ;; disabled permanently -- too wrong
1677 (let ((color (caar group)))
1678 (dolist (stone (cdr group))
1679 (gnugo-query "play %s %s" color stone)))))
1682 ;; drastic (and wrong -- clobbers capture info, etc)
1683 (gnugo-query "clear_board")
1684 (mapc #'populate (cdr live)))))
1685 ;; here is the desired interface (to be enabled Some Day)
1687 (gnugo-query "change_dragon_status %s %s"
1688 (cadr group) (if (eq now live)
1694 (defun gnugo-estimate-score ()
1695 "Display estimated score of a game of GNU Go.
1696 Output includes number of stones on the board and number of stones
1697 captured by each player, and the estimate of who has the advantage (and
1698 by how many stones)."
1700 (message "Est.score ...")
1701 (let ((black (length (gnugo-lsquery "list_stones black")))
1702 (white (length (gnugo-lsquery "list_stones white")))
1703 (black-captures (gnugo-query "captures black"))
1704 (white-captures (gnugo-query "captures white"))
1705 (est (gnugo-query "estimate_score")))
1706 ;; might as well update this
1707 (gnugo-put :black-captures black-captures)
1708 (gnugo-put :white-captures white-captures)
1709 (message "Est.score ... B %s %s | W %s %s | %s"
1710 black black-captures white white-captures est)))
1712 (defun gnugo-write-sgf-file (filename)
1713 "Save the game history to FILENAME (even if unfinished).
1714 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1715 (interactive "FWrite game as SGF file: ")
1716 (when (and (file-exists-p filename)
1717 (not (y-or-n-p "File exists. Continue? ")))
1718 (user-error "Not writing %s" filename))
1719 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1720 (set-buffer-modified-p nil))
1722 (defun gnugo--who-is-who (wait play samep)
1723 (message "GNU Go %splays as %s, you as %s (%s)"
1724 (if samep "" "now ")
1727 "NOTE: this is a switch!")))
1729 (defsubst gnugo--nodep (x)
1730 (keywordp (caar x)))
1732 (defsubst gnugo--SZ! (size)
1733 (gnugo-put :SZ size))
1735 (defun gnugo-read-sgf-file (filename)
1736 "Load the first game tree from FILENAME, a file in SGF format."
1737 (interactive "fSGF file to load: ")
1738 (when (file-directory-p filename)
1739 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1740 (let (ans play wait samep coll tree)
1741 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1742 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1743 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1744 (expand-file-name filename)))
1746 (user-error "%s" ans))
1747 (setq play (substring ans 2)
1748 wait (gnugo-other play)
1749 samep (string= (gnugo-get :user-color) play))
1750 (gnugo-put :last-mover wait)
1752 (gnugo-put :gnugo-color wait)
1753 (gnugo-put :user-color play))
1754 (setq coll (gnugo/sgf-create filename)
1755 tree (nth (let ((n (length coll)))
1759 ;; (let* ((q (format "Which game? (1-%d)" n))
1760 ;; (choice (1- (read-number q 1))))
1761 ;; (if (and (< -1 choice) (< choice n))
1763 ;; (message "(Selecting the first game)")
1765 ;; but this is what we use (for now) to accomodate
1766 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1768 (message "(Selecting the first game)"))
1771 (gnugo-put :sgf-collection coll)
1772 (gnugo-put :sgf-gametree tree)
1773 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0))
1774 ;; This is deliberately undocumented for now.
1775 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1777 (gnugo-put :game-over
1779 (or (gnugo--root-prop :RE tree)
1780 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1782 (when (and game-over
1783 ;; (maybe) todo: user var to inhibit (can be slow)
1785 (gnugo-close-game nil game-over)))
1787 (set-buffer-modified-p nil)
1788 (gnugo--who-is-who wait play samep)))
1790 (defun gnugo-magic-undo (spec &optional noalt keep)
1791 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1792 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1793 check that the position is occupied by a stone of the user's color,
1794 and if so, remove moves from the history until that position is clear.
1795 If SPEC is a positive number, remove exactly that many moves from the
1796 history, signaling an error if the history is exhausted before finishing.
1797 If SPEC Is 0 (zero), remove either one or two moves,
1798 so that you are to play next.
1799 If SPEC is not recognized, signal \"bad spec\" error.
1801 Refresh the board for each move undone. If (in the case where SPEC is
1802 a number) after finishing, the color to play is not the user's color,
1803 schedule a move by GNU Go.
1805 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1806 turn to play. Optional second arg NOALT non-nil inhibits this.
1808 Optional third arg KEEP non-nil means do not prune the undone moves
1809 from the gametree, such that they become a sub-gametree (variation)
1813 (user-color (gnugo-get :user-color))
1814 (monkey (gnugo-get :monkey))
1815 (tree (gnugo-get :sgf-gametree))
1816 (ends (gnugo--tree-ends tree))
1817 (remorseful (not (gnugo--no-regrets monkey ends)))
1819 (cond ((numberp spec)
1820 (setq n (if (zerop spec)
1821 (if (string= user-color (gnugo-get :last-mover))
1825 done (lambda () (zerop n))))
1826 ((string-match "^[a-z]" spec)
1827 (let ((pos (upcase spec)))
1828 (setq done `(lambda ()
1829 (gnugo-goto-pos ,pos)
1830 (memq (following-char) '(?. ?+))))
1831 (when (funcall done)
1832 (user-error "%s already clear" pos))
1833 (when (= (save-excursion
1834 (gnugo-goto-pos pos)
1836 (if (gnugo--blackp user-color)
1839 (user-error "%s not occupied by %s" pos user-color))))
1840 (t (user-error "Bad spec: %S" spec)))
1841 (when (gnugo-get :game-over)
1842 (gnugo--unclose-game))
1843 (while (not (funcall done))
1844 (setq ans (gnugo--q "undo"))
1845 (unless (= ?= (aref ans 0))
1846 (user-error "%s" ans))
1847 (pop (aref monkey 0))
1848 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1849 (gnugo-merge-showboard-results) ; all
1850 (gnugo-refresh) ; this
1852 (redisplay)) ; eye candy
1853 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1855 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1856 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1858 (gnugo-get :center-position)))
1860 (unless (or keep remorseful)
1861 (aset ends (aref monkey 1) (aref monkey 0)))
1862 (when (and ulastp (not noalt))
1863 (gnugo-get-move (gnugo-get :gnugo-color))))))
1865 (defun gnugo-undo-one-move (&optional me-next)
1866 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1867 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1868 Prefix arg ME-NEXT means to arrange for you to play
1869 the color of the next move (and GNU Go the opposite).
1870 This is useful after loading an SGF file whose last
1871 move was done by the color you prefer to play:
1872 \\[gnugo-read-sgf-file] FILENAME RET
1873 C-u \\[gnugo-undo-one-move]
1875 See also `gnugo-undo-two-moves'."
1878 (gnugo-magic-undo 1 t)
1880 (let* ((wait (gnugo-get :last-mover))
1881 (play (gnugo-other wait)))
1882 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
1883 (gnugo-put :user-color play)
1884 (gnugo-put :gnugo-color wait))))
1886 (defun gnugo-undo-two-moves ()
1887 "Undo a pair of moves (GNU Go's and yours).
1888 However, if you are the last mover, undo only one move.
1889 Regardless, after undoing, it is your turn to play again."
1892 (gnugo-magic-undo 0))
1894 (defun gnugo-oops (&optional position)
1895 "Like `gnugo-undo-two-moves', but keep the undone moves.
1896 The kept moves become a sub-gametree (variation) when play resumes.
1897 Prefix arg means, instead, undo repeatedly up to and including
1898 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1901 (gnugo-magic-undo (if position
1906 (defun gnugo-display-final-score ()
1907 "Display final score and other info in another buffer (when game over).
1908 If the game is still ongoing, Emacs asks if you wish to stop play (by
1909 making sure two \"pass\" moves are played consecutively, if necessary).
1910 Also, add the `:RE' SGF property to the root node of the game tree."
1912 (let ((game-over (gnugo-get :game-over)))
1913 (unless (or game-over
1914 (and (not (gnugo-get :waitingp))
1915 (y-or-n-p "Game still in play. Stop play now? ")))
1916 (user-error "Sorry, game still in play"))
1920 (message "Playing PASS for %s ..."
1921 (gnugo-get (if userp :user-color :gnugo-color)))
1923 (gnugo-push-move userp "PASS")))
1928 (let ((b= " Black = ")
1930 (res (when (string= "resign" (gnugo-move-history 'car))
1931 (gnugo-get :last-mover)))
1935 (format "%s wins.\n"
1936 (substring (if (= ?b (aref res 0)) w= b=)
1938 "The game is over.\n"
1939 (format "Resignation by %s.\n" res))
1940 result (concat (upcase (substring (gnugo-other res) 0 1))
1942 (message "Computing final score ...")
1943 (let* ((g-over (gnugo-get :game-over))
1944 (live (cdr (assq 'live g-over)))
1945 (dead (cdr (assq 'dead g-over)))
1946 (seed (gnugo-get :scoring-seed))
1947 (terr-q (format "final_status_list %%s_territory %d" seed))
1950 (b-terr (length (gnugo-lsquery terr-q "black")))
1951 (w-terr (length (gnugo-lsquery terr-q "white")))
1952 (b-capt (string-to-number (gnugo-get :black-captures)))
1953 (w-capt (string-to-number (gnugo-get :white-captures)))
1954 (komi (gnugo--root-prop :KM)))
1955 (setq blurb (list "The game is over. Final score:\n")
1956 result (gnugo-query "final_score %d" seed))
1957 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1958 (dolist (group live)
1959 (incf (if (gnugo--blackp (caar group))
1962 (length (cdr group))))
1963 (dolist (group dead)
1964 (incf (if (gnugo--blackp (caar group))
1967 (length (cdr group))))
1968 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1969 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1970 w-terr terr komi 'komi (+ w-terr komi))
1973 (dolist (group dead)
1974 (incf (if (gnugo--blackp (caar group))
1977 (* 2 (length (cdr group)))))
1978 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1983 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1987 (+ w-terr w-capt komi))
1989 (push (if (string= "0" result)
1990 "The game is a draw.\n"
1991 (format "%s wins by %s.\n"
1992 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1993 (substring result 2)))
1995 (message "Computing final score ... done")))
1997 (let ((beg (gnugo-get :game-start-time))
1998 (end (gnugo-get :game-end-time)))
2002 ((yep (pretty moment)
2003 (push (format-time-string
2004 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2007 (yep "Game start" beg)
2009 (setq blurb (apply 'concat (nreverse blurb)))
2010 (gnugo--set-root-prop :RE result)
2011 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2015 (defun gnugo-quit ()
2016 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2017 If the game is not over, ask for confirmation first."
2019 (if (or (gnugo-get :game-over)
2020 (y-or-n-p "Quit? "))
2022 (message "(not quitting)")))
2024 (defun gnugo-leave-me-alone ()
2025 "Kill the current buffer unconditionally."
2029 (defun gnugo-fancy-undo (count)
2030 "Rewind the game tree in various ways.
2031 Prefix arg COUNT means to undo that many moves.
2032 Otherwise, undo repeatedly up to and including the move
2033 which placed the stone at point."
2036 ;; TODO: Move this into `gnugo-magic-undo' proper.
2037 (cond ((numberp count) count)
2038 ((consp count) (car count))
2039 (t (gnugo-position)))))
2041 (defun gnugo-toggle-image-display-command () ; ugh
2042 "Toggle use of images to display the board, then refresh."
2044 (gnugo-toggle-image-display)
2045 (save-excursion (gnugo-refresh)))
2047 (defun gnugo-describe-position ()
2048 "Display the board position under cursor in the echo area."
2050 (message "%s" (gnugo-position)))
2052 (defun gnugo-switch-to-another ()
2053 "Switch to another GNU Go game buffer (if any)."
2055 (loop for buf in (cdr (buffer-list))
2056 if (gnugo-board-buffer-p buf)
2059 (switch-to-buffer buf))
2060 finally do (message "(only one)")))
2062 ;;;---------------------------------------------------------------------------
2063 ;;; Command properties and gnugo-command
2065 ;; GTP commands entered by the user are never issued directly to GNU Go;
2066 ;; instead, their behavior and output are controlled by the property
2067 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2068 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2070 ;; :full -- completely interpret the command string; the value is a
2071 ;; func that takes the list of words derived from splitting the
2072 ;; command string (minus the command) and handles everything.
2074 ;; :output -- either a keyword specifying the preferred output method:
2075 ;; :message -- show output in minibuffer
2076 ;; :discard -- sometimes you just don't care;
2077 ;; or a function that takes one arg, the output string, and
2078 ;; handles it completely. default is to switch to buffer
2079 ;; "*gnugo command output*" if the output has a newline,
2080 ;; otherwise use `message'.
2082 ;; :post-thunk -- run after output processing (at the very end).
2084 (defun gnugo-command (command)
2085 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2086 Output and Emacs behavior depend on which command is given (some
2087 commands are handled completely by Emacs w/o using the subprocess;
2088 some commands have their output displayed in specially prepared
2089 buffers or in the echo area; some commands are instrumented to do
2090 gnugo.el-specific housekeeping).
2092 For example, for the command \"help\", Emacs visits the
2093 GTP command reference info page.
2095 NOTE: At this time, GTP command handling specification is still
2096 incomplete. Thus, some commands WILL confuse gnugo.el."
2097 (interactive "sCommand: ")
2098 (if (string= "" command)
2099 (message "(no command given)")
2100 (let* ((split (split-string command))
2101 (cmd (intern (car split)))
2102 (spec (get cmd :gnugo-gtp-command-spec))
2103 (full (plist-get spec :full)))
2105 (funcall full (cdr split))
2106 (message "Doing %s ..." command)
2107 (let* ((ans (gnugo--q command))
2108 (where (plist-get spec :output)))
2109 (if (string-match "unknown.command" ans)
2111 (cond ((functionp where) (funcall where ans))
2112 ((eq :discard where) (message ""))
2113 ((or (eq :message where)
2114 (not (string-match "\n" ans)))
2116 (t (switch-to-buffer "*gnugo command output*")
2119 (message "Doing %s ... done." command)))
2120 (let ((thunk (plist-get spec :post-thunk)))
2121 (when thunk (funcall thunk)))))))))
2123 ;;;---------------------------------------------------------------------------
2124 ;;; Major mode for interacting with a GNUGO subprocess
2126 (put 'gnugo-board-mode 'mode-class 'special)
2127 (defun gnugo-board-mode ()
2128 "Major mode for playing GNU Go.
2129 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2130 In this mode, keys do not self insert.
2132 \\{gnugo-board-mode-map}"
2133 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2134 (buffer-disable-undo) ; todo: undo undo undoing
2135 (kill-all-local-variables)
2136 (use-local-map gnugo-board-mode-map)
2137 (set (make-local-variable 'font-lock-defaults)
2138 '(gnugo-font-lock-keywords t))
2139 (setq major-mode 'gnugo-board-mode
2140 mode-name "GNUGO Board"
2142 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2143 (set (make-local-variable 'gnugo-state)
2144 (gnugo--mkht :size (1- 42)))
2145 (add-to-invisibility-spec :nogrid)
2146 (mapc (lambda (prop)
2147 (gnugo-put prop nil)) ; todo: separate display/game aspects;
2148 '(:game-over ; move latter to func `gnugo'
2155 :display-using-images
2159 (let ((name (if (string-match "[ ]" gnugo-program)
2160 (let ((p (substring gnugo-program 0 (match-beginning 0)))
2161 (o (substring gnugo-program (match-end 0)))
2162 (h (or (car gnugo-option-history) "")))
2163 (when (string-match "--mode" o)
2164 (user-error "Found \"--mode\" in `gnugo-program'"))
2165 (when (and o (cl-plusp (length o))
2166 h (cl-plusp (length o))
2167 (or (< (length h) (length o))
2168 (not (string= (substring h 0 (length o))
2170 (push (concat o " " h) gnugo-option-history))
2173 (args (read-string "GNU Go options: "
2174 (car gnugo-option-history)
2175 'gnugo-option-history))
2177 board-size user-color handicap komi minus-l infile)
2178 (loop for (var default opt &optional rx)
2179 in '((board-size 19 "--boardsize")
2180 (user-color "black" "--color" "\\(black\\|white\\)")
2181 (handicap 0 "--handicap")
2183 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2184 (infile nil "--infile" "[ ]*[^ ]+"))
2186 (or (when (string-match opt args)
2187 (let ((start (match-end 0)) s)
2188 (string-match (or rx "[0-9.]+") args start)
2189 (setq s (match-string 0 args))
2190 (if rx s (string-to-number s))))
2192 (gnugo-put :user-color user-color)
2193 (let ((proc-args (split-string args)))
2194 (gnugo-put :proc-args proc-args)
2195 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2196 (current-buffer) name
2197 "--mode" "gtp" "--quiet"
2199 (set-process-sentinel proc 'gnugo-sentinel)
2200 ;; Emacs is too protective sometimes, blech.
2201 (set-process-query-on-exit-flag proc nil)
2202 (when (or minus-l infile)
2204 in '((board-size "query_boardsize")
2206 (handicap "get_handicap"))
2207 do (set prop (string-to-number (gnugo-query q)))))
2208 (gnugo-put :diamond (substring (process-name proc) 5))
2209 (gnugo-put :gnugo-color (gnugo-other user-color))
2210 (gnugo-put :highlight-last-move-spec
2211 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2212 (gnugo-put :lparen-ov (make-overlay 1 1))
2213 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
2214 (overlay-put ov 'display ")")
2216 (let* ((coll (gnugo/sgf-create "(;FF[4]GM[1])" t))
2218 (gnugo-put :sgf-gametree tree)
2219 (gnugo-put :sgf-collection coll)
2220 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0)))
2221 (gnugo--SZ! board-size)
2222 (loop with gb = (gnugo--blackp (gnugo-other user-color))
2223 for (property value &optional mogrifyp) in
2225 (:DT ,(format-time-string "%Y-%m-%d"))
2226 (:RU ,(if (string-match "--chinese-rules" args)
2229 (:AP ("gnugo.el" . ,gnugo-version))
2231 (,(if gb :PW :PB) ,(user-full-name))
2232 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
2233 ,@(when (not (zerop handicap))
2235 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
2237 do (gnugo-note property value mogrifyp)))
2238 (gnugo-put :waiting-start (current-time))
2241 (run-hooks 'gnugo-board-mode-hook)
2244 ;;;---------------------------------------------------------------------------
2248 (defun gnugo (&optional new-game)
2249 "Run gnugo in a buffer, or resume a game in progress.
2250 Prefix arg means skip the game-in-progress check and start a new
2252 \\<gnugo-board-mode-map>
2253 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2255 You are queried for additional command-line options (Emacs supplies
2256 \"--mode gtp --quiet\" automatically). Here is a list of options
2257 that gnugo.el understands and handles specially:
2259 --boardsize num Set the board size to use (5--19)
2260 --color <color> Choose your color ('black' or 'white')
2261 --handicap <num> Set the number of handicap stones (0--9)
2263 If there is already a game in progress you may resume it instead of
2264 starting a new one. See `gnugo-board-mode' documentation for more info."
2266 (let* ((all (let (acc)
2267 (dolist (buf (buffer-list))
2268 (when (gnugo-board-buffer-p buf)
2269 (push (cons (buffer-name buf) buf) acc)))
2272 (if (and (not new-game)
2274 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2275 (if (= 1 n) "" "s"))))
2280 (let ((sel (completing-read "Which one? " all nil t)))
2281 (if (string= "" sel)
2283 (assoc sel all))))))
2284 ;; set up a new board
2286 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2287 (gnugo-goto-pos (format "A%d" half))
2288 (forward-char (* 2 (1- half)))
2289 (gnugo-put :last-user-bpos
2290 (gnugo-put :center-position
2291 (get-text-property (point) 'gnugo-position))))
2293 (gnugo-put :game-start-time (current-time))
2294 (let ((g (gnugo-get :gnugo-color))
2295 (n (or (gnugo--root-prop :HA) 0))
2296 (u (gnugo-get :user-color)))
2297 (gnugo-put :last-mover g)
2298 (when (or (and (gnugo--blackp u) (< 1 n))
2299 (and (gnugo--blackp g) (< n 2)))
2300 (gnugo-put :last-mover u)
2302 (gnugo-get-move g))))))
2304 ;;;---------------------------------------------------------------------------
2305 ;;; Load-time actions
2307 (mapc (lambda (pair)
2308 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2309 '(("q" . gnugo-frolic-quit)
2310 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2311 ("\C-b" . gnugo-frolic-backward-branch)
2312 ("\C-f" . gnugo-frolic-forward-branch)
2313 ("j" . gnugo-frolic-exchange-left)
2314 ("J" . gnugo-frolic-rotate-left)
2315 ("k" . gnugo-frolic-exchange-right)
2316 ("K" . gnugo-frolic-rotate-right)
2317 ("\C-m" . gnugo-frolic-set-as-main-line)
2318 ("\C-\M-p" . gnugo-frolic-prune-branch)
2319 ("o" . gnugo-frolic-return-to-origin)))
2321 (unless gnugo-board-mode-map
2322 (setq gnugo-board-mode-map (make-sparse-keymap))
2323 (suppress-keymap gnugo-board-mode-map)
2324 (mapc (lambda (pair)
2325 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2326 '(("?" . describe-mode)
2327 ("\C-m" . gnugo-move)
2330 ("R" . gnugo-resign)
2332 ("Q" . gnugo-leave-me-alone)
2333 ("U" . gnugo-fancy-undo)
2334 ("\M-u" . gnugo-undo-one-move)
2335 ("u" . gnugo-undo-two-moves)
2336 ("\C-?" . gnugo-undo-two-moves)
2338 ("\C-l" . gnugo-refresh)
2339 ("\M-_" . gnugo-boss-is-near)
2340 ("_" . gnugo-boss-is-near)
2341 ("h" . gnugo-move-history)
2342 ("L" . gnugo-frolic-in-the-leaves)
2343 ("i" . gnugo-toggle-image-display-command)
2344 ("w" . gnugo-worm-stones)
2345 ("W" . gnugo-worm-data)
2346 ("d" . gnugo-dragon-stones)
2347 ("D" . gnugo-dragon-data)
2348 ("t" . gnugo-toggle-dead-group)
2349 ("g" . gnugo-toggle-grid)
2350 ("!" . gnugo-estimate-score)
2351 (":" . gnugo-command)
2352 (";" . gnugo-command)
2353 ("=" . gnugo-describe-position)
2354 ("s" . gnugo-write-sgf-file)
2355 ("\C-x\C-s" . gnugo-write-sgf-file)
2356 ("\C-x\C-w" . gnugo-write-sgf-file)
2357 ("l" . gnugo-read-sgf-file)
2358 ("F" . gnugo-display-final-score)
2359 ("A" . gnugo-switch-to-another)
2361 ([(down-mouse-1)] . gnugo-mouse-move)
2362 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2363 ([(down-mouse-3)] . gnugo-mouse-pass)
2364 ;; delving into the curiosities
2365 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2367 (unless (get 'help :gnugo-gtp-command-spec)
2369 ((sget (x) (get x :gnugo-gtp-command-spec))
2370 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2371 (plist-put (sget cmd) prop val)))
2372 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2375 (jam cmd (car ls) (cadr ls))
2376 (setq ls (cddr ls)))))))
2377 (cl-macrolet ((deffull (who &body body)
2378 (declare (indent 1))
2379 `(defgtp ',who :full (lambda (sel)
2383 (info "(gnugo)GTP command reference")
2384 (when sel (setq sel (intern (car sel))))
2385 (let (buffer-read-only pad cur spec output found)
2387 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2388 (goto-char (point-min))
2390 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2393 (setq pad (make-string (- (match-beginning 1)
2394 (match-beginning 0))
2398 (get (setq cur (intern (match-string 1)))
2399 :gnugo-gtp-command-spec))
2401 (note "handles this command completely"))
2402 (when (setq output (plist-get spec :output))
2403 (if (functionp output)
2404 (note "handles the output specially")
2406 (:discard (note "discards the output"))
2407 (:message (note "displays the output in the echo area")))))
2409 (setq found (match-beginning 0))))))
2410 (cond (found (goto-char found))
2412 (t (message "(no such command: %s)" sel)))))
2414 (deffull final_score
2415 (gnugo-display-final-score))
2421 :post-thunk (lambda ()
2422 (gnugo--unclose-game)
2423 (gnugo-put :last-mover nil)
2425 (gnugo--SZ! (string-to-number
2427 "query_boardsize")))
2431 (gnugo-read-sgf-file (car sel)))
2433 (deffull (undo gg-undo)
2437 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2438 (t (car sel)))))))))
2443 ;;;---------------------------------------------------------------------------
2444 ;;; The remainder of this file defines a simplified SGF-handling library.
2445 ;;; When/if it should start to attain generality, it should be split off into
2446 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2447 ;;; "gnugo/" prefix.
2449 (defconst gnugo/sgf-*r4-properties*
2450 '((AB "Add Black" setup list stone)
2451 (AE "Add Empty" game list point)
2452 (AN "Annotation" game simpletext)
2453 (AP "Application" root (simpletext . simpletext))
2454 (AR "Arrow" - list (point . point))
2455 (AS "Who adds stones" - simpletext) ; (LOA)
2456 (AW "Add White" setup list stone)
2457 (B "Black" move move)
2458 (BL "Black time left" move real)
2459 (BM "Bad move" move double)
2460 (BR "Black rank" game simpletext)
2461 (BT "Black team" game simpletext)
2462 (C "Comment" - text)
2463 (CA "Charset" root simpletext)
2464 (CP "Copyright" game simpletext)
2465 (CR "Circle" - list point)
2466 (DD "Dim points" - elist point) ; (inherit)
2467 (DM "Even position" - double)
2468 (DO "Doubtful" move none)
2469 (DT "Date" game simpletext)
2470 (EV "Event" game simpletext)
2471 (FF "Fileformat" root [number (1 . 4)])
2472 (FG "Figure" - (or none (number . simpletext)))
2473 (GB "Good for Black" - double)
2474 (GC "Game comment" game text)
2475 (GM "Game" root [number (1 . 20)])
2476 (GN "Game name" game simpletext)
2477 (GW "Good for White" - double)
2478 (HA "Handicap" game number) ; (Go)
2479 (HO "Hotspot" - double)
2480 (IP "Initial pos." game simpletext) ; (LOA)
2481 (IT "Interesting" move none)
2482 (IY "Invert Y-axis" game simpletext) ; (LOA)
2483 (KM "Komi" game real) ; (Go)
2485 (LB "Label" - list (point . simpletext))
2486 (LN "Line" - list (point . point))
2487 (MA "Mark" - list point)
2488 (MN "set move number" move number)
2489 (N "Nodename" - simpletext)
2490 (OB "OtStones Black" move number)
2491 (ON "Opening" game text)
2492 (OT "Overtime" game simpletext)
2493 (OW "OtStones White" move number)
2494 (PB "Player Black" game simpletext)
2495 (PC "Place" game simpletext)
2496 (PL "Player to play" setup color)
2497 (PM "Print move mode" - number) ; (inherit)
2498 (PW "Player White" game simpletext)
2499 (RE "Result" game simpletext)
2500 (RO "Round" game simpletext)
2501 (RU "Rules" game simpletext)
2502 (SE "Markup" - point) ; (LOA)
2503 (SL "Selected" - list point)
2504 (SO "Source" game simpletext)
2505 (SQ "Square" - list point)
2506 (ST "Style" root [number (0 . 3)])
2507 (SU "Setup type" game simpletext) ; (LOA)
2508 (SZ "Size" root (or number (number . number)))
2509 (TB "Territory Black" - elist point) ; (Go)
2510 (TE "Tesuji" move double)
2511 (TM "Timelimit" game real)
2512 (TR "Triangle" - list point)
2513 (TW "Territory White" - elist point) ; (Go)
2514 (UC "Unclear pos" - double)
2515 (US "User" game simpletext)
2517 (VW "View" - elist point) ; (inherit)
2518 (W "White" move move)
2519 (WL "White time left" move real)
2520 (WR "White rank" game simpletext)
2521 (WT "White team" game simpletext)
2522 (LT "Lose on time" setup simpletext))
2523 ;; r4-specific notes
2524 ;; - changed: DT FG LB RE RU SZ
2525 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2526 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2528 (defun gnugo/sgf-create (file-or-data &optional data-p)
2529 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2530 FILE-OR-DATA is a file name or SGF[4] data.
2531 Optional arg DATA-P non-nil means FILE-OR-DATA is
2532 a string containing SGF[4] data.
2533 A collection is a list of gametrees, each a vector of four elements:
2535 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2536 have a move number of the previous \"move\" node (or zero)
2538 KIDS -- `eq' hash: node to node list (branch points only)
2540 ENDS -- a vector of node lists, with shared tails
2541 (last element of all the lists is the root node)
2543 ROOT -- the root node"
2544 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2545 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2546 (put 'gnugo/sgf-*r4-properties* :keywords
2547 (mapcar (lambda (full)
2549 (intern (format ":%s" (car full)))))
2550 gnugo/sgf-*r4-properties*))))
2551 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2552 (put 'gnugo/sgf-*r4-properties* :specs
2553 (mapcar (lambda (full)
2554 (cons (car full) (cdddr full)))
2555 gnugo/sgf-*r4-properties*))))
2558 ((sw () (skip-chars-forward " \t\n"))
2559 (x (end) (let ((beg (point))
2561 (:end (lambda (char) (= ?\] char)))
2562 (:mid (lambda (char) (= ?\: char)))
2563 (t (lambda (char) (or (= ?\: char)
2566 (while (not (funcall endp (setq c (following-char))))
2572 ((looking-at "\\s-+")
2573 (delete-region (point) (match-end 0))
2575 (t (forward-char 1))))
2576 (buffer-substring-no-properties beg (point))))
2577 (one (type end) (let ((s (progn
2582 ;; blech, begone bu"tt"-ugly blatherings
2583 ;; (but bide brobdingnagian boards)...
2584 (if (and (string= "tt" s)
2589 ((simpletext color) s)
2590 ((number real double) (string-to-number s))
2593 (t (error "Unhandled type: %S" type)))))
2594 (val (spec) (cond ((symbolp spec)
2597 ;; todo: check range here.
2598 (one (aref spec 0) :end))
2599 ((eq 'or (car spec))
2600 (let ((v (one (cadr spec) t)))
2601 (if (= ?\] (following-char))
2604 ;; todo: this assumes `spec' has the form
2605 ;; (or foo (foo . bar))
2606 ;; i.e., foo is not rescanned. e.g., `SZ'.
2607 ;; probably this assumption is consistent
2608 ;; w/ the SGF authors' desire to make the
2609 ;; parsing easy, but you never know...
2610 (cons v (one (cdaddr spec) :end)))))
2611 (t (cons (one (car spec) :mid)
2612 (one (cdr spec) :end)))))
2613 (short (who) (when (eobp)
2614 (error "Unexpected EOF while reading %s" who)))
2615 (atvalp () (= ?\[ (following-char)))
2616 (PROP () (let (name spec ltype)
2617 (sw) (short 'property)
2618 (when (looking-at "[A-Z]")
2619 (setq name (read (current-buffer))
2620 spec (cdr (assq name specs)))
2623 (cdr (assq name keywords))
2624 (prog1 (if (= 1 (length spec))
2626 (unless (memq (setq ltype (car spec))
2628 (error "Bad spec: %S" spec))
2629 (if (and (eq 'elist ltype) (sw)
2632 (let ((type (cadr spec))
2634 (while (and (sw) (atvalp)
2635 (setq mo (val type)))
2640 (forward-char 1))))))
2641 (morep () (and (sw) (not (eobp))))
2642 (seek (c) (and (morep) (= c (following-char))))
2643 (seek-into (c) (when (seek c)
2646 (NODE () (when (seek-into ?\;)
2648 while (setq prop (PROP))
2650 (when (eq :SZ (car prop))
2651 (setq SZ (cdr prop)))
2653 (TREE (parent mnum kids)
2660 (puthash node (+ (if (gnugo--move-prop node)
2663 (gethash prev mnum 0))
2666 (when (listp (gethash prev kids t))
2667 (push node (gethash prev kids)))
2671 (if (not (seek ?\())
2676 (puthash node (list) kids)
2677 (loop while (seek ?\()
2678 append (TREE ls mnum kids)))
2682 (insert-file-contents file-or-data)
2683 (insert file-or-data)
2684 (goto-char (point-min)))
2686 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2687 (kids (gnugo--mkht))
2688 (ends (TREE nil mnum kids))
2689 (root (car (last (car ends)))))
2692 (apply 'vector ends)
2695 (defun gnugo/sgf-hang-from-root (tree)
2696 (let ((ht (gnugo--mkht))
2697 (leaves (append tree nil)))
2701 with rh ; rectified history
2702 with bp ; branch point
2704 until (setq bp (gethash node ht))
2706 (push node rh) ; good for now: ½τ
2710 ;; first run: main line
2712 ;; subsequent runs: grafts (value discarded)
2714 ;; Maintain order of ‘leaves’.
2715 (let ((was (cdr bp)))
2716 (if (gnugo--nodep (car was))
2720 (setq tree (hang (pop leaves)))
2721 (mapc #'hang leaves)
2724 (defun gnugo/sgf-write-file (collection filename)
2725 ;; take responsibility for our actions
2726 (let ((me (cons "gnugo.el" gnugo-version)))
2727 (dolist (tree collection)
2728 (gnugo--set-root-prop :AP me tree)))
2730 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2731 (specs (mapcar (lambda (full)
2732 (cons (intern (format ":%s" (car full)))
2734 gnugo/sgf-*r4-properties*))
2736 ;; todo: escape special chars for `text' and `simpletext'.
2738 ((>>one (v) (insert (format "[%s]" v)))
2739 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2740 (>>nl () (cond ((memq name aft-newline-appreciated)
2742 ((< 60 (current-column))
2750 (insert (substring (symbol-name name) 1))
2753 (setq spec (cdr (assq name specs)))
2757 (let ((>> (if (consp (cadr spec))
2760 (dolist (little-v v)
2762 (funcall >> little-v)
2769 (loop initially (insert ";")
2773 (unless (zerop (current-column))
2777 (funcall (if (gnugo--nodep x)
2783 (dolist (tree collection)
2784 (>>tree (gnugo/sgf-hang-from-root tree)))
2786 (write-file filename)))))
2788 ;;; gnugo.el ends here