]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo int] Drop :monkey COUNT; use node's tree MNUM directly.
[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 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
8
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.
13
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.
18
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/>.
21
22 ;;; Commentary:
23
24 ;; Playing
25 ;; -------
26 ;;
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.
32 ;;
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.
37 ;;
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.
47 ;;
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. :-)
53 ;;
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
56 ;; the program.
57 ;;
58 ;;
59 ;; Meta-Playing (aka Customizing)
60 ;; ------------------------------
61 ;;
62 ;; Customization is presently limited to
63 ;; vars: `gnugo-program'
64 ;; `gnugo-animation-string'
65 ;; `gnugo-mode-line'
66 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
67 ;; `gnugo-xpms'
68 ;; normal hooks: `gnugo-board-mode-hook'
69 ;; `gnugo-post-move-hook'
70 ;; and the keymap: `gnugo-board-mode-map'
71 ;;
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
74 ;; interface.
75
76 ;;; Code:
77
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'
81
82 ;;;---------------------------------------------------------------------------
83 ;;; Political arts
84
85 (defconst gnugo-version "2.3.1"
86 "Version of gnugo.el currently loaded.
87 This follows a MAJOR.MINOR.PATCH scheme.")
88
89 ;;;---------------------------------------------------------------------------
90 ;;; Variables for the uninquisitive programmer
91
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
97 in OPTIONS.
98
99 For more information on GTP and GNU Go, feel free to visit:
100 http://www.gnu.org/software/gnugo")
101
102 (defvar gnugo-board-mode-map nil
103 "Keymap for GNUGO Board mode.")
104
105 (defvar gnugo-board-mode-hook nil
106 "Hook run when entering GNUGO Board mode.")
107
108 (defvar gnugo-inhibit-refresh nil
109 "Used in `gnugo-post-move-hook'.")
110
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.")
119
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...
133 yada yada yada))
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.")
138
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)
145 ~m move number
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.")
150
151 (defvar gnugo-X-face 'font-lock-string-face
152 "Name of face to use for X (black) stones.")
153
154 (defvar gnugo-O-face 'font-lock-builtin-face
155 "Name of face to use for O (white) stones.")
156
157 (defvar gnugo-grid-face 'default
158 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
159
160 ;;;---------------------------------------------------------------------------
161 ;;; Variables for the inquisitive programmer
162
163 (defconst gnugo-font-lock-keywords
164 '(("X" . gnugo-X-face)
165 ("O" . gnugo-O-face))
166 "Font lock keywords for `gnugo-board-mode'.")
167
168 (defvar gnugo-option-history nil)
169
170 (defvar gnugo-state nil) ; hint: C-c C-p
171
172 (eval-when-compile
173 (defvar gnugo-xpms nil))
174
175 ;;;---------------------------------------------------------------------------
176 ;;; Support functions
177
178 (defsubst gnugo--mkht (&rest etc)
179 (apply 'make-hash-table :test 'eq etc))
180
181 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
182 (compare-strings s1 beg1 nil s2 beg2 nil))
183
184 (defun gnugo-put (key value)
185 "Associate move/game/board-specific property KEY with VALUE.
186
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\".
195
196 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
197
198 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
199
200 :game-over -- nil until game over at which time its value is set to
201 the alist `((live GROUP ...) (dead GROUP ...))'
202
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
206
207 :sgf-gametree -- one of the gametrees in :sgf-collection
208
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\"
212
213 :gnugo-color -- either \"black\" or \"white\"
214 :user-color
215 :last-mover
216
217 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
218 :waiting-start
219
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!)
225
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)
229
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'
235
236 :lparen-ov -- overlays shuffled about to indicate the last move; only
237 :rparen-ov one is used when displaying using images
238
239 :last-user-bpos -- board position; keep the hapless human happy
240
241 As things stabilize probably more info will be added to this docstring."
242 (declare (indent 1))
243 (puthash key value gnugo-state))
244
245 (defun gnugo-get (key)
246 "Return the move/game/board-specific value for KEY.
247 See `gnugo-put'."
248 (gethash key gnugo-state))
249
250 (defsubst gnugo--tree-mnum (tree)
251 (aref tree 0))
252
253 (defsubst gnugo--tree-ends (tree)
254 (aref tree 2))
255
256 (defsubst gnugo--set-tree-ends (tree ends)
257 (aset tree 2 ends)
258 ;; hmm, probably unnecessary
259 tree)
260
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."
264 (interactive)
265 (let ((buf (current-buffer))
266 (d (gnugo-get :diamond))
267 acc)
268 (loop for key being the hash-keys of gnugo-state
269 using (hash-values val)
270 do (push (cons key
271 (case key
272 ((:xpms :local-xpms)
273 (format "hash: %X (%d images)"
274 (sxhash val)
275 (length val)))
276 (:sgf-collection
277 (length val))
278 (:sgf-gametree
279 (list (hash-table-count
280 (gnugo--tree-mnum val))
281 (hash-table-count
282 (aref val 1))
283 (gnugo--tree-ends val)))
284 (:monkey
285 (let ((mem (aref val 0)))
286 (list (aref val 1)
287 (car mem))))
288 (t val)))
289 acc))
290 (switch-to-buffer (get-buffer-create
291 (format "%s*GNUGO Board Properties*"
292 (gnugo-get :diamond))))
293 (erase-buffer)
294 (emacs-lisp-mode)
295 (setq truncate-lines t)
296 (save-excursion
297 (pp acc
298 (current-buffer))
299 (goto-char (point-min))
300 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
301 (if (string= "" d)
302 ".+\n"
303 ""))))
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))))
310
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))
314
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)))))
319
320 (defsubst gnugo--blackp (string)
321 (string= "black" string))
322
323 (defun gnugo-other (color)
324 (if (gnugo--blackp color) "white" "black"))
325
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")))
336
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
344 (list " [%s ("
345 (propertize (car (split-string string))
346 'face 'font-lock-warning-face)
347 ")]"))
348 (when (eq proc (gnugo-get :proc))
349 (gnugo-put :proc nil))))))))
350
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"))
357
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)
371 string)))
372 (process-put proc :srs full)
373 (unless (numberp (gnugo--compare-strings
374 full (max 0 (- (length full)
375 2))
376 "\n\n" nil))
377 (process-put proc :incomplete nil))))
378 (if (null args)
379 fmt
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 ""))))
385
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)
392 2))
393
394 (defun gnugo-lsquery (message-format &rest args)
395 (split-string (apply 'gnugo-query message-format args)))
396
397 (defun gnugo--root-node (&optional tree)
398 (aref (or tree (gnugo-get :sgf-gametree))
399 3))
400
401 (defsubst gnugo--root-prop (prop &optional tree)
402 (cdr (assq prop (gnugo--root-node tree))))
403
404 (defun gnugo--set-root-prop (prop value &optional tree)
405 (let* ((root (gnugo--root-node tree))
406 (cur (assq prop root)))
407 (if cur
408 (setcdr cur value)
409 (push (cons prop value)
410 (cdr (last root))))))
411
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))))
417 (forward-char 1)
418 (forward-char (+ (if (= 32 (following-char)) 1 2)
419 (* 2 (- (let ((letter (aref pos 0)))
420 (if (> ?I letter)
421 letter
422 (1- letter)))
423 ?A)))))
424
425 (defun gnugo-f (frag)
426 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
427
428 (defun gnugo-yang (c)
429 (cdr (assq c '((?+ . hoshi)
430 (?. . empty)
431 (?X . (bmoku . bpmoku))
432 (?O . (wmoku . wpmoku))))))
433
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))
438 (t yang)))))
439
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)))
452 (mapc (lambda (yy)
453 (setcar (symbol-plist yy) act))
454 (or (gnugo-get :all-yy)
455 (gnugo-put :all-yy
456 (prog1 (mapcar (lambda (ent)
457 (let* ((k (car ent))
458 (yy (gnugo-yy (cdr k) (car k))))
459 (setplist yy `(not-yet ,(cdr ent)))
460 yy))
461 (gnugo-get :xpms))
462 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
463 'not-yet))))
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
468 (if new
469 '((lambda (p)
470 (get (gnugo-yy (get-text-property p 'gnugo-yin)
471 (get-text-property p 'gnugo-yang)
472 t)
473 'display))
474 0 delete-overlay)
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)))
483
484 (defun gnugo-toggle-grid ()
485 "Turn the grid around the board on or off."
486 (interactive)
487 (funcall (if (memq :nogrid buffer-invisibility-spec)
488 'remove-from-invisibility-spec
489 'add-to-invisibility-spec)
490 :nogrid)
491 (save-excursion (gnugo-refresh)))
492
493 (defun gnugo-propertize-board-buffer ()
494 (erase-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)
510 (forward-char 1)
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))
514 (edge (match-end 0))
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)))
520 (nR (- edge 1))
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)))
531 ((< other-edge p))
532 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
533 (truncate (- p edge) 2))
534 row))
535 (yin (let ((A-p (= edge p))
536 (Z-p (= (1- other-edge) p)))
537 (cond ((and top-p A-p) 1)
538 ((and top-p Z-p) 3)
539 ((and bot-p A-p) 7)
540 ((and bot-p Z-p) 9)
541 (top-p 2)
542 (bot-p 8)
543 (A-p 4)
544 (Z-p 6)
545 (t 5))))
546 (yang (gnugo-yang (char-after p))))
547 (add-text-properties p (1+ p)
548 `(gnugo-position
549 ,position
550 gnugo-yin
551 ,yin
552 gnugo-yang
553 ,yang
554 category
555 ,(gnugo-yy yin yang)
556 front-sticky
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))
565 :white-captures
566 :black-captures))
567 (beg (match-beginning 2))
568 (end (match-end 2)))
569 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
570 (gnugo-put prop (match-string-no-properties 2))))
571 (end-of-line)
572 (put-text-property right-empty (point) 'category %rpad)
573 (forward-char 1)))
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))
578 'category %gspc)))
579
580 (defun gnugo-merge-showboard-results ()
581 (let ((aft (substring (gnugo--q "showboard") 3))
582 (adj 1) ; string to buffer position adjustment
583
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:
587 ;;
588 ;; (before)
589 ;; ... WHITE has captured 1 stones
590 ;; ^
591 ;; (after)
592 ;; ... WHITE has captured 14 stones
593 ;; ^
594 ;;
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).
599
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
605 bef bef-start
606 aft aft-start)))
607 (setq aft-sync-backtrack nil
608 inc (if (cl-minusp mis)
609 (- (+ 1 mis))
610 (- mis 1))
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))
614 (match-end 0)
615 (1+ 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))))
621 (match-end 0)
622 (1+ aft-idx))
623 cut (+ bef-idx adj
624 (if aft-sync-backtrack
625 (- aft-sync-backtrack aft-idx)
626 0)))
627 (goto-char cut)
628 (if aft-sync-backtrack
629 (let* ((asb aft-sync-backtrack)
630 (l-p (get-text-property cut :gnugo-cf))
631 (old-len (car l-p))
632 (capprop (cdr l-p))
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)
645 `(gnugo-yang
646 ,yang
647 category
648 ,(gnugo-yy yin yang))))
649 (delete-char 1)
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))))))
654
655 (defsubst gnugo--move-prop (node)
656 (or (assq :B node)
657 (assq :W node)))
658
659 (defun gnugo--as-pos-func (size)
660 (lexical-let ((size size))
661 ;; rv
662 (lambda (cc)
663 (if (string= "" cc)
664 "PASS"
665 (let ((col (aref cc 0)))
666 (format "%c%d"
667 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
668 (- size (- (aref cc 1) ?a))))))))
669
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.
680
681 For all other values of RSEL, do nothing and return nil."
682 (interactive "P")
683 (let* ((monkey (gnugo-get :monkey))
684 (mem (aref monkey 0))
685 (as-pos (gnugo--as-pos-func (gnugo-get :SZ)))
686 col
687 acc node mprop move)
688 (cl-flet*
689 ((as-pos-maybe (x) (if (string= "resign" x)
690 x
691 (funcall as-pos x)))
692 (next (byp) (when (setq node (pop mem)
693 mprop (gnugo--move-prop node))
694 (setq move (as-pos-maybe (cdr mprop)))
695 (push (if byp
696 (format "%s%s" move (car mprop))
697 move)
698 acc)))
699 (nn () (next nil))
700 (tell () (message "(%d moves) %s"
701 (length acc)
702 (mapconcat 'identity (nreverse acc) " ")))
703 (finish (byp) (while mem (next byp)) (tell)))
704 (pcase rsel
705 (`(4) (finish t))
706 (`nil (finish nil))
707 (`car (car (nn)))
708 (`cadr (nn) (car (nn)))
709 (`count (gethash (car mem) (gnugo--tree-mnum
710 (gnugo-get :sgf-gametree))))
711 (`two (nn) (nn) acc)
712 (_ nil)))))
713
714 (defun gnugo-frolic-in-the-leaves ()
715 "Display the game tree in a *GNUGO Frolic* buffer.
716 This looks something like:
717
718 1 B -- E7 E7 E7 E7
719 2 W -- K10 K10 K10 K10
720 3 B -- E2 E2 E2 E2
721 4 W -- J3 J3 J3 J3
722 5 B -- A6 A6 A6 A6
723 6 W -- C9 C9 C9 C9
724
725 ├─────┬─────┐
726 │ │ │
727 7 B -- H7 B8 C8 C8
728
729 ├─────┐
730 │ │
731 8 W -- D9 D9 D9 E9
732 9 B -- H8 H8
733 10 W -- PASS PASS
734 11 B -- H5 PASS
735 12 W -- PASS
736 13 B -- *PASS
737
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."
743 (interactive)
744 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
745 "*GNUGO Frolic*")))
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))
752 (seen (gnugo--mkht))
753 (soil (gnugo--mkht))
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))
762 mnum)))
763 (eert (make-vector width nil))
764 finish)
765 (cl-flet
766 ((on (node)
767 (gethash node seen))
768 (emph (s face)
769 (propertize s 'face face))
770 (fsi (fmt &rest args)
771 (insert (apply 'format fmt args))))
772 ;; breathe in
773 (let ((monkey-on-main-line (zerop bidx))
774 fixup)
775 ;; monkey knows a lot
776 (loop with acc
777 for node in (aref monkey 0)
778 do (puthash node bidx seen)
779 if (gnugo--move-prop node)
780 do (push node acc)
781 finally do (progn
782 (unless monkey-on-main-line
783 (setq fixup (apply 'vector acc)))
784 (aset eert bidx acc)))
785 ;; but monkey does not know everything
786 (loop
787 for bx below width
788 do (loop
789 with (bef acc node fork cur)
790 for ls on (aref ends bx)
791 do (if (setq node (car ls)
792 fork (on node))
793 (cl-flet
794 ((link (other)
795 (push other (gethash node soil))))
796 (let ((move-num (gethash node mnum)))
797 (when (< bx fork)
798 (assert (and (not monkey-on-main-line)
799 (= fork bidx)))
800 (loop for old in ls
801 while (< bx (on old))
802 do (puthash old bx seen))
803 (when (< move-num (length fixup))
804 (link (aref fixup move-num))))
805 ;; ugh, wasteful
806 (when (setq bef (copy-sequence (aref eert fork)))
807 (setcdr (nthcdr (1- move-num) bef)
808 acc))
809 (aset eert bx (or bef acc))
810 (when acc
811 (link (car acc)))))
812 (puthash node bx seen)
813 (when (gnugo--move-prop node)
814 (push node acc)))
815 until fork)))
816 ;; breathe out
817 (switch-to-buffer buf)
818 (when view-mode
819 (view-mode -1))
820 (buffer-disable-undo)
821 (erase-buffer)
822 (setq header-line-format
823 (concat (make-string 11 ?\s)
824 (mapconcat (lambda (n)
825 (format "%-5s" n))
826 lanes
827 " ")))
828 (loop
829 for n ; move number
830 from 1 upto max-move-num
831 do
832 (loop
833 with (move forks br)
834 initially (fsi "%3d %s -- "
835 n (aref ["W" "B"] (logand 1 n)))
836 for bx below width
837 do (let* ((node (pop (aref eert bx)))
838 (ok (when node
839 (= bx (on node))))
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)))
847 (push bx br))
848 ;; do not point w/ a fist
849 (when br
850 (push (cons bx (sort br '<))
851 forks)))
852 (fsi " %-5s"
853 (cond ((and (eq at node)
854 (or ok (= bx bidx)))
855 (when (= bx bidx)
856 (setq finish (point)))
857 (emph s (list :inherit 'default
858 :foreground (frame-parameter
859 nil 'cursor-color))))
860 ((not ok)
861 (emph s dimmed-node-face))
862 (t s))))
863 finally do
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)))
870 (cl-flet*
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 "-----"))
878 (cnxn (lanes set)
879 (spaced lanes (lambda (bx)
880 (if (memq bx set)
881 "|"
882 " "))))
883 (pad-unless (condition)
884 (if condition
885 ""
886 " "))
887 (edge (set)
888 (insert margin
889 (cnxn lanes set)
890 "\n")))
891 (edge heads)
892 (loop with bef
893 for ls on forks
894 do (let* ((one (car ls))
895 (yes (append
896 ;; "aft" heads
897 (mapcar 'car (cdr ls))
898 ;; ‘bef’ tails
899 (apply 'append (mapcar 'cdr bef))))
900 (ord (sort one '<))
901 (beg (car ord))
902 (end (car (last ord))))
903 (cl-flet
904 ((also (b e) (cnxn (number-sequence b e)
905 yes)))
906 (insert
907 margin
908 (also 0 (1- beg))
909 (pad-unless (zerop beg))
910 (dashed (number-sequence beg end)
911 (lambda (bx)
912 (cond ((memq bx ord) "+")
913 ((memq bx yes) "|")
914 (t "-"))))
915 (pad-unless (>= end width))
916 (also (1+ end) (1- width))
917 "\n"))
918 (push one bef)))
919 (edge (apply 'append tails))
920 (aa2u (line-beginning-position
921 (- (1+ (length forks))))
922 (point))))))))
923 (when finish
924 (goto-char finish)
925 (recenter (- (count-lines (line-beginning-position) (point-max)))))
926 (view-mode 1)))
927
928 (defun gnugo-boss-is-near ()
929 "Do `bury-buffer' until the current one is not a GNU Board."
930 (interactive)
931 (while (gnugo-board-buffer-p)
932 (bury-buffer)))
933
934 (defsubst gnugo--passp (string)
935 (string= "PASS" string))
936
937 (defsubst gnugo--no-regrets (monkey ends)
938 (eq (aref ends (aref monkey 1))
939 (aref monkey 0)))
940
941 (defun gnugo-note (property value &optional mogrifyp)
942 (when mogrifyp
943 (let ((sz (gnugo-get :SZ)))
944 (cl-flet
945 ((mog (pos) (if (gnugo--passp pos)
946 ""
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)
953 (mapcar #'mog value)
954 (mog value))))))
955 (let* ((pair (cons property value))
956 (fruit (list pair))
957 (monkey (gnugo-get :monkey))
958 (mem (aref monkey 0))
959 (tip (car mem)))
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:
966 ;;
967 ;; X---Y---A new
968 ;; \
969 ;; --A---B old
970 ;;
971 ;; (such "variations" do not actually vary!) in favor of:
972 ;;
973 ;; X---Y---A new
974 ;; \
975 ;; --B old
976 (loop
977 with count = (length ends)
978 with (bx previous)
979 for i
980 ;; Start with latest / highest likelihood for hit.
981 ;; todo: prune unfeasible candidates
982 from (if (gnugo--no-regrets monkey ends)
983 1
984 0)
985 below count
986 if (setq bx (mod (+ bidx i) count)
987 previous
988 ;; todo: early termination based on move number
989 (loop for m on (aref ends bx)
990 if (eq mem (cdr m))
991 return
992 (when (equal pair (assoc property (car m)))
993 m)
994 finally return
995 nil))
996 ;; yes => follow
997 return
998 (progn
999 (unless (= bidx bx)
1000 (rotatef (aref ends bidx)
1001 (aref ends bx)))
1002 (setq mem previous))
1003 ;; no => construct
1004 finally do
1005 (progn
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)
1015 (push fruit mem)
1016 (aset ends bidx mem)))
1017 (setf (aref monkey 0) mem))
1018 (setcdr (last tip) fruit))))
1019
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)
1024 (cadr now))))
1025 (gnugo-put :game-over
1026 (if (or (eq t resign)
1027 (and (stringp resign)
1028 (string-match "[BW][+][Rr]esign" resign)))
1029 (cl-flet
1030 ((ls (color) (mapcar
1031 (lambda (x)
1032 (cons (list color)
1033 (split-string x)))
1034 (split-string
1035 (gnugo-query "worm_stones %s" color)
1036 "\n"))))
1037 (let ((live (append (ls "black") (ls "white"))))
1038 `((live ,@live)
1039 (dead))))
1040 (let ((dd (gnugo-query "dragon_data"))
1041 (start 0) mem color ent live dead)
1042 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1043 dd start)
1044 (setq mem (match-string 1 dd)
1045 color (match-string 2 dd)
1046 start (match-end 0)
1047 ent (cons (list color)
1048 (sort (gnugo-lsquery "dragon_stones %s" mem)
1049 'string<)))
1050 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1051 dd start)
1052 (if (match-string 2 dd)
1053 (push ent live)
1054 (push ent dead))
1055 (setq start (match-end 0)))
1056 `((live ,@live)
1057 (dead ,@dead))))))
1058
1059 (defun gnugo--unclose-game ()
1060 (dolist (prop '(:game-over ; all those in -close-game
1061 :scoring-seed
1062 :game-end-time))
1063 (gnugo-put prop nil))
1064 (let* ((root (gnugo--root-node))
1065 (cur (assq :RE root)))
1066 (when cur
1067 (assert (not (eq cur (car root))) nil
1068 ":RE at head of root node: %S"
1069 root)
1070 (delq cur root))))
1071
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))))
1081 (unless passp
1082 (gnugo-merge-showboard-results))
1083 (gnugo-put :last-mover color)
1084 (when userp
1085 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1086 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
1087 (when start
1088 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1089 (when donep
1090 (gnugo-close-game now resignp))
1091 (gnugo-put :waiting-start (and (not donep) now))
1092 donep))
1093
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))
1103 (bop (lambda (s)
1104 (let* ((start 0)
1105 (ncolors
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)
1114 (match-end 0))))
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
1120 (while (< sx lx)
1121 (when (and (not (= color-key (aref new sx)))
1122 (cl-plusp (random 4)))
1123 (aset new sx (aref bg-data sb)))
1124 (incf sx)
1125 (incf sb))
1126 (create-image new 'xpm t :ascent 'center)))
1127
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.
1135
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
1139 its move."
1140 (interactive "P")
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))
1147 window last)
1148 ;; last move
1149 (when move
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)
1155 (let* ((p (point))
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)
1164 display-value))
1165 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1166 (if r-action
1167 (funcall r-action r-ov)
1168 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1169 ;; buffer name
1170 (rename-buffer (concat (gnugo-get :diamond)
1171 (if game-over
1172 (format "%s(game over)"
1173 (if (string= move "resign")
1174 (concat move "ation ")
1175 ""))
1176 (format "%s(%s to play)"
1177 (if move (concat move " ") "")
1178 other))))
1179 ;; pall of death
1180 (when game-over
1181 (let ((live (cdr (assq 'live game-over)))
1182 (dead (cdr (assq 'dead game-over)))
1183 p pall)
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)
1188 (setq p (point))
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)))
1202 (overlay-put
1203 ov 'display
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)))
1210 (push ov pall))
1211 (setcdr (car group) pall))))))
1212 ;; window update
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))
1219 (if gridp 2 0))
1220 2)
1221 (if gridp 0 1)))
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
1228 (* size wmul)
1229 (if imagesp
1230 0
1231 (1- size))
1232 2 ; between board and grid
1233 (if gridp
1234 (if under10p 2 4)
1235 0))
1236 2.0)))
1237 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1238 `(display ,(make-string h 10))
1239 '(invisible :nogrid)))
1240 (gpad . (display
1241 (space :align-to
1242 ,(+ w
1243 2.0
1244 (cond (imagesp (+ (* 0.5 wmul)
1245 (if under10p
1246 -0.5
1247 0.5)))
1248 (under10p 0)
1249 (t 1))))))
1250 (gspc . ,(when imagesp
1251 `(display
1252 (space-width
1253 ,(-
1254 ;; DWR: image width alone => OBOE!
1255 ;;- wmul
1256 ;; NB: ‘(* wmul cw)’ is the same
1257 ;; as ‘(car (image-size ... t))’.
1258 (let ((cw (frame-char-width)))
1259 (/ (+ 1.0 (* wmul cw))
1260 cw))
1261 1.0)))))
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
1268 ;; column A.
1269 (if gridp
1270 `(before-string
1271 ,(apply 'propertize " " d))
1272 d)))
1273 (rpad . (display
1274 (space :align-to ,(1- avail-width))))))
1275 (setplist (gnugo-f (car pair)) (cdr pair)))))
1276 ;; mode line update
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))
1284 (let (acc cut c)
1285 (while (setq cut (string-match "~[bwpmtu]" cur))
1286 (aset cur cut ?%)
1287 (setq c (aref cur (incf cut)))
1288 (aset cur cut ?s)
1289 (push
1290 `(,(intern (format "squig-%c" c))
1291 ,(case 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)))
1296 (if ws
1297 (cadr (time-since ws))
1298 "-")))
1299 (?u '(or (gnugo-get :last-waiting) "-"))
1300 (?m '(gnugo-move-history 'count))))
1301 acc))
1302 `(let ,(delete-dups (copy-sequence acc))
1303 (format ,cur ,@(reverse (mapcar 'car acc))))))
1304 (t cur))))
1305 (let ((form (gnugo-get :mode-line-form)))
1306 (setq mode-line-process
1307 (and form
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))
1313 ;; last user move
1314 (when (setq last (gnugo-get :last-user-bpos))
1315 (gnugo-goto-pos last))))
1316
1317 ;;;---------------------------------------------------------------------------
1318 ;;; Game play actions
1319
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))))))))))
1335
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))
1342
1343 (defun gnugo-cleanup ()
1344 (when (gnugo-board-buffer-p)
1345 (unless (zerop (buffer-size))
1346 (message "Thank you for playing GNU Go."))
1347 (mapc (lambda (sym)
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...
1351 (unintern sym nil))
1352 (append (gnugo-get :all-yy)
1353 (mapcar 'gnugo-f
1354 '(anim
1355 tpad
1356 gpad
1357 gspc
1358 lpad
1359 rpad
1360 ispc))))
1361 (setq gnugo-state nil)))
1362
1363 (defun gnugo-position ()
1364 (or (get-text-property (point) 'gnugo-position)
1365 (user-error "Not a proper position point")))
1366
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."
1372 (interactive)
1373 (gnugo-gate t)
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
1385 (gnugo-refresh))))
1386 (with-current-buffer buf
1387 (gnugo-get-move (gnugo-get :gnugo-color)))))
1388
1389 (defun gnugo-mouse-move (e)
1390 "Do `gnugo-move' at mouse location."
1391 (interactive "@e")
1392 (mouse-set-point e)
1393 (when (looking-at "[.+]")
1394 (gnugo-move)))
1395
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."
1400 (interactive)
1401 (gnugo-gate t)
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
1411 (gnugo-refresh))))
1412 (unless donep
1413 (with-current-buffer buf
1414 (gnugo-get-move (gnugo-get :gnugo-color))))))
1415
1416 (defun gnugo-mouse-pass (e)
1417 "Do `gnugo-pass' at mouse location."
1418 (interactive "@e")
1419 (mouse-set-point e)
1420 (gnugo-pass))
1421
1422 (defun gnugo-resign ()
1423 (interactive)
1424 (gnugo-gate t)
1425 (if (not (y-or-n-p "Resign? "))
1426 (message "(not resigning)")
1427 (gnugo-push-move t "resign")
1428 (gnugo-refresh)))
1429
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))
1434 blurb stones)
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))
1448 dn up))
1449 (split-string gnugo-animation-string "" t)))
1450 (cell (list spec))
1451 (ovs (save-excursion
1452 (mapcar (lambda (pos)
1453 (gnugo-goto-pos pos)
1454 (let* ((p (point))
1455 (ov (make-overlay p (1+ p))))
1456 (overlay-put ov 'category (gnugo-f 'anim))
1457 (overlay-put ov 'priority most-positive-fixnum)
1458 ov))
1459 stones))))
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))
1466 (sit-for 5)
1467 (mapc 'delete-overlay ovs)
1468 t)))
1469
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)
1474 (erase-buffer)
1475 (insert data))
1476 (message "Computing %s ... done." command))
1477
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."
1482 (interactive)
1483 (gnugo-gate)
1484 (gnugo-animate-group 'worm))
1485
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."
1489 (interactive)
1490 (gnugo-gate)
1491 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1492
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."
1497 (interactive)
1498 (gnugo-gate)
1499 (gnugo-animate-group 'dragon))
1500
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."
1504 (interactive)
1505 (gnugo-gate)
1506 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1507
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.
1512
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.
1521
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."
1525 (interactive)
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)
1532 (cadr now)))
1533 (let ((live (assq 'live game-over))
1534 (dead (assq 'dead game-over))
1535 bef now)
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
1542 (when nil
1543 (cl-flet
1544 ((populate (group)
1545 (let ((color (caar group)))
1546 (dolist (stone (cdr group))
1547 (gnugo-query "play %s %s" color stone)))))
1548 (if (eq now live)
1549 (populate group)
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)
1554 (when nil
1555 (gnugo-query "change_dragon_status %s %s"
1556 (cadr group) (if (eq now live)
1557 'alive
1558 'dead)))))
1559 (save-excursion
1560 (gnugo-refresh)))
1561
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)."
1567 (interactive)
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)))
1579
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))
1589
1590 (defun gnugo--who-is-who (wait play samep)
1591 (message "GNU Go %splays as %s, you as %s (%s)"
1592 (if samep "" "now ")
1593 wait play (if samep
1594 "as before"
1595 "NOTE: this is a switch!")))
1596
1597 (defsubst gnugo--nodep (x)
1598 (keywordp (caar x)))
1599
1600 (defsubst gnugo--SZ! (size)
1601 (gnugo-put :SZ size))
1602
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)))
1613 0))
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)
1619 (unless samep
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)))
1624 ;; This is better:
1625 ;; (if (= 1 n)
1626 ;; 0
1627 ;; (let* ((q (format "Which game? (1-%d)" n))
1628 ;; (choice (1- (read-number q 1))))
1629 ;; (if (and (< -1 choice) (< choice n))
1630 ;; choice
1631 ;; (message "(Selecting the first game)")
1632 ;; 0)))
1633 ;; but this is what we use (for now) to accomodate
1634 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1635 (unless (= 1 n)
1636 (message "(Selecting the first game)"))
1637 0)
1638 coll))
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))
1644 (let (game-over)
1645 (gnugo-put :game-over
1646 (setq game-over
1647 (or (gnugo--root-prop :RE tree)
1648 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1649 'two-passes))))
1650 (when (and game-over
1651 ;; (maybe) todo: user var to inhibit (can be slow)
1652 t)
1653 (gnugo-close-game nil game-over)))
1654 (gnugo-refresh t)
1655 (set-buffer-modified-p nil)
1656 (gnugo--who-is-who wait play samep)))
1657
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.
1668
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.
1672
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.
1675
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)
1678 when play resumes."
1679 (gnugo-gate)
1680 (let* ((n 0)
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)))
1686 done ans)
1687 (cond ((numberp spec)
1688 (setq n (if (zerop spec)
1689 (if (string= user-color (gnugo-get :last-mover))
1690 1
1691 2)
1692 spec)
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)
1703 (following-char))
1704 (if (gnugo--blackp user-color)
1705 ?O
1706 ?X))
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
1719 (decf n) ; is
1720 (redisplay)) ; eye candy
1721 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1722
1723 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1724 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1725 ubpos
1726 (gnugo-get :center-position)))
1727 (gnugo-refresh t)
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))))))
1732
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]
1742
1743 See also `gnugo-undo-two-moves'."
1744 (interactive "P")
1745 (gnugo-gate)
1746 (gnugo-magic-undo 1 t)
1747 (when me-next
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))))
1753
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."
1758 (interactive)
1759 (gnugo-gate)
1760 (gnugo-magic-undo 0))
1761
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]'."
1767 (interactive "P")
1768 (gnugo-gate)
1769 (gnugo-magic-undo (if position
1770 (gnugo-position)
1771 0)
1772 nil t))
1773
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."
1779 (interactive)
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"))
1785 (unless game-over
1786 (cl-flet
1787 ((pass (userp)
1788 (message "Playing PASS for %s ..."
1789 (gnugo-get (if userp :user-color :gnugo-color)))
1790 (sit-for 1)
1791 (gnugo-push-move userp "PASS")))
1792 (unless (pass t)
1793 (pass nil)))
1794 (gnugo-refresh)
1795 (sit-for 3)))
1796 (let ((b= " Black = ")
1797 (w= " White = ")
1798 (res (when (string= "resign" (gnugo-move-history 'car))
1799 (gnugo-get :last-mover)))
1800 blurb result)
1801 (if res
1802 (setq blurb (list
1803 (format "%s wins.\n"
1804 (substring (if (= ?b (aref res 0)) w= b=)
1805 3 8))
1806 "The game is over.\n"
1807 (format "Resignation by %s.\n" res))
1808 result (concat (upcase (substring (gnugo-other res) 0 1))
1809 "+Resign"))
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))
1816 (terr "territory")
1817 (capt "captures")
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))
1828 b-terr
1829 w-terr)
1830 (length (cdr group))))
1831 (dolist (group dead)
1832 (incf (if (gnugo--blackp (caar group))
1833 w-terr
1834 b-terr)
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))
1839 blurb))
1840 (t
1841 (dolist (group dead)
1842 (incf (if (gnugo--blackp (caar group))
1843 w-terr
1844 b-terr)
1845 (* 2 (length (cdr group)))))
1846 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1847 b-terr terr
1848 b-capt capt
1849 (+ b-terr b-capt))
1850 blurb)
1851 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1852 w-terr terr
1853 w-capt capt
1854 komi 'komi
1855 (+ w-terr w-capt komi))
1856 blurb)))
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)))
1862 blurb)
1863 (message "Computing final score ... done")))
1864 ;; extra info
1865 (let ((beg (gnugo-get :game-start-time))
1866 (end (gnugo-get :game-end-time)))
1867 (when end
1868 (push "\n" blurb)
1869 (cl-flet
1870 ((yep (pretty moment)
1871 (push (format-time-string
1872 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
1873 moment)
1874 blurb)))
1875 (yep "Game start" beg)
1876 (yep " end" end))))
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)))
1880 (erase-buffer)
1881 (insert blurb)))
1882
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."
1886 (interactive)
1887 (if (or (gnugo-get :game-over)
1888 (y-or-n-p "Quit? "))
1889 (kill-buffer nil)
1890 (message "(not quitting)")))
1891
1892 (defun gnugo-leave-me-alone ()
1893 "Kill the current buffer unconditionally."
1894 (interactive)
1895 (kill-buffer nil))
1896
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."
1902 (interactive "P")
1903 (gnugo-magic-undo
1904 ;; TODO: Move this into `gnugo-magic-undo' proper.
1905 (cond ((numberp count) count)
1906 ((consp count) (car count))
1907 (t (gnugo-position)))))
1908
1909 (defun gnugo-toggle-image-display-command () ; ugh
1910 "Toggle use of images to display the board, then refresh."
1911 (interactive)
1912 (gnugo-toggle-image-display)
1913 (save-excursion (gnugo-refresh)))
1914
1915 (defun gnugo-describe-position ()
1916 "Display the board position under cursor in the echo area."
1917 (interactive)
1918 (message "%s" (gnugo-position)))
1919
1920 (defun gnugo-switch-to-another ()
1921 "Switch to another GNU Go game buffer (if any)."
1922 (interactive)
1923 (loop for buf in (cdr (buffer-list))
1924 if (gnugo-board-buffer-p buf)
1925 return (progn
1926 (bury-buffer)
1927 (switch-to-buffer buf))
1928 finally do (message "(only one)")))
1929
1930 ;;;---------------------------------------------------------------------------
1931 ;;; Command properties and gnugo-command
1932
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:
1937 ;;
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.
1941 ;;
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'.
1949 ;;
1950 ;; :post-thunk -- run after output processing (at the very end).
1951
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).
1959
1960 For example, for the command \"help\", Emacs visits the
1961 GTP command reference info page.
1962
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)))
1972 (if 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)
1978 (message "%s" ans)
1979 (cond ((functionp where) (funcall where ans))
1980 ((eq :discard where) (message ""))
1981 ((or (eq :message where)
1982 (not (string-match "\n" ans)))
1983 (message "%s" ans))
1984 (t (switch-to-buffer "*gnugo command output*")
1985 (erase-buffer)
1986 (insert ans)
1987 (message "Doing %s ... done." command)))
1988 (let ((thunk (plist-get spec :post-thunk)))
1989 (when thunk (funcall thunk)))))))))
1990
1991 ;;;---------------------------------------------------------------------------
1992 ;;; Major mode for interacting with a GNUGO subprocess
1993
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.
1999
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"
2009 truncate-lines t)
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'
2017 :waitingp
2018 :last-waiting
2019 :black-captures
2020 :white-captures
2021 :mode-line
2022 :mode-line-form
2023 :display-using-images
2024 :xpms
2025 :local-xpms
2026 :all-yy))
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))
2037 o))))
2038 (push (concat o " " h) gnugo-option-history))
2039 p)
2040 gnugo-program))
2041 (args (read-string "GNU Go options: "
2042 (car gnugo-option-history)
2043 'gnugo-option-history))
2044 proc
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")
2050 (komi 0.0 "--komi")
2051 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2052 (infile nil "--infile" "[ ]*[^ ]+"))
2053 do (set var
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))))
2059 default)))
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"
2066 proc-args))))
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)
2071 (loop for (prop q)
2072 in '((board-size "query_boardsize")
2073 (komi "get_komi")
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 ")")
2083 ov))
2084 (let* ((coll (gnugo/sgf-create "(;FF[4]GM[1])" t))
2085 (tree (car coll)))
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
2092 `((:SZ ,board-size)
2093 (:DT ,(format-time-string "%Y-%m-%d"))
2094 (:RU ,(if (string-match "--chinese-rules" args)
2095 "Chinese"
2096 "Japanese"))
2097 (:AP ("gnugo.el" . ,gnugo-version))
2098 (:KM ,komi)
2099 (,(if gb :PW :PB) ,(user-full-name))
2100 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
2101 ,@(when (not (zerop handicap))
2102 `((:HA ,handicap)
2103 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
2104 t))))
2105 do (gnugo-note property value mogrifyp)))
2106 (gnugo-put :waiting-start (current-time))
2107 (gnugo-put :hmul 1)
2108 (gnugo-put :wmul 1)
2109 (run-hooks 'gnugo-board-mode-hook)
2110 (gnugo-refresh t))
2111
2112 ;;;---------------------------------------------------------------------------
2113 ;;; Entry point
2114
2115 ;;;###autoload
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
2119 game straight away.
2120 \\<gnugo-board-mode-map>
2121 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2122
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:
2126
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)
2130
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."
2133 (interactive "P")
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)))
2138 acc))
2139 (n (length all)))
2140 (if (and (not new-game)
2141 (cl-plusp n)
2142 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2143 (if (= 1 n) "" "s"))))
2144 ;; resume
2145 (switch-to-buffer
2146 (cdr (if (= 1 n)
2147 (car all)
2148 (let ((sel (completing-read "Which one? " all nil t)))
2149 (if (string= "" sel)
2150 (car all)
2151 (assoc sel all))))))
2152 ;; set up a new board
2153 (gnugo-board-mode)
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))))
2160 ;; first move
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)
2169 (gnugo-refresh t)
2170 (gnugo-get-move g))))))
2171
2172 ;;;---------------------------------------------------------------------------
2173 ;;; Load-time actions
2174
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)
2182 (" " . gnugo-move)
2183 ("P" . gnugo-pass)
2184 ("R" . gnugo-resign)
2185 ("q" . gnugo-quit)
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)
2191 ("o" . gnugo-oops)
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)
2214 ;; mouse
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))))
2220
2221 (unless (get 'help :gnugo-gtp-command-spec)
2222 (cl-flet*
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))
2227 (let ((ls props))
2228 (while ls
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)
2234 ,@body))))
2235
2236 (deffull help
2237 (info "(gnugo)GTP command reference")
2238 (when sel (setq sel (intern (car sel))))
2239 (let (buffer-read-only pad cur spec output found)
2240 (cl-flet
2241 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2242 (goto-char (point-min))
2243 (save-excursion
2244 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2245 (point-max) t)
2246 (unless pad
2247 (setq pad (make-string (- (match-beginning 1)
2248 (match-beginning 0))
2249 32)))
2250 (when (plist-get
2251 (setq spec
2252 (get (setq cur (intern (match-string 1)))
2253 :gnugo-gtp-command-spec))
2254 :full)
2255 (note "handles this command completely"))
2256 (when (setq output (plist-get spec :output))
2257 (if (functionp output)
2258 (note "handles the output specially")
2259 (case output
2260 (:discard (note "discards the output"))
2261 (:message (note "displays the output in the echo area")))))
2262 (when (eq sel cur)
2263 (setq found (match-beginning 0))))))
2264 (cond (found (goto-char found))
2265 ((not sel))
2266 (t (message "(no such command: %s)" sel)))))
2267
2268 (deffull final_score
2269 (gnugo-display-final-score))
2270
2271 (defgtp '(boardsize
2272 clear_board
2273 fixed_handicap)
2274 :output :discard
2275 :post-thunk (lambda ()
2276 (gnugo--unclose-game)
2277 (gnugo-put :last-mover nil)
2278 ;; ugh
2279 (gnugo--SZ! (string-to-number
2280 (gnugo-query
2281 "query_boardsize")))
2282 (gnugo-refresh t)))
2283
2284 (deffull loadsgf
2285 (gnugo-read-sgf-file (car sel)))
2286
2287 (deffull (undo gg-undo)
2288 (gnugo-magic-undo
2289 (let (n)
2290 (cond ((not sel) 1)
2291 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2292 (t (car sel)))))))))
2293
2294 (provide 'gnugo)
2295
2296 \f
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.
2302
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)
2338 (KO "Ko" move none)
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)
2370 (V "Value" - real)
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...).")
2381
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:
2388
2389 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2390 have a move number of the previous \"move\" node (or zero)
2391
2392 KIDS -- `eq' hash: node to node list (branch points only)
2393
2394 ENDS -- a vector of node lists, with shared tails
2395 (last element of all the lists is the root node)
2396
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)
2402 (cons (car 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*))))
2410 SZ)
2411 (cl-labels
2412 ((sw () (skip-chars-forward " \t\n"))
2413 (x (end) (let ((beg (point))
2414 (endp (case end
2415 (:end (lambda (char) (= ?\] char)))
2416 (:mid (lambda (char) (= ?\: char)))
2417 (t (lambda (char) (or (= ?\: char)
2418 (= ?\] char))))))
2419 c)
2420 (while (not (funcall endp (setq c (following-char))))
2421 (cond ((= ?\\ c)
2422 (delete-char 1)
2423 (if (eolp)
2424 (kill-line 1)
2425 (forward-char 1)))
2426 ((looking-at "\\s-+")
2427 (delete-region (point) (match-end 0))
2428 (insert " "))
2429 (t (forward-char 1))))
2430 (buffer-substring-no-properties beg (point))))
2431 (one (type end) (let ((s (progn
2432 (forward-char 1)
2433 (x end))))
2434 (case type
2435 ((stone point move)
2436 ;; blech, begone bu"tt"-ugly blatherings
2437 ;; (but bide brobdingnagian boards)...
2438 (if (and (string= "tt" s)
2439 SZ
2440 (>= 19 SZ))
2441 ""
2442 s))
2443 ((simpletext color) s)
2444 ((number real double) (string-to-number s))
2445 ((text) s)
2446 ((none) "")
2447 (t (error "Unhandled type: %S" type)))))
2448 (val (spec) (cond ((symbolp spec)
2449 (one spec :end))
2450 ((vectorp 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))
2456 v
2457 (forward-char 1)
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)))
2475 (sw)
2476 (cons
2477 (cdr (assq name keywords))
2478 (prog1 (if (= 1 (length spec))
2479 (val (car spec))
2480 (unless (memq (setq ltype (car spec))
2481 '(elist list))
2482 (error "Bad spec: %S" spec))
2483 (if (and (eq 'elist ltype) (sw)
2484 (not (atvalp)))
2485 nil
2486 (let ((type (cadr spec))
2487 mo ls)
2488 (while (and (sw) (atvalp)
2489 (setq mo (val type)))
2490 (push mo ls)
2491 (forward-char 1))
2492 (forward-char -1)
2493 (nreverse ls))))
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)
2498 (forward-char 1)
2499 t))
2500 (NODE () (when (seek-into ?\;)
2501 (loop with prop
2502 while (setq prop (PROP))
2503 collect (progn
2504 (when (eq :SZ (car prop))
2505 (setq SZ (cdr prop)))
2506 prop))))
2507 (TREE (parent mnum kids)
2508 (let ((ls parent)
2509 prev node)
2510 (seek-into ?\()
2511 (while (seek ?\;)
2512 (setq prev (car ls)
2513 node (NODE))
2514 (puthash node (+ (if (gnugo--move-prop node)
2515 1
2516 0)
2517 (gethash prev mnum 0))
2518 mnum)
2519 ;; phase 2
2520 (when (listp (gethash prev kids t))
2521 (push node (gethash prev kids)))
2522 (push node
2523 ls))
2524 (prog1
2525 (if (not (seek ?\())
2526 ;; singular
2527 (list ls)
2528 ;; multiple
2529 ;; phase 1
2530 (puthash node (list) kids)
2531 (loop while (seek ?\()
2532 append (TREE ls mnum kids)))
2533 (seek-into ?\))))))
2534 (with-temp-buffer
2535 (if (not data-p)
2536 (insert-file-contents file-or-data)
2537 (insert file-or-data)
2538 (goto-char (point-min)))
2539 (loop while (morep)
2540 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2541 (kids (gnugo--mkht))
2542 (ends (TREE nil mnum kids))
2543 (root (car (last (car ends)))))
2544 (vector mnum
2545 kids
2546 (apply 'vector ends)
2547 root)))))))
2548
2549 (defun gnugo/sgf-hang-from-root (tree)
2550 (let ((ht (gnugo--mkht))
2551 (leaves (append tree nil)))
2552 (cl-flet
2553 ((hang (stack)
2554 (loop
2555 with rh ; rectified history
2556 with bp ; branch point
2557 for node in stack
2558 until (setq bp (gethash node ht))
2559 do (puthash node
2560 (push node rh) ; good for now: ½τ
2561 ht)
2562 finally return
2563 (if (not bp)
2564 ;; first run: main line
2565 rh
2566 ;; subsequent runs: grafts (value discarded)
2567 (setcdr bp (nconc
2568 ;; Maintain order of ‘leaves’.
2569 (let ((was (cdr bp)))
2570 (if (gnugo--nodep (car was))
2571 (list was)
2572 was))
2573 (list rh)))))))
2574 (setq tree (hang (pop leaves)))
2575 (mapc #'hang leaves)
2576 tree)))
2577
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)))
2583 ;; write it out
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)))
2587 (cdddr full)))
2588 gnugo/sgf-*r4-properties*))
2589 p name v spec)
2590 ;; todo: escape special chars for `text' and `simpletext'.
2591 (cl-labels
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)
2595 (insert "\n"))
2596 ((< 60 (current-column))
2597 (save-excursion
2598 (goto-char p)
2599 (insert "\n")))))
2600 (>>prop (prop)
2601 (setq p (point)
2602 name (car prop)
2603 v (cdr prop))
2604 (insert (substring (symbol-name name) 1))
2605 (cond ((not v))
2606 ((and (consp v)
2607 (setq spec (cdr (assq name specs)))
2608 (memq (car spec)
2609 '(list elist)))
2610 (>>nl)
2611 (let ((>> (if (consp (cadr spec))
2612 #'>>two
2613 #'>>one)))
2614 (dolist (little-v v)
2615 (setq p (point))
2616 (funcall >> little-v)
2617 (>>nl))))
2618 ((consp v)
2619 (>>two v) (>>nl))
2620 (t
2621 (>>one v) (>>nl))))
2622 (>>node (node)
2623 (loop initially (insert ";")
2624 for prop in node
2625 do (>>prop prop)))
2626 (>>tree (tree)
2627 (unless (zerop (current-column))
2628 (newline))
2629 (insert "(")
2630 (dolist (x tree)
2631 (funcall (if (gnugo--nodep x)
2632 #'>>node
2633 #'>>tree)
2634 x))
2635 (insert ")")))
2636 (with-temp-buffer
2637 (dolist (tree collection)
2638 (>>tree (gnugo/sgf-hang-from-root tree)))
2639 (newline)
2640 (write-file filename)))))
2641
2642 ;;; gnugo.el ends here