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