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