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 ;;;---------------------------------------------------------------------------
176 ;;; Support functions
178 (defsubst gnugo--mkht (&rest etc)
179 (apply 'make-hash-table :test 'eq etc))
181 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
182 (compare-strings s1 beg1 nil s2 beg2 nil))
184 (defun gnugo-put (key value)
185 "Associate move/game/board-specific property KEY with VALUE.
187 There are many properties, each named by a keyword, that record and control
188 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
189 of properties, stored in the hash table `gnugo-state'. Here we document
190 some of the more stable properties. You may wish to use them as part of
191 a `gnugo-post-move-hook' function, for example. Be careful to preserve
192 the current buffer as `gnugo-state' is made into a buffer-local variable.
193 NOTE: In the following, \"see foo\" actually means \"see foo source or
194 you may never really understand to any degree of personal satisfaction\".
196 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
198 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
200 :game-over -- nil until game over at which time its value is set to
201 the alist `((live GROUP ...) (dead GROUP ...))'
203 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
204 a simple list of one or more gametrees, updated in
205 conjunction w/ :sgf-gametree and :monkey
207 :sgf-gametree -- one of the gametrees in :sgf-collection
209 :monkey -- vector of two elements:
210 MEM, a pointer to one of the branches in the gametree;
211 BIDX, the index of the \"current branch\"
213 :gnugo-color -- either \"black\" or \"white\"
217 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
220 :black-captures -- these are strings since gnugo.el doesn't do anything
221 :white-captures w/ the information besides display it in the mode line;
222 gory details in functions `gnugo-propertize-board-buffer'
223 and `gnugo-merge-showboard-results' (almost more effort
224 than they are worth!)
226 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
227 `gnugo-toggle-image-display' and `gnugo-refresh',
228 as well as gnugo-xpms.el (available elsewhere)
230 :all-yy -- list of 46 keywords used as the `category' text property
231 (so that their plists, typically w/ property `display' or
232 `do-not-display') are consulted by the Emacs display engine;
233 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
234 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
236 :lparen-ov -- overlays shuffled about to indicate the last move; only
237 :rparen-ov one is used when displaying using images
239 :last-user-bpos -- board position; keep the hapless human happy
241 As things stabilize probably more info will be added to this docstring."
243 (puthash key value gnugo-state))
245 (defun gnugo-get (key)
246 "Return the move/game/board-specific value for KEY.
248 (gethash key gnugo-state))
250 (defsubst gnugo--tree-mnum (tree)
253 (defsubst gnugo--tree-ends (tree)
256 (defsubst gnugo--set-tree-ends (tree ends)
258 ;; hmm, probably unnecessary
261 (defun gnugo-describe-internal-properties ()
262 "Pretty-print `gnugo-state' properties in another buffer.
263 Handle the big, slow-to-render, and/or uninteresting ones specially."
265 (let ((buf (current-buffer))
266 (d (gnugo-get :diamond))
268 (loop for key being the hash-keys of gnugo-state
269 using (hash-values val)
273 (format "hash: %X (%d images)"
279 (list (hash-table-count
280 (gnugo--tree-mnum val))
283 (gnugo--tree-ends val)))
285 (let ((mem (aref val 0)))
290 (switch-to-buffer (get-buffer-create
291 (format "%s*GNUGO Board Properties*"
292 (gnugo-get :diamond))))
295 (setq truncate-lines t)
299 (goto-char (point-min))
300 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
304 (while (re-search-forward rx (point-max) t)
305 (let ((pos (get-text-property (string-to-number (match-string 1))
306 'gnugo-position buf)))
307 (delete-region (+ 2 (match-beginning 0)) (point))
308 (insert (format " %S" pos))))))
309 (message "%d properties" (length acc))))
311 (defun gnugo-board-buffer-p (&optional buffer)
312 "Return non-nil if BUFFER is a GNUGO Board buffer."
313 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
315 (defun gnugo-board-user-play-ok-p (&optional buffer)
316 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
317 (with-current-buffer (or buffer (current-buffer))
318 (and gnugo-state (not (gnugo-get :waitingp)))))
320 (defsubst gnugo--blackp (string)
321 (string= "black" string))
323 (defun gnugo-other (color)
324 (if (gnugo--blackp color) "white" "black"))
326 (defun gnugo-gate (&optional in-progress-p)
327 (unless (gnugo-board-buffer-p)
328 (user-error "Wrong buffer -- try M-x gnugo"))
329 (unless (gnugo-get :proc)
330 (user-error "No \"gnugo\" process!"))
331 (when (gnugo-get :waitingp)
332 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
333 (gnugo-get :user-color)))
334 (when (and (gnugo-get :game-over) in-progress-p)
335 (user-error "Sorry, game over")))
337 (defun gnugo-sentinel (proc string)
338 (let ((status (process-status proc)))
339 (when (memq status '(exit signal))
340 (let ((buf (process-buffer proc)))
341 (when (buffer-live-p buf)
342 (with-current-buffer buf
343 (setq mode-line-process
345 (propertize (car (split-string string))
346 'face 'font-lock-warning-face)
348 (when (eq proc (gnugo-get :proc))
349 (gnugo-put :proc nil))))))))
351 (defun gnugo--begin-exchange (proc filter line)
352 (declare (indent 2)) ; good time, for a rime
353 ; nice style, for a wile...
354 (set-process-filter proc filter)
355 (process-send-string proc line)
356 (process-send-string proc "\n"))
358 (defun gnugo--q (fmt &rest args)
359 "Send formatted command \"FMT ARGS...\"; wait for / return response.
360 The response is a string whose first two characters indicate the
361 status of the command. See also `gnugo-query'."
362 (when (gnugo-get :waitingp)
363 (user-error "Sorry, still waiting for %s to play"
364 (gnugo-get :gnugo-color)))
365 (let ((proc (gnugo-get :proc)))
366 (process-put proc :incomplete t)
367 (process-put proc :srs "") ; synchronous return stash
368 (gnugo--begin-exchange
369 proc (lambda (proc string)
370 (let ((full (concat (process-get proc :srs)
372 (process-put proc :srs full)
373 (unless (numberp (gnugo--compare-strings
374 full (max 0 (- (length full)
377 (process-put proc :incomplete nil))))
380 (apply #'format fmt args)))
381 (while (process-get proc :incomplete)
382 (accept-process-output proc 30))
383 (prog1 (substring (process-get proc :srs) 0 -2)
384 (process-put proc :srs ""))))
386 (defun gnugo-query (message-format &rest args)
387 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
388 Return a string that omits the first two characters (corresponding
389 to the status indicator in the Go Text Protocol). Use this function
390 when you are sure the command cannot fail."
391 (substring (apply 'gnugo--q message-format args)
394 (defun gnugo-lsquery (message-format &rest args)
395 (split-string (apply 'gnugo-query message-format args)))
397 (defun gnugo--root-node (&optional tree)
398 (aref (or tree (gnugo-get :sgf-gametree))
401 (defsubst gnugo--root-prop (prop &optional tree)
402 (cdr (assq prop (gnugo--root-node tree))))
404 (defun gnugo--set-root-prop (prop value &optional tree)
405 (let* ((root (gnugo--root-node tree))
406 (cur (assq prop root)))
409 (push (cons prop value)
410 (cdr (last root))))))
412 (defun gnugo-goto-pos (pos)
413 "Move point to board position POS, a letter-number string."
414 (goto-char (point-min))
415 (forward-line (- (1+ (gnugo-get :SZ))
416 (string-to-number (substring pos 1))))
418 (forward-char (+ (if (= 32 (following-char)) 1 2)
419 (* 2 (- (let ((letter (aref pos 0)))
425 (defun gnugo-f (frag)
426 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
428 (defun gnugo-yang (c)
429 (cdr (assq c '((?+ . hoshi)
431 (?X . (bmoku . bpmoku))
432 (?O . (wmoku . wpmoku))))))
434 (defun gnugo-yy (yin yang &optional momentaryp)
435 (gnugo-f (format "%d-%s"
436 yin (cond ((and (consp yang) momentaryp) (cdr yang))
437 ((consp yang) (car yang))
440 (defun gnugo-toggle-image-display ()
441 (unless (and (fboundp 'display-images-p) (display-images-p))
442 (user-error "Display does not support images, sorry"))
443 (require 'gnugo-xpms)
444 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
445 (user-error "Could not load `gnugo-xpms', sorry"))
446 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
447 (unless (eq fresh (gnugo-get :xpms))
448 (gnugo-put :xpms fresh)
449 (gnugo-put :all-yy nil)))
450 (let* ((new (not (gnugo-get :display-using-images)))
451 (act (if new 'display 'do-not-display)))
453 (setcar (symbol-plist yy) act))
454 (or (gnugo-get :all-yy)
456 (prog1 (mapcar (lambda (ent)
458 (yy (gnugo-yy (cdr k) (car k))))
459 (setplist yy `(not-yet ,(cdr ent)))
462 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
464 (gnugo-put :w-imul (car imul))
465 (gnugo-put :h-imul (cdr imul)))))))
466 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
467 (gnugo-put :highlight-last-move-spec
470 (get (gnugo-yy (get-text-property p 'gnugo-yin)
471 (get-text-property p 'gnugo-yang)
475 (gnugo-get :default-highlight-last-move-spec)))
476 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
477 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
478 (mapc 'delete-overlay (cdar group))
479 (setcdr (car group) nil))
480 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
481 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
482 (gnugo-put :display-using-images new)))
484 (defun gnugo-toggle-grid ()
485 "Turn the grid around the board on or off."
487 (funcall (if (memq :nogrid buffer-invisibility-spec)
488 'remove-from-invisibility-spec
489 'add-to-invisibility-spec)
491 (save-excursion (gnugo-refresh)))
493 (defun gnugo-propertize-board-buffer ()
495 (insert (substring (gnugo--q "showboard") 3))
496 (let* ((grid-props (list 'invisible :nogrid
497 'font-lock-face gnugo-grid-face))
498 (%gpad (gnugo-f 'gpad))
499 (%gspc (gnugo-f 'gspc))
500 (%lpad (gnugo-f 'lpad))
501 (%rpad (gnugo-f 'rpad))
502 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
503 (size (gnugo-get :SZ))
504 (size-string (number-to-string size)))
505 (goto-char (point-min))
506 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
507 (skip-chars-forward " ")
508 (put-text-property (1- (point)) (point) 'category %gpad)
509 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
511 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
512 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
513 (let* ((row (match-string-no-properties 1))
515 (other-edge (+ edge (* 2 size) -1))
516 (right-empty (+ other-edge (length row) 1))
517 (top-p (string= size-string row))
518 (bot-p (string= "1" row)))
519 (let* ((nL (- edge 1 (length size-string)))
521 (ov (make-overlay nL nR (current-buffer) t)))
522 (add-text-properties nL nR grid-props)
523 ;; We redundantly set `invisible' in the overlay to workaround
524 ;; a display bug whereby text *following* the overlaid text is
525 ;; displayed with the face of the overlaid text, but only when
526 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
527 ;; This has something to do w/ the bletcherous `before-string'.
528 (overlay-put ov 'invisible :nogrid)
529 (overlay-put ov 'category %lpad))
530 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
532 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
533 (truncate (- p edge) 2))
535 (yin (let ((A-p (= edge p))
536 (Z-p (= (1- other-edge) p)))
537 (cond ((and top-p A-p) 1)
546 (yang (gnugo-yang (char-after p))))
547 (add-text-properties p (1+ p)
557 (gnugo-position gnugo-yin))))
558 (unless (= (1- other-edge) p)
559 (add-text-properties (1+ p) (+ 2 p) ispc-props)
560 (put-text-property p (+ 2 p) 'intangible ival)))
561 (add-text-properties (1+ other-edge) right-empty grid-props)
562 (goto-char right-empty)
563 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
564 (let ((prop (if (string= "WH" (match-string 1))
567 (beg (match-beginning 2))
569 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
570 (gnugo-put prop (match-string-no-properties 2))))
572 (put-text-property right-empty (point) 'category %rpad)
574 (add-text-properties (1- (point)) (point-max) grid-props)
575 (skip-chars-forward " ")
576 (put-text-property (1- (point)) (point) 'category %gpad)
577 (put-text-property (point) (progn (end-of-line) (point))
580 (defun gnugo-merge-showboard-results ()
581 (let ((aft (substring (gnugo--q "showboard") 3))
582 (adj 1) ; string to buffer position adjustment
584 (sync "[0-9]* stones$")
585 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
586 ;; restrictive a condition that fails in the case of:
589 ;; ... WHITE has captured 1 stones
592 ;; ... WHITE has captured 14 stones
595 ;; where the after count has more digits than the before count,
596 ;; but shares the same leading digits. In this case, the result
597 ;; of `compare-strings' points to the SPC following the before
598 ;; count (indicated by caret in this example).
600 (bef (buffer-substring-no-properties (point-min) (point-max)))
601 (bef-start 0) (bef-idx 0)
602 (aft-start 0) (aft-idx 0)
603 aft-sync-backtrack mis inc cut new very-strange)
604 (while (numberp (setq mis (gnugo--compare-strings
607 (setq aft-sync-backtrack nil
608 inc (if (cl-minusp mis)
611 bef-idx (+ bef-start inc)
612 aft-idx (+ aft-start inc)
613 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
616 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
617 (let ((peek (1- aft-idx)))
618 (while (not (= 32 (aref aft peek)))
619 (setq peek (1- peek)))
620 (setq aft-sync-backtrack (1+ peek))))
624 (if aft-sync-backtrack
625 (- aft-sync-backtrack aft-idx)
628 (if aft-sync-backtrack
629 (let* ((asb aft-sync-backtrack)
630 (l-p (get-text-property cut :gnugo-cf))
633 (keep (text-properties-at cut)))
634 (setq new (substring aft asb (string-match " " aft asb)))
635 (plist-put keep :gnugo-cf (cons (length new) capprop))
636 (gnugo-put capprop new)
637 (delete-char old-len)
638 (insert (apply 'propertize new keep))
639 (incf adj (- (length new) old-len)))
640 (setq new (aref aft aft-idx))
641 (insert-and-inherit (char-to-string new))
642 (let ((yin (get-text-property cut 'gnugo-yin))
643 (yang (gnugo-yang new)))
644 (add-text-properties cut (1+ cut)
648 ,(gnugo-yy yin yang))))
650 ;; do this last to avoid complications w/ font lock
651 ;; (this also means we cannot include `intangible' in `front-sticky')
652 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
653 (put-text-property cut (1+ cut) 'intangible very-strange))))))
655 (defsubst gnugo--move-prop (node)
659 (defun gnugo--as-pos-func (size)
660 (lexical-let ((size size))
665 (let ((col (aref cc 0)))
667 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
668 (- size (- (aref cc 1) ?a))))))))
670 (defun gnugo-move-history (&optional rsel)
671 "Determine and return the game's move history.
672 Optional arg RSEL controls side effects and return value.
673 If nil, display the history in the echo area as \"(N moves)\"
674 followed by the space-separated list of moves. When called
675 interactively with a prefix arg (i.e., RSEL is `(4)'), display
676 similarly, but suffix with the mover (either \":B\" or \":W\").
677 If RSEL is the symbol `car' return the most-recent move; if
678 `cadr', the next-to-most-recent move; if `count' the number of
679 moves thus far; if `two' the last two moves as a list, oldest last.
681 For all other values of RSEL, do nothing and return nil."
683 (let* ((monkey (gnugo-get :monkey))
684 (mem (aref monkey 0))
685 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
689 ((as-pos-maybe (x) (if (string= "resign" x)
692 (next (byp) (when (setq node (pop mem)
693 mprop (gnugo--move-prop node))
694 (setq move (as-pos-maybe (cdr mprop)))
696 (format "%s%s" move (car mprop))
700 (tell () (message "(%d moves) %s"
702 (mapconcat 'identity (nreverse acc) " ")))
703 (finish (byp) (while mem (next byp)) (tell)))
708 (`cadr (nn) (car (nn)))
709 (`count (gethash (car mem) (gnugo--tree-mnum
710 (gnugo-get :sgf-gametree))))
714 (defun gnugo-frolic-in-the-leaves ()
715 "Display the game tree in a *GNUGO Frolic* buffer.
716 This looks something like:
719 2 W -- K10 K10 K10 K10
738 with 0, 1, ... N (in this case N is 3) in the header line
739 to indicate the branches. Branch 0 is the \"main line\".
740 Point (* in this example) indicates the current position,
741 and moves not actually on the game tree (e.g., E7, branch 3)
742 are dimmed. The buffer is in View minor mode."
744 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
746 ;; todo: use defface once we finally succumb to ‘customize’
747 (dimmed-node-face (list :inherit 'default
748 :foreground "gray50"))
749 (tree (gnugo-get :sgf-gametree))
750 (ends (gnugo--tree-ends tree))
751 (mnum (gnugo--tree-mnum tree))
754 (width (length ends))
755 (lanes (number-sequence 0 (1- width)))
756 (monkey (gnugo-get :monkey))
757 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
758 (at (car (aref monkey 0)))
759 (bidx (aref monkey 1))
760 (max-move-num (loop for bx in lanes
761 maximize (gethash (car (aref ends bx))
763 (eert (make-vector width nil))
769 (propertize s 'face face))
770 (fsi (fmt &rest args)
771 (insert (apply 'format fmt args))))
773 (let ((monkey-on-main-line (zerop bidx))
775 ;; monkey knows a lot
777 for node in (aref monkey 0)
778 do (puthash node bidx seen)
779 if (gnugo--move-prop node)
782 (unless monkey-on-main-line
783 (setq fixup (apply 'vector acc)))
784 (aset eert bidx acc)))
785 ;; but monkey does not know everything
789 with (bef acc node fork cur)
790 for ls on (aref ends bx)
791 do (if (setq node (car ls)
795 (push other (gethash node soil))))
796 (let ((move-num (gethash node mnum)))
798 (assert (and (not monkey-on-main-line)
801 while (< bx (on old))
802 do (puthash old bx seen))
803 (when (< move-num (length fixup))
804 (link (aref fixup move-num))))
806 (when (setq bef (copy-sequence (aref eert fork)))
807 (setcdr (nthcdr (1- move-num) bef)
809 (aset eert bx (or bef acc))
812 (puthash node bx seen)
813 (when (gnugo--move-prop node)
817 (switch-to-buffer buf)
820 (buffer-disable-undo)
822 (setq header-line-format
823 (concat (make-string 11 ?\s)
824 (mapconcat (lambda (n)
830 from 1 upto max-move-num
834 initially (fsi "%3d %s -- "
835 n (aref ["W" "B"] (logand 1 n)))
837 do (let* ((node (pop (aref eert bx)))
840 (s (cond ((not node) "")
841 ((not (setq move (gnugo--move-prop node))) "-")
842 (t (funcall as-pos (cdr move))))))
843 ;; todo: move this into "breathe in"
844 (when (and ok (setq br (gethash node soil)))
845 (setq br (delq bx (mapcar #'on br)))
846 (when (and br (car (aref eert bx)))
848 ;; do not point w/ a fist
850 (push (cons bx (sort br '<))
853 (cond ((and (eq at node)
856 (setq finish (point)))
857 (emph s (list :inherit 'default
858 :foreground (frame-parameter
859 nil 'cursor-color))))
861 (emph s dimmed-node-face))
864 (when (progn (newline)
865 (setq forks (nreverse forks)))
866 (let* ((margin (make-string 11 ?\s))
867 (count (length forks))
868 (heads (mapcar #'car forks))
869 (tails (mapcar #'cdr forks)))
871 ((spaced (lanes func)
872 (mapconcat func lanes " "))
873 ;; live to play ~ ~ ()
874 ;; play to learn (+) (-) . o O
875 ;; learn to live --ttn .M. _____U
876 (dashed (lanes func) ;;; _____ ^^^^
877 (mapconcat func lanes "-----"))
879 (spaced lanes (lambda (bx)
883 (pad-unless (condition)
894 do (let* ((one (car ls))
897 (mapcar 'car (cdr ls))
899 (apply 'append (mapcar 'cdr bef))))
902 (end (car (last ord))))
904 ((also (b e) (cnxn (number-sequence b e)
909 (pad-unless (zerop beg))
910 (dashed (number-sequence beg end)
912 (cond ((memq bx ord) "+")
915 (pad-unless (>= end width))
916 (also (1+ end) (1- width))
919 (edge (apply 'append tails))
920 (aa2u (line-beginning-position
921 (- (1+ (length forks))))
925 (recenter (- (count-lines (line-beginning-position) (point-max)))))
928 (defun gnugo-boss-is-near ()
929 "Do `bury-buffer' until the current one is not a GNU Board."
931 (while (gnugo-board-buffer-p)
934 (defsubst gnugo--passp (string)
935 (string= "PASS" string))
937 (defsubst gnugo--no-regrets (monkey ends)
938 (eq (aref ends (aref monkey 1))
941 (defun gnugo-note (property value &optional mogrifyp)
943 (let ((sz (gnugo-get :SZ)))
945 ((mog (pos) (if (gnugo--passp pos)
947 (let* ((col (aref pos 0))
948 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
949 (two (+ ?a (- sz (string-to-number
950 (substring pos 1))))))
951 (format "%c%c" one two)))))
952 (setq value (if (consp value)
955 (let* ((pair (cons property value))
957 (monkey (gnugo-get :monkey))
958 (mem (aref monkey 0))
960 (if (memq property '(:B :W))
961 (let* ((tree (gnugo-get :sgf-gametree))
962 (ends (gnugo--tree-ends tree))
963 (mnum (gnugo--tree-mnum tree))
964 (bidx (aref monkey 1)))
965 ;; Detect déjà-vu. That is, when placing "A", avoid:
971 ;; (such "variations" do not actually vary!) in favor of:
977 with count = (length ends)
980 ;; Start with latest / highest likelihood for hit.
981 ;; todo: prune unfeasible candidates
982 from (if (gnugo--no-regrets monkey ends)
986 if (setq bx (mod (+ bidx i) count)
988 ;; todo: early termination based on move number
989 (loop for m on (aref ends bx)
992 (when (equal pair (assoc property (car m)))
1000 (rotatef (aref ends bidx)
1002 (setq mem previous))
1006 (unless (gnugo--no-regrets monkey ends)
1007 ;; <grumble grumble> SGF sez "move" node in the root
1008 ;; position of a (sub-)gametree is "bad style". :-/
1009 (gnugo--set-tree-ends
1010 tree (let ((ls (append ends nil)))
1011 ;; copy old to the right of new
1012 (push mem (nthcdr bidx ls))
1013 (apply 'vector ls))))
1014 (puthash fruit (1+ (gethash tip mnum)) mnum)
1016 (aset ends bidx mem)))
1017 (setf (aref monkey 0) mem))
1018 (setcdr (last tip) fruit))))
1020 (defun gnugo-close-game (end-time resign)
1021 (gnugo-put :game-end-time end-time)
1022 (let ((now (or end-time (current-time))))
1023 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1025 (gnugo-put :game-over
1026 (if (or (eq t resign)
1027 (and (stringp resign)
1028 (string-match "[BW][+][Rr]esign" resign)))
1030 ((ls (color) (mapcar
1035 (gnugo-query "worm_stones %s" color)
1037 (let ((live (append (ls "black") (ls "white"))))
1040 (let ((dd (gnugo-query "dragon_data"))
1041 (start 0) mem color ent live dead)
1042 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1044 (setq mem (match-string 1 dd)
1045 color (match-string 2 dd)
1047 ent (cons (list color)
1048 (sort (gnugo-lsquery "dragon_stones %s" mem)
1050 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1052 (if (match-string 2 dd)
1055 (setq start (match-end 0)))
1059 (defun gnugo--unclose-game ()
1060 (dolist (prop '(:game-over ; all those in -close-game
1063 (gnugo-put prop nil))
1064 (let* ((root (gnugo--root-node))
1065 (cur (assq :RE root)))
1067 (assert (not (eq cur (car root))) nil
1068 ":RE at head of root node: %S"
1072 (defun gnugo-push-move (userp move)
1073 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
1074 (start (gnugo-get :waiting-start))
1075 (now (current-time))
1076 (resignp (string= "resign" move))
1077 (passp (gnugo--passp move))
1078 (head (gnugo-move-history 'car))
1079 (onep (and head (gnugo--passp head)))
1080 (donep (or resignp (and onep passp))))
1082 (gnugo-merge-showboard-results))
1083 (gnugo-put :last-mover color)
1085 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1086 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
1088 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1090 (gnugo-close-game now resignp))
1091 (gnugo-put :waiting-start (and (not donep) now))
1094 (defun gnugo-venerate (yin yang)
1095 (let* ((fg-yy (gnugo-yy yin yang))
1096 (fg-disp (or (get fg-yy 'display)
1097 (get fg-yy 'do-not-display)))
1098 (fg-data (plist-get (cdr fg-disp) :data))
1099 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1100 (bg-disp (or (get bg-yy 'display)
1101 (get bg-yy 'do-not-display)))
1102 (bg-data (plist-get (cdr bg-disp) :data))
1106 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1107 (setq start (match-end 0))
1108 (string-to-number (match-string 1 s)))))
1109 (while (and (not (cl-minusp ncolors))
1110 (string-match ",\n" s start))
1111 (setq start (match-end 0)
1112 ncolors (1- ncolors)))
1113 (string-match "\"" s start)
1115 (new (copy-sequence fg-data))
1116 (lx (length fg-data))
1117 (sx (funcall bop fg-data))
1118 (sb (funcall bop bg-data))
1119 (color-key (aref new sx))) ; blech, heuristic
1121 (when (and (not (= color-key (aref new sx)))
1122 (cl-plusp (random 4)))
1123 (aset new sx (aref bg-data sb)))
1126 (create-image new 'xpm t :ascent 'center)))
1128 (defun gnugo-refresh (&optional nocache)
1129 "Update GNUGO Board buffer display.
1130 While a game is in progress, parenthesize the last-played stone (no parens
1131 for pass). If the buffer is currently displayed in the selected window,
1132 recenter the board (presuming there is extra space in the window). Update
1133 the mode line. Lastly, move point to the last position played by the user,
1134 if that move was not a pass.
1136 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1137 be slow. (This should normally be unnecessary; specify it only if the display
1138 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1141 (when (and nocache (not (gnugo-get :waitingp)))
1142 (gnugo-propertize-board-buffer))
1143 (let* ((last-mover (gnugo-get :last-mover))
1144 (other (gnugo-other last-mover))
1145 (move (gnugo-move-history 'car))
1146 (game-over (gnugo-get :game-over))
1150 (let ((l-ov (gnugo-get :lparen-ov))
1151 (r-ov (gnugo-get :rparen-ov)))
1152 (if (member move '("PASS" "resign"))
1153 (mapc 'delete-overlay (list l-ov r-ov))
1154 (gnugo-goto-pos move)
1156 (hspec (gnugo-get :highlight-last-move-spec))
1157 (display-value (nth 0 hspec))
1158 (l-offset (nth 1 hspec))
1159 (l-new-pos (+ p l-offset))
1160 (r-action (nth 2 hspec)))
1161 (overlay-put l-ov 'display
1162 (if (functionp display-value)
1163 (funcall display-value p)
1165 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1167 (funcall r-action r-ov)
1168 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1170 (rename-buffer (concat (gnugo-get :diamond)
1172 (format "%s(game over)"
1173 (if (string= move "resign")
1174 (concat move "ation ")
1176 (format "%s(%s to play)"
1177 (if move (concat move " ") "")
1181 (let ((live (cdr (assq 'live game-over)))
1182 (dead (cdr (assq 'dead game-over)))
1184 (unless (eq game-over (get-text-property 1 'game-over))
1185 (dolist (group (append live dead))
1186 (dolist (pos (cdr group))
1187 (gnugo-goto-pos pos)
1189 (put-text-property p (1+ p) 'group group)))
1190 (put-text-property 1 2 'game-over game-over))
1191 (dolist (group live)
1192 (when (setq pall (cdar group))
1193 (mapc 'delete-overlay pall)
1194 (setcdr (car group) nil)))
1195 (dolist (group dead)
1196 (unless (cdar group)
1197 (let (ov pall c (color (caar group)))
1198 (setq c (if (gnugo--blackp color) "x" "o"))
1199 (dolist (pos (cdr group))
1200 (gnugo-goto-pos pos)
1201 (setq p (point) ov (make-overlay p (1+ p)))
1204 (if (gnugo-get :display-using-images)
1205 ;; respect the dead individually; it takes more time
1206 ;; but that's not a problem (for them)
1207 (gnugo-venerate (get-text-property p 'gnugo-yin)
1208 (gnugo-yang (aref (upcase c) 0)))
1209 (propertize c 'face 'font-lock-warning-face)))
1211 (setcdr (car group) pall))))))
1213 (when (setq window (get-buffer-window (current-buffer)))
1214 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1215 (size (gnugo-get :SZ))
1216 (under10p (< size 10))
1217 (h (- (truncate (- (window-height window)
1218 (* size (gnugo-get :hmul))
1222 (edges (window-edges window))
1223 (right-w-edge (nth 2 edges))
1224 (avail-width (- right-w-edge (nth 0 edges)))
1225 (wmul (gnugo-get :wmul))
1226 (imagesp (symbol-plist (gnugo-f 'ispc)))
1227 (w (/ (- avail-width
1232 2 ; between board and grid
1237 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1238 `(display ,(make-string h 10))
1239 '(invisible :nogrid)))
1244 (cond (imagesp (+ (* 0.5 wmul)
1250 (gspc . ,(when imagesp
1254 ;; DWR: image width alone => OBOE!
1256 ;; NB: ‘(* wmul cw)’ is the same
1257 ;; as ‘(car (image-size ... t))’.
1258 (let ((cw (frame-char-width)))
1259 (/ (+ 1.0 (* wmul cw))
1262 (lpad . ,(let ((d `(display (space :align-to ,w))))
1263 ;; We distinguish between these cases to
1264 ;; workaround a display bug whereby the
1265 ;; `before-string' is omitted entirely (not
1266 ;; rendered) when interacting w/ the text
1267 ;; mode last-move left-paren for moves in
1271 ,(apply 'propertize " " d))
1274 (space :align-to ,(1- avail-width))))))
1275 (setplist (gnugo-f (car pair)) (cdr pair)))))
1277 (let ((cur (gnugo-get :mode-line)))
1278 (unless (equal cur gnugo-mode-line)
1279 (setq cur gnugo-mode-line)
1280 (gnugo-put :mode-line cur)
1281 (gnugo-put :mode-line-form
1282 (cond ((stringp cur)
1283 (setq cur (copy-sequence cur))
1285 (while (setq cut (string-match "~[bwpmtu]" cur))
1287 (setq c (aref cur (incf cut)))
1290 `(,(intern (format "squig-%c" c))
1292 (?b '(or (gnugo-get :black-captures) 0))
1293 (?w '(or (gnugo-get :white-captures) 0))
1294 (?p '(gnugo-other (gnugo-get :last-mover)))
1295 (?t '(let ((ws (gnugo-get :waiting-start)))
1297 (cadr (time-since ws))
1299 (?u '(or (gnugo-get :last-waiting) "-"))
1300 (?m '(gnugo-move-history 'count))))
1302 `(let ,(delete-dups (copy-sequence acc))
1303 (format ,cur ,@(reverse (mapcar 'car acc))))))
1305 (let ((form (gnugo-get :mode-line-form)))
1306 (setq mode-line-process
1308 ;; this dynamicism is nice but excessive in its wantonness
1309 ;;- `(" [" (:eval ,form) "]")
1310 ;; this dynamicism is ok because the user triggers it
1311 (list (format " [%s]" (eval form))))))
1312 (force-mode-line-update))
1314 (when (setq last (gnugo-get :last-user-bpos))
1315 (gnugo-goto-pos last))))
1317 ;;;---------------------------------------------------------------------------
1318 ;;; Game play actions
1320 (defun gnugo-get-move-insertion-filter (proc string)
1321 (with-current-buffer (process-buffer proc)
1322 (let* ((so-far (gnugo-get :get-move-string))
1323 (full (gnugo-put :get-move-string (concat so-far string))))
1324 (when (string-match "^= \\(.+\\)\n\n" full)
1325 (let ((pos-or-pass (match-string 1 full)))
1326 (gnugo-put :get-move-string nil)
1327 (gnugo-put :waitingp nil)
1328 (gnugo-push-move nil pos-or-pass)
1329 (let ((buf (current-buffer)))
1330 (let (gnugo-inhibit-refresh)
1331 (run-hooks 'gnugo-post-move-hook)
1332 (unless gnugo-inhibit-refresh
1333 (with-current-buffer buf
1334 (gnugo-refresh))))))))))
1336 (defun gnugo-get-move (color)
1337 (gnugo-put :waitingp t)
1338 (gnugo--begin-exchange
1339 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1340 (concat "genmove " color))
1341 (accept-process-output))
1343 (defun gnugo-cleanup ()
1344 (when (gnugo-board-buffer-p)
1345 (unless (zerop (buffer-size))
1346 (message "Thank you for playing GNU Go."))
1348 (setplist sym nil) ; "...is next to fordliness." --Huxley
1349 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1350 ;; No worries, things will be Much Better w/ structs, RSN...
1352 (append (gnugo-get :all-yy)
1361 (setq gnugo-state nil)))
1363 (defun gnugo-position ()
1364 (or (get-text-property (point) 'gnugo-position)
1365 (user-error "Not a proper position point")))
1367 (defun gnugo-move ()
1368 "Make a move on the GNUGO Board buffer.
1369 The position is computed from current point.
1370 Signal error if done out-of-turn or if game-over.
1371 To start a game try M-x gnugo."
1374 (let* ((buf (current-buffer))
1375 (pos (gnugo-position))
1376 (move (format "play %s %s" (gnugo-get :user-color) pos))
1377 (accept (gnugo--q move)))
1378 (unless (= ?= (aref accept 0))
1379 (user-error "%s" accept))
1380 (gnugo-push-move t pos) ; value always nil for non-pass move
1381 (let (gnugo-inhibit-refresh)
1382 (run-hooks 'gnugo-post-move-hook)
1383 (unless gnugo-inhibit-refresh
1384 (with-current-buffer buf
1386 (with-current-buffer buf
1387 (gnugo-get-move (gnugo-get :gnugo-color)))))
1389 (defun gnugo-mouse-move (e)
1390 "Do `gnugo-move' at mouse location."
1393 (when (looking-at "[.+]")
1396 (defun gnugo-pass ()
1397 "Make a pass on the GNUGO Board buffer.
1398 Signal error if done out-of-turn or if game-over.
1399 To start a game try M-x gnugo."
1402 (let ((accept (gnugo--q "play %s PASS" (gnugo-get :user-color))))
1403 (unless (= ?= (aref accept 0))
1404 (user-error "%s" accept)))
1405 (let ((donep (gnugo-push-move t "PASS"))
1406 (buf (current-buffer)))
1407 (let (gnugo-inhibit-refresh)
1408 (run-hooks 'gnugo-post-move-hook)
1409 (unless gnugo-inhibit-refresh
1410 (with-current-buffer buf
1413 (with-current-buffer buf
1414 (gnugo-get-move (gnugo-get :gnugo-color))))))
1416 (defun gnugo-mouse-pass (e)
1417 "Do `gnugo-pass' at mouse location."
1422 (defun gnugo-resign ()
1425 (if (not (y-or-n-p "Resign? "))
1426 (message "(not resigning)")
1427 (gnugo-push-move t "resign")
1430 (defun gnugo-animate-group (w/d)
1431 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1432 (let* ((pos (gnugo-position))
1433 (orig-b-m-p (buffer-modified-p))
1435 (unless (memq (following-char) '(?X ?O))
1436 (user-error "No stone at %s" pos))
1437 (setq blurb (message "Computing %s stones ..." w/d)
1438 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1439 (message "%s %s in group." blurb (length stones))
1440 (setplist (gnugo-f 'anim) nil)
1441 (let* ((spec (if (gnugo-get :display-using-images)
1442 (loop with yin = (get-text-property (point) 'gnugo-yin)
1443 with yang = (gnugo-yang (following-char))
1444 with up = (get (gnugo-yy yin yang t) 'display)
1445 with dn = (get (gnugo-yy yin yang) 'display)
1446 for n below (length gnugo-animation-string)
1447 collect (if (zerop (logand 1 n))
1449 (split-string gnugo-animation-string "" t)))
1451 (ovs (save-excursion
1452 (mapcar (lambda (pos)
1453 (gnugo-goto-pos pos)
1455 (ov (make-overlay p (1+ p))))
1456 (overlay-put ov 'category (gnugo-f 'anim))
1457 (overlay-put ov 'priority most-positive-fixnum)
1460 (setplist (gnugo-f 'anim) (cons 'display cell))
1461 (while (and (cdr spec) ; let last linger lest levity lost
1462 (sit-for 0.08675309)) ; jenny jenny i got your number...
1463 (setcar cell (setq spec (cdr spec)))
1464 ;; Force redisplay of overlays.
1465 (set-buffer-modified-p orig-b-m-p))
1467 (mapc 'delete-overlay ovs)
1470 (defun gnugo-display-group-data (command buffer-name)
1471 (message "Computing %s ..." command)
1472 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1473 (switch-to-buffer buffer-name)
1476 (message "Computing %s ... done." command))
1478 (defun gnugo-worm-stones ()
1479 "In the GNUGO Board buffer, animate \"worm\" at current position.
1480 Signal error if done out-of-turn or if game-over.
1481 See variable `gnugo-animation-string' for customization."
1484 (gnugo-animate-group 'worm))
1486 (defun gnugo-worm-data ()
1487 "Display in another buffer data from \"worm\" at current position.
1488 Signal error if done out-of-turn or if game-over."
1491 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1493 (defun gnugo-dragon-stones ()
1494 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1495 Signal error if done out-of-turn or if game-over.
1496 See variable `gnugo-animation-string' for customization."
1499 (gnugo-animate-group 'dragon))
1501 (defun gnugo-dragon-data ()
1502 "Display in another buffer data from \"dragon\" at current position.
1503 Signal error if done out-of-turn or if game-over."
1506 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1508 (defun gnugo-toggle-dead-group ()
1509 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1510 The group is selected from current position (point). Signal error if
1511 not in game-over or if there is no group at that position.
1513 In the context of GNU Go, a group is called a \"dragon\" and may be
1514 composed of more than one \"worm\" (set of directly-connected stones).
1515 It is unclear to the gnugo.el author whether or not GNU Go supports
1516 - considering worms as groups in their own right; and
1517 - toggling group aliveness via GTP.
1518 Due to these uncertainties, this command is only half complete; the
1519 changes you may see in Emacs are not propagated to the gnugo subprocess.
1520 Thus, GTP commands like `final_score' may give unexpected results.
1522 If you are able to expose via GTP `change_dragon_status' in utils.c,
1523 you may consider modifying the `gnugo-toggle-dead-group' source code
1524 to enable full functionality."
1526 (let ((game-over (or (gnugo-get :game-over)
1527 (user-error "Sorry, game still in play")))
1528 (group (or (get-text-property (point) 'group)
1529 (user-error "No stone at that position")))
1530 (now (current-time)))
1531 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1533 (let ((live (assq 'live game-over))
1534 (dead (assq 'dead game-over))
1536 (if (memq group live)
1537 (setq bef live now dead)
1538 (setq bef dead now live))
1539 (setcdr bef (delq group (cdr bef)))
1540 (setcdr now (cons group (cdr now)))
1541 ;; disabled permanently -- too wrong
1545 (let ((color (caar group)))
1546 (dolist (stone (cdr group))
1547 (gnugo-query "play %s %s" color stone)))))
1550 ;; drastic (and wrong -- clobbers capture info, etc)
1551 (gnugo-query "clear_board")
1552 (mapc #'populate (cdr live)))))
1553 ;; here is the desired interface (to be enabled Some Day)
1555 (gnugo-query "change_dragon_status %s %s"
1556 (cadr group) (if (eq now live)
1562 (defun gnugo-estimate-score ()
1563 "Display estimated score of a game of GNU Go.
1564 Output includes number of stones on the board and number of stones
1565 captured by each player, and the estimate of who has the advantage (and
1566 by how many stones)."
1568 (message "Est.score ...")
1569 (let ((black (length (gnugo-lsquery "list_stones black")))
1570 (white (length (gnugo-lsquery "list_stones white")))
1571 (black-captures (gnugo-query "captures black"))
1572 (white-captures (gnugo-query "captures white"))
1573 (est (gnugo-query "estimate_score")))
1574 ;; might as well update this
1575 (gnugo-put :black-captures black-captures)
1576 (gnugo-put :white-captures white-captures)
1577 (message "Est.score ... B %s %s | W %s %s | %s"
1578 black black-captures white white-captures est)))
1580 (defun gnugo-write-sgf-file (filename)
1581 "Save the game history to FILENAME (even if unfinished).
1582 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1583 (interactive "FWrite game as SGF file: ")
1584 (when (and (file-exists-p filename)
1585 (not (y-or-n-p "File exists. Continue? ")))
1586 (user-error "Not writing %s" filename))
1587 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1588 (set-buffer-modified-p nil))
1590 (defun gnugo--who-is-who (wait play samep)
1591 (message "GNU Go %splays as %s, you as %s (%s)"
1592 (if samep "" "now ")
1595 "NOTE: this is a switch!")))
1597 (defsubst gnugo--nodep (x)
1598 (keywordp (caar x)))
1600 (defsubst gnugo--SZ! (size)
1601 (gnugo-put :SZ size))
1603 (defun gnugo-read-sgf-file (filename)
1604 "Load the first game tree from FILENAME, a file in SGF format."
1605 (interactive "fSGF file to load: ")
1606 (when (file-directory-p filename)
1607 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1608 (let (ans play wait samep coll tree)
1609 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1610 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1611 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1612 (expand-file-name filename)))
1614 (user-error "%s" ans))
1615 (setq play (substring ans 2)
1616 wait (gnugo-other play)
1617 samep (string= (gnugo-get :user-color) play))
1618 (gnugo-put :last-mover wait)
1620 (gnugo-put :gnugo-color wait)
1621 (gnugo-put :user-color play))
1622 (setq coll (gnugo/sgf-create filename)
1623 tree (nth (let ((n (length coll)))
1627 ;; (let* ((q (format "Which game? (1-%d)" n))
1628 ;; (choice (1- (read-number q 1))))
1629 ;; (if (and (< -1 choice) (< choice n))
1631 ;; (message "(Selecting the first game)")
1633 ;; but this is what we use (for now) to accomodate
1634 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1636 (message "(Selecting the first game)"))
1639 (gnugo-put :sgf-collection coll)
1640 (gnugo-put :sgf-gametree tree)
1641 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0))
1642 ;; This is deliberately undocumented for now.
1643 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1645 (gnugo-put :game-over
1647 (or (gnugo--root-prop :RE tree)
1648 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1650 (when (and game-over
1651 ;; (maybe) todo: user var to inhibit (can be slow)
1653 (gnugo-close-game nil game-over)))
1655 (set-buffer-modified-p nil)
1656 (gnugo--who-is-who wait play samep)))
1658 (defun gnugo-magic-undo (spec &optional noalt keep)
1659 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1660 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1661 check that the position is occupied by a stone of the user's color,
1662 and if so, remove moves from the history until that position is clear.
1663 If SPEC is a positive number, remove exactly that many moves from the
1664 history, signaling an error if the history is exhausted before finishing.
1665 If SPEC Is 0 (zero), remove either one or two moves,
1666 so that you are to play next.
1667 If SPEC is not recognized, signal \"bad spec\" error.
1669 Refresh the board for each move undone. If (in the case where SPEC is
1670 a number) after finishing, the color to play is not the user's color,
1671 schedule a move by GNU Go.
1673 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1674 turn to play. Optional second arg NOALT non-nil inhibits this.
1676 Optional third arg KEEP non-nil means do not prune the undone moves
1677 from the gametree, such that they become a sub-gametree (variation)
1681 (user-color (gnugo-get :user-color))
1682 (monkey (gnugo-get :monkey))
1683 (tree (gnugo-get :sgf-gametree))
1684 (ends (gnugo--tree-ends tree))
1685 (remorseful (not (gnugo--no-regrets monkey ends)))
1687 (cond ((numberp spec)
1688 (setq n (if (zerop spec)
1689 (if (string= user-color (gnugo-get :last-mover))
1693 done (lambda () (zerop n))))
1694 ((string-match "^[a-z]" spec)
1695 (let ((pos (upcase spec)))
1696 (setq done `(lambda ()
1697 (gnugo-goto-pos ,pos)
1698 (memq (following-char) '(?. ?+))))
1699 (when (funcall done)
1700 (user-error "%s already clear" pos))
1701 (when (= (save-excursion
1702 (gnugo-goto-pos pos)
1704 (if (gnugo--blackp user-color)
1707 (user-error "%s not occupied by %s" pos user-color))))
1708 (t (user-error "Bad spec: %S" spec)))
1709 (when (gnugo-get :game-over)
1710 (gnugo--unclose-game))
1711 (while (not (funcall done))
1712 (setq ans (gnugo--q "undo"))
1713 (unless (= ?= (aref ans 0))
1714 (user-error "%s" ans))
1715 (pop (aref monkey 0))
1716 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1717 (gnugo-merge-showboard-results) ; all
1718 (gnugo-refresh) ; this
1720 (redisplay)) ; eye candy
1721 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1723 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1724 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1726 (gnugo-get :center-position)))
1728 (unless (or keep remorseful)
1729 (aset ends (aref monkey 1) (aref monkey 0)))
1730 (when (and ulastp (not noalt))
1731 (gnugo-get-move (gnugo-get :gnugo-color))))))
1733 (defun gnugo-undo-one-move (&optional me-next)
1734 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1735 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1736 Prefix arg ME-NEXT means to arrange for you to play
1737 the color of the next move (and GNU Go the opposite).
1738 This is useful after loading an SGF file whose last
1739 move was done by the color you prefer to play:
1740 \\[gnugo-read-sgf-file] FILENAME RET
1741 C-u \\[gnugo-undo-one-move]
1743 See also `gnugo-undo-two-moves'."
1746 (gnugo-magic-undo 1 t)
1748 (let* ((wait (gnugo-get :last-mover))
1749 (play (gnugo-other wait)))
1750 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
1751 (gnugo-put :user-color play)
1752 (gnugo-put :gnugo-color wait))))
1754 (defun gnugo-undo-two-moves ()
1755 "Undo a pair of moves (GNU Go's and yours).
1756 However, if you are the last mover, undo only one move.
1757 Regardless, after undoing, it is your turn to play again."
1760 (gnugo-magic-undo 0))
1762 (defun gnugo-oops (&optional position)
1763 "Like `gnugo-undo-two-moves', but keep the undone moves.
1764 The kept moves become a sub-gametree (variation) when play resumes.
1765 Prefix arg means, instead, undo repeatedly up to and including
1766 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1769 (gnugo-magic-undo (if position
1774 (defun gnugo-display-final-score ()
1775 "Display final score and other info in another buffer (when game over).
1776 If the game is still ongoing, Emacs asks if you wish to stop play (by
1777 making sure two \"pass\" moves are played consecutively, if necessary).
1778 Also, add the `:RE' SGF property to the root node of the game tree."
1780 (let ((game-over (gnugo-get :game-over)))
1781 (unless (or game-over
1782 (and (not (gnugo-get :waitingp))
1783 (y-or-n-p "Game still in play. Stop play now? ")))
1784 (user-error "Sorry, game still in play"))
1788 (message "Playing PASS for %s ..."
1789 (gnugo-get (if userp :user-color :gnugo-color)))
1791 (gnugo-push-move userp "PASS")))
1796 (let ((b= " Black = ")
1798 (res (when (string= "resign" (gnugo-move-history 'car))
1799 (gnugo-get :last-mover)))
1803 (format "%s wins.\n"
1804 (substring (if (= ?b (aref res 0)) w= b=)
1806 "The game is over.\n"
1807 (format "Resignation by %s.\n" res))
1808 result (concat (upcase (substring (gnugo-other res) 0 1))
1810 (message "Computing final score ...")
1811 (let* ((g-over (gnugo-get :game-over))
1812 (live (cdr (assq 'live g-over)))
1813 (dead (cdr (assq 'dead g-over)))
1814 (seed (gnugo-get :scoring-seed))
1815 (terr-q (format "final_status_list %%s_territory %d" seed))
1818 (b-terr (length (gnugo-lsquery terr-q "black")))
1819 (w-terr (length (gnugo-lsquery terr-q "white")))
1820 (b-capt (string-to-number (gnugo-get :black-captures)))
1821 (w-capt (string-to-number (gnugo-get :white-captures)))
1822 (komi (gnugo--root-prop :KM)))
1823 (setq blurb (list "The game is over. Final score:\n")
1824 result (gnugo-query "final_score %d" seed))
1825 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1826 (dolist (group live)
1827 (incf (if (gnugo--blackp (caar group))
1830 (length (cdr group))))
1831 (dolist (group dead)
1832 (incf (if (gnugo--blackp (caar group))
1835 (length (cdr group))))
1836 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1837 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1838 w-terr terr komi 'komi (+ w-terr komi))
1841 (dolist (group dead)
1842 (incf (if (gnugo--blackp (caar group))
1845 (* 2 (length (cdr group)))))
1846 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1851 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1855 (+ w-terr w-capt komi))
1857 (push (if (string= "0" result)
1858 "The game is a draw.\n"
1859 (format "%s wins by %s.\n"
1860 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1861 (substring result 2)))
1863 (message "Computing final score ... done")))
1865 (let ((beg (gnugo-get :game-start-time))
1866 (end (gnugo-get :game-end-time)))
1870 ((yep (pretty moment)
1871 (push (format-time-string
1872 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
1875 (yep "Game start" beg)
1877 (setq blurb (apply 'concat (nreverse blurb)))
1878 (gnugo--set-root-prop :RE result)
1879 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1883 (defun gnugo-quit ()
1884 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1885 If the game is not over, ask for confirmation first."
1887 (if (or (gnugo-get :game-over)
1888 (y-or-n-p "Quit? "))
1890 (message "(not quitting)")))
1892 (defun gnugo-leave-me-alone ()
1893 "Kill the current buffer unconditionally."
1897 (defun gnugo-fancy-undo (count)
1898 "Rewind the game tree in various ways.
1899 Prefix arg COUNT means to undo that many moves.
1900 Otherwise, undo repeatedly up to and including the move
1901 which placed the stone at point."
1904 ;; TODO: Move this into `gnugo-magic-undo' proper.
1905 (cond ((numberp count) count)
1906 ((consp count) (car count))
1907 (t (gnugo-position)))))
1909 (defun gnugo-toggle-image-display-command () ; ugh
1910 "Toggle use of images to display the board, then refresh."
1912 (gnugo-toggle-image-display)
1913 (save-excursion (gnugo-refresh)))
1915 (defun gnugo-describe-position ()
1916 "Display the board position under cursor in the echo area."
1918 (message "%s" (gnugo-position)))
1920 (defun gnugo-switch-to-another ()
1921 "Switch to another GNU Go game buffer (if any)."
1923 (loop for buf in (cdr (buffer-list))
1924 if (gnugo-board-buffer-p buf)
1927 (switch-to-buffer buf))
1928 finally do (message "(only one)")))
1930 ;;;---------------------------------------------------------------------------
1931 ;;; Command properties and gnugo-command
1933 ;; GTP commands entered by the user are never issued directly to GNU Go;
1934 ;; instead, their behavior and output are controlled by the property
1935 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1936 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1938 ;; :full -- completely interpret the command string; the value is a
1939 ;; func that takes the list of words derived from splitting the
1940 ;; command string (minus the command) and handles everything.
1942 ;; :output -- either a keyword specifying the preferred output method:
1943 ;; :message -- show output in minibuffer
1944 ;; :discard -- sometimes you just don't care;
1945 ;; or a function that takes one arg, the output string, and
1946 ;; handles it completely. default is to switch to buffer
1947 ;; "*gnugo command output*" if the output has a newline,
1948 ;; otherwise use `message'.
1950 ;; :post-thunk -- run after output processing (at the very end).
1952 (defun gnugo-command (command)
1953 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1954 Output and Emacs behavior depend on which command is given (some
1955 commands are handled completely by Emacs w/o using the subprocess;
1956 some commands have their output displayed in specially prepared
1957 buffers or in the echo area; some commands are instrumented to do
1958 gnugo.el-specific housekeeping).
1960 For example, for the command \"help\", Emacs visits the
1961 GTP command reference info page.
1963 NOTE: At this time, GTP command handling specification is still
1964 incomplete. Thus, some commands WILL confuse gnugo.el."
1965 (interactive "sCommand: ")
1966 (if (string= "" command)
1967 (message "(no command given)")
1968 (let* ((split (split-string command))
1969 (cmd (intern (car split)))
1970 (spec (get cmd :gnugo-gtp-command-spec))
1971 (full (plist-get spec :full)))
1973 (funcall full (cdr split))
1974 (message "Doing %s ..." command)
1975 (let* ((ans (gnugo--q command))
1976 (where (plist-get spec :output)))
1977 (if (string-match "unknown.command" ans)
1979 (cond ((functionp where) (funcall where ans))
1980 ((eq :discard where) (message ""))
1981 ((or (eq :message where)
1982 (not (string-match "\n" ans)))
1984 (t (switch-to-buffer "*gnugo command output*")
1987 (message "Doing %s ... done." command)))
1988 (let ((thunk (plist-get spec :post-thunk)))
1989 (when thunk (funcall thunk)))))))))
1991 ;;;---------------------------------------------------------------------------
1992 ;;; Major mode for interacting with a GNUGO subprocess
1994 (put 'gnugo-board-mode 'mode-class 'special)
1995 (defun gnugo-board-mode ()
1996 "Major mode for playing GNU Go.
1997 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1998 In this mode, keys do not self insert.
2000 \\{gnugo-board-mode-map}"
2001 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2002 (buffer-disable-undo) ; todo: undo undo undoing
2003 (kill-all-local-variables)
2004 (use-local-map gnugo-board-mode-map)
2005 (set (make-local-variable 'font-lock-defaults)
2006 '(gnugo-font-lock-keywords t))
2007 (setq major-mode 'gnugo-board-mode
2008 mode-name "GNUGO Board"
2010 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2011 (set (make-local-variable 'gnugo-state)
2012 (gnugo--mkht :size (1- 42)))
2013 (add-to-invisibility-spec :nogrid)
2014 (mapc (lambda (prop)
2015 (gnugo-put prop nil)) ; todo: separate display/game aspects;
2016 '(:game-over ; move latter to func `gnugo'
2023 :display-using-images
2027 (let ((name (if (string-match "[ ]" gnugo-program)
2028 (let ((p (substring gnugo-program 0 (match-beginning 0)))
2029 (o (substring gnugo-program (match-end 0)))
2030 (h (or (car gnugo-option-history) "")))
2031 (when (string-match "--mode" o)
2032 (user-error "Found \"--mode\" in `gnugo-program'"))
2033 (when (and o (cl-plusp (length o))
2034 h (cl-plusp (length o))
2035 (or (< (length h) (length o))
2036 (not (string= (substring h 0 (length o))
2038 (push (concat o " " h) gnugo-option-history))
2041 (args (read-string "GNU Go options: "
2042 (car gnugo-option-history)
2043 'gnugo-option-history))
2045 board-size user-color handicap komi minus-l infile)
2046 (loop for (var default opt &optional rx)
2047 in '((board-size 19 "--boardsize")
2048 (user-color "black" "--color" "\\(black\\|white\\)")
2049 (handicap 0 "--handicap")
2051 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2052 (infile nil "--infile" "[ ]*[^ ]+"))
2054 (or (when (string-match opt args)
2055 (let ((start (match-end 0)) s)
2056 (string-match (or rx "[0-9.]+") args start)
2057 (setq s (match-string 0 args))
2058 (if rx s (string-to-number s))))
2060 (gnugo-put :user-color user-color)
2061 (let ((proc-args (split-string args)))
2062 (gnugo-put :proc-args proc-args)
2063 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2064 (current-buffer) name
2065 "--mode" "gtp" "--quiet"
2067 (set-process-sentinel proc 'gnugo-sentinel)
2068 ;; Emacs is too protective sometimes, blech.
2069 (set-process-query-on-exit-flag proc nil)
2070 (when (or minus-l infile)
2072 in '((board-size "query_boardsize")
2074 (handicap "get_handicap"))
2075 do (set prop (string-to-number (gnugo-query q)))))
2076 (gnugo-put :diamond (substring (process-name proc) 5))
2077 (gnugo-put :gnugo-color (gnugo-other user-color))
2078 (gnugo-put :highlight-last-move-spec
2079 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2080 (gnugo-put :lparen-ov (make-overlay 1 1))
2081 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
2082 (overlay-put ov 'display ")")
2084 (let* ((coll (gnugo/sgf-create "(;FF[4]GM[1])" t))
2086 (gnugo-put :sgf-gametree tree)
2087 (gnugo-put :sgf-collection coll)
2088 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0)))
2089 (gnugo--SZ! board-size)
2090 (loop with gb = (gnugo--blackp (gnugo-other user-color))
2091 for (property value &optional mogrifyp) in
2093 (:DT ,(format-time-string "%Y-%m-%d"))
2094 (:RU ,(if (string-match "--chinese-rules" args)
2097 (:AP ("gnugo.el" . ,gnugo-version))
2099 (,(if gb :PW :PB) ,(user-full-name))
2100 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
2101 ,@(when (not (zerop handicap))
2103 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
2105 do (gnugo-note property value mogrifyp)))
2106 (gnugo-put :waiting-start (current-time))
2109 (run-hooks 'gnugo-board-mode-hook)
2112 ;;;---------------------------------------------------------------------------
2116 (defun gnugo (&optional new-game)
2117 "Run gnugo in a buffer, or resume a game in progress.
2118 Prefix arg means skip the game-in-progress check and start a new
2120 \\<gnugo-board-mode-map>
2121 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2123 You are queried for additional command-line options (Emacs supplies
2124 \"--mode gtp --quiet\" automatically). Here is a list of options
2125 that gnugo.el understands and handles specially:
2127 --boardsize num Set the board size to use (5--19)
2128 --color <color> Choose your color ('black' or 'white')
2129 --handicap <num> Set the number of handicap stones (0--9)
2131 If there is already a game in progress you may resume it instead of
2132 starting a new one. See `gnugo-board-mode' documentation for more info."
2134 (let* ((all (let (acc)
2135 (dolist (buf (buffer-list))
2136 (when (gnugo-board-buffer-p buf)
2137 (push (cons (buffer-name buf) buf) acc)))
2140 (if (and (not new-game)
2142 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2143 (if (= 1 n) "" "s"))))
2148 (let ((sel (completing-read "Which one? " all nil t)))
2149 (if (string= "" sel)
2151 (assoc sel all))))))
2152 ;; set up a new board
2154 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2155 (gnugo-goto-pos (format "A%d" half))
2156 (forward-char (* 2 (1- half)))
2157 (gnugo-put :last-user-bpos
2158 (gnugo-put :center-position
2159 (get-text-property (point) 'gnugo-position))))
2161 (gnugo-put :game-start-time (current-time))
2162 (let ((g (gnugo-get :gnugo-color))
2163 (n (or (gnugo--root-prop :HA) 0))
2164 (u (gnugo-get :user-color)))
2165 (gnugo-put :last-mover g)
2166 (when (or (and (gnugo--blackp u) (< 1 n))
2167 (and (gnugo--blackp g) (< n 2)))
2168 (gnugo-put :last-mover u)
2170 (gnugo-get-move g))))))
2172 ;;;---------------------------------------------------------------------------
2173 ;;; Load-time actions
2175 (unless gnugo-board-mode-map
2176 (setq gnugo-board-mode-map (make-sparse-keymap))
2177 (suppress-keymap gnugo-board-mode-map)
2178 (mapc (lambda (pair)
2179 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2180 '(("?" . describe-mode)
2181 ("\C-m" . gnugo-move)
2184 ("R" . gnugo-resign)
2186 ("Q" . gnugo-leave-me-alone)
2187 ("U" . gnugo-fancy-undo)
2188 ("\M-u" . gnugo-undo-one-move)
2189 ("u" . gnugo-undo-two-moves)
2190 ("\C-?" . gnugo-undo-two-moves)
2192 ("\C-l" . gnugo-refresh)
2193 ("\M-_" . gnugo-boss-is-near)
2194 ("_" . gnugo-boss-is-near)
2195 ("h" . gnugo-move-history)
2196 ("L" . gnugo-frolic-in-the-leaves)
2197 ("i" . gnugo-toggle-image-display-command)
2198 ("w" . gnugo-worm-stones)
2199 ("W" . gnugo-worm-data)
2200 ("d" . gnugo-dragon-stones)
2201 ("D" . gnugo-dragon-data)
2202 ("t" . gnugo-toggle-dead-group)
2203 ("g" . gnugo-toggle-grid)
2204 ("!" . gnugo-estimate-score)
2205 (":" . gnugo-command)
2206 (";" . gnugo-command)
2207 ("=" . gnugo-describe-position)
2208 ("s" . gnugo-write-sgf-file)
2209 ("\C-x\C-s" . gnugo-write-sgf-file)
2210 ("\C-x\C-w" . gnugo-write-sgf-file)
2211 ("l" . gnugo-read-sgf-file)
2212 ("F" . gnugo-display-final-score)
2213 ("A" . gnugo-switch-to-another)
2215 ([(down-mouse-1)] . gnugo-mouse-move)
2216 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2217 ([(down-mouse-3)] . gnugo-mouse-pass)
2218 ;; delving into the curiosities
2219 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2221 (unless (get 'help :gnugo-gtp-command-spec)
2223 ((sget (x) (get x :gnugo-gtp-command-spec))
2224 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2225 (plist-put (sget cmd) prop val)))
2226 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2229 (jam cmd (car ls) (cadr ls))
2230 (setq ls (cddr ls)))))))
2231 (cl-macrolet ((deffull (who &body body)
2232 (declare (indent 1))
2233 `(defgtp ',who :full (lambda (sel)
2237 (info "(gnugo)GTP command reference")
2238 (when sel (setq sel (intern (car sel))))
2239 (let (buffer-read-only pad cur spec output found)
2241 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2242 (goto-char (point-min))
2244 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2247 (setq pad (make-string (- (match-beginning 1)
2248 (match-beginning 0))
2252 (get (setq cur (intern (match-string 1)))
2253 :gnugo-gtp-command-spec))
2255 (note "handles this command completely"))
2256 (when (setq output (plist-get spec :output))
2257 (if (functionp output)
2258 (note "handles the output specially")
2260 (:discard (note "discards the output"))
2261 (:message (note "displays the output in the echo area")))))
2263 (setq found (match-beginning 0))))))
2264 (cond (found (goto-char found))
2266 (t (message "(no such command: %s)" sel)))))
2268 (deffull final_score
2269 (gnugo-display-final-score))
2275 :post-thunk (lambda ()
2276 (gnugo--unclose-game)
2277 (gnugo-put :last-mover nil)
2279 (gnugo--SZ! (string-to-number
2281 "query_boardsize")))
2285 (gnugo-read-sgf-file (car sel)))
2287 (deffull (undo gg-undo)
2291 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2292 (t (car sel)))))))))
2297 ;;;---------------------------------------------------------------------------
2298 ;;; The remainder of this file defines a simplified SGF-handling library.
2299 ;;; When/if it should start to attain generality, it should be split off into
2300 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2301 ;;; "gnugo/" prefix.
2303 (defconst gnugo/sgf-*r4-properties*
2304 '((AB "Add Black" setup list stone)
2305 (AE "Add Empty" game list point)
2306 (AN "Annotation" game simpletext)
2307 (AP "Application" root (simpletext . simpletext))
2308 (AR "Arrow" - list (point . point))
2309 (AS "Who adds stones" - simpletext) ; (LOA)
2310 (AW "Add White" setup list stone)
2311 (B "Black" move move)
2312 (BL "Black time left" move real)
2313 (BM "Bad move" move double)
2314 (BR "Black rank" game simpletext)
2315 (BT "Black team" game simpletext)
2316 (C "Comment" - text)
2317 (CA "Charset" root simpletext)
2318 (CP "Copyright" game simpletext)
2319 (CR "Circle" - list point)
2320 (DD "Dim points" - elist point) ; (inherit)
2321 (DM "Even position" - double)
2322 (DO "Doubtful" move none)
2323 (DT "Date" game simpletext)
2324 (EV "Event" game simpletext)
2325 (FF "Fileformat" root [number (1 . 4)])
2326 (FG "Figure" - (or none (number . simpletext)))
2327 (GB "Good for Black" - double)
2328 (GC "Game comment" game text)
2329 (GM "Game" root [number (1 . 20)])
2330 (GN "Game name" game simpletext)
2331 (GW "Good for White" - double)
2332 (HA "Handicap" game number) ; (Go)
2333 (HO "Hotspot" - double)
2334 (IP "Initial pos." game simpletext) ; (LOA)
2335 (IT "Interesting" move none)
2336 (IY "Invert Y-axis" game simpletext) ; (LOA)
2337 (KM "Komi" game real) ; (Go)
2339 (LB "Label" - list (point . simpletext))
2340 (LN "Line" - list (point . point))
2341 (MA "Mark" - list point)
2342 (MN "set move number" move number)
2343 (N "Nodename" - simpletext)
2344 (OB "OtStones Black" move number)
2345 (ON "Opening" game text)
2346 (OT "Overtime" game simpletext)
2347 (OW "OtStones White" move number)
2348 (PB "Player Black" game simpletext)
2349 (PC "Place" game simpletext)
2350 (PL "Player to play" setup color)
2351 (PM "Print move mode" - number) ; (inherit)
2352 (PW "Player White" game simpletext)
2353 (RE "Result" game simpletext)
2354 (RO "Round" game simpletext)
2355 (RU "Rules" game simpletext)
2356 (SE "Markup" - point) ; (LOA)
2357 (SL "Selected" - list point)
2358 (SO "Source" game simpletext)
2359 (SQ "Square" - list point)
2360 (ST "Style" root [number (0 . 3)])
2361 (SU "Setup type" game simpletext) ; (LOA)
2362 (SZ "Size" root (or number (number . number)))
2363 (TB "Territory Black" - elist point) ; (Go)
2364 (TE "Tesuji" move double)
2365 (TM "Timelimit" game real)
2366 (TR "Triangle" - list point)
2367 (TW "Territory White" - elist point) ; (Go)
2368 (UC "Unclear pos" - double)
2369 (US "User" game simpletext)
2371 (VW "View" - elist point) ; (inherit)
2372 (W "White" move move)
2373 (WL "White time left" move real)
2374 (WR "White rank" game simpletext)
2375 (WT "White team" game simpletext)
2376 (LT "Lose on time" setup simpletext))
2377 ;; r4-specific notes
2378 ;; - changed: DT FG LB RE RU SZ
2379 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2380 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2382 (defun gnugo/sgf-create (file-or-data &optional data-p)
2383 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2384 FILE-OR-DATA is a file name or SGF[4] data.
2385 Optional arg DATA-P non-nil means FILE-OR-DATA is
2386 a string containing SGF[4] data.
2387 A collection is a list of gametrees, each a vector of four elements:
2389 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2390 have a move number of the previous \"move\" node (or zero)
2392 KIDS -- `eq' hash: node to node list (branch points only)
2394 ENDS -- a vector of node lists, with shared tails
2395 (last element of all the lists is the root node)
2397 ROOT -- the root node"
2398 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2399 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2400 (put 'gnugo/sgf-*r4-properties* :keywords
2401 (mapcar (lambda (full)
2403 (intern (format ":%s" (car full)))))
2404 gnugo/sgf-*r4-properties*))))
2405 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2406 (put 'gnugo/sgf-*r4-properties* :specs
2407 (mapcar (lambda (full)
2408 (cons (car full) (cdddr full)))
2409 gnugo/sgf-*r4-properties*))))
2412 ((sw () (skip-chars-forward " \t\n"))
2413 (x (end) (let ((beg (point))
2415 (:end (lambda (char) (= ?\] char)))
2416 (:mid (lambda (char) (= ?\: char)))
2417 (t (lambda (char) (or (= ?\: char)
2420 (while (not (funcall endp (setq c (following-char))))
2426 ((looking-at "\\s-+")
2427 (delete-region (point) (match-end 0))
2429 (t (forward-char 1))))
2430 (buffer-substring-no-properties beg (point))))
2431 (one (type end) (let ((s (progn
2436 ;; blech, begone bu"tt"-ugly blatherings
2437 ;; (but bide brobdingnagian boards)...
2438 (if (and (string= "tt" s)
2443 ((simpletext color) s)
2444 ((number real double) (string-to-number s))
2447 (t (error "Unhandled type: %S" type)))))
2448 (val (spec) (cond ((symbolp spec)
2451 ;; todo: check range here.
2452 (one (aref spec 0) :end))
2453 ((eq 'or (car spec))
2454 (let ((v (one (cadr spec) t)))
2455 (if (= ?\] (following-char))
2458 ;; todo: this assumes `spec' has the form
2459 ;; (or foo (foo . bar))
2460 ;; i.e., foo is not rescanned. e.g., `SZ'.
2461 ;; probably this assumption is consistent
2462 ;; w/ the SGF authors' desire to make the
2463 ;; parsing easy, but you never know...
2464 (cons v (one (cdaddr spec) :end)))))
2465 (t (cons (one (car spec) :mid)
2466 (one (cdr spec) :end)))))
2467 (short (who) (when (eobp)
2468 (error "Unexpected EOF while reading %s" who)))
2469 (atvalp () (= ?\[ (following-char)))
2470 (PROP () (let (name spec ltype)
2471 (sw) (short 'property)
2472 (when (looking-at "[A-Z]")
2473 (setq name (read (current-buffer))
2474 spec (cdr (assq name specs)))
2477 (cdr (assq name keywords))
2478 (prog1 (if (= 1 (length spec))
2480 (unless (memq (setq ltype (car spec))
2482 (error "Bad spec: %S" spec))
2483 (if (and (eq 'elist ltype) (sw)
2486 (let ((type (cadr spec))
2488 (while (and (sw) (atvalp)
2489 (setq mo (val type)))
2494 (forward-char 1))))))
2495 (morep () (and (sw) (not (eobp))))
2496 (seek (c) (and (morep) (= c (following-char))))
2497 (seek-into (c) (when (seek c)
2500 (NODE () (when (seek-into ?\;)
2502 while (setq prop (PROP))
2504 (when (eq :SZ (car prop))
2505 (setq SZ (cdr prop)))
2507 (TREE (parent mnum kids)
2514 (puthash node (+ (if (gnugo--move-prop node)
2517 (gethash prev mnum 0))
2520 (when (listp (gethash prev kids t))
2521 (push node (gethash prev kids)))
2525 (if (not (seek ?\())
2530 (puthash node (list) kids)
2531 (loop while (seek ?\()
2532 append (TREE ls mnum kids)))
2536 (insert-file-contents file-or-data)
2537 (insert file-or-data)
2538 (goto-char (point-min)))
2540 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2541 (kids (gnugo--mkht))
2542 (ends (TREE nil mnum kids))
2543 (root (car (last (car ends)))))
2546 (apply 'vector ends)
2549 (defun gnugo/sgf-hang-from-root (tree)
2550 (let ((ht (gnugo--mkht))
2551 (leaves (append tree nil)))
2555 with rh ; rectified history
2556 with bp ; branch point
2558 until (setq bp (gethash node ht))
2560 (push node rh) ; good for now: ½τ
2564 ;; first run: main line
2566 ;; subsequent runs: grafts (value discarded)
2568 ;; Maintain order of ‘leaves’.
2569 (let ((was (cdr bp)))
2570 (if (gnugo--nodep (car was))
2574 (setq tree (hang (pop leaves)))
2575 (mapc #'hang leaves)
2578 (defun gnugo/sgf-write-file (collection filename)
2579 ;; take responsibility for our actions
2580 (let ((me (cons "gnugo.el" gnugo-version)))
2581 (dolist (tree collection)
2582 (gnugo--set-root-prop :AP me tree)))
2584 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2585 (specs (mapcar (lambda (full)
2586 (cons (intern (format ":%s" (car full)))
2588 gnugo/sgf-*r4-properties*))
2590 ;; todo: escape special chars for `text' and `simpletext'.
2592 ((>>one (v) (insert (format "[%s]" v)))
2593 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2594 (>>nl () (cond ((memq name aft-newline-appreciated)
2596 ((< 60 (current-column))
2604 (insert (substring (symbol-name name) 1))
2607 (setq spec (cdr (assq name specs)))
2611 (let ((>> (if (consp (cadr spec))
2614 (dolist (little-v v)
2616 (funcall >> little-v)
2623 (loop initially (insert ";")
2627 (unless (zerop (current-column))
2631 (funcall (if (gnugo--nodep x)
2637 (dolist (tree collection)
2638 (>>tree (gnugo/sgf-hang-from-root tree)))
2640 (write-file filename)))))
2642 ;;; gnugo.el ends here