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