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