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