-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgnugo.el
2864 lines (2671 loc) · 116 KB
/
gnugo.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
;; Copyright (C) 2014-2023 Free Software Foundation, Inc.
;; Author: Thien-Thi Nguyen <[email protected]>
;; Maintainer: [email protected]
;; Version: 3.1.2
;; Package-Requires: ((ascii-art-to-unicode "1.5") (xpm "1.0.1") (cl-lib "0.5"))
;; Keywords: games, processes
;; URL: https://www.gnuvola.org/software/gnugo/
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Playing
;; -------
;;
;; This file provides the command `gnugo' which allows you to play the game of
;; go against the external program "gnugo" (https://www.gnu.org/software/gnugo)
;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
;; Go" to refer to the process object created by running the external program.
;;
;; At the start of a new game, you can pass additional command-line arguments
;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
;; default GNU Go plays at level 10, board size 19, color white, and zero for
;; both komi and handicap.
;;
;; To play a stone, move the cursor to the desired vertice and type `SPC' or
;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
;; back through an arbitrary stone that you played, place the cursor on a
;; stone and type `U' (note: uppercase).
;;
;; There are a great many other commands. Other keybindings are described in
;; the `gnugo-board-mode' documentation, which you may view with the command
;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
;; the last move and who is currently to play. Capture counts and other info
;; are shown on the mode line immediately following the major mode name.
;;
;; While GNU Go is pondering its next move, certain commands that rely on its
;; assistance will result in a "still waiting" error. Do not be alarmed; that
;; is normal. When it is your turn again you may retry the command. In the
;; meantime, you can use Emacs for other tasks, or start an entirely new game
;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
;;
;; If GNU Go should crash during a game the mode line will show "no process".
;; Please report the event to the GNU Go maintainers so that they can improve
;; the program.
;;
;;
;; Meta-Playing (aka Customizing)
;; ------------------------------
;;
;; Customization is presently limited to
;; vars: `gnugo-program'
;; `gnugo-animation-string'
;; `gnugo-mode-line'
;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
;; `gnugo-undo-reaction'
;; `gnugo-xpms' (see also gnugo-imgen.el)
;; normal hooks: `gnugo-board-mode-hook'
;; `gnugo-frolic-mode-hook'
;; `gnugo-start-game-hook'
;; `gnugo-post-move-hook'
;; and the keymaps: `gnugo-board-mode-map'
;; `gnugo-frolic-mode-map'
;;
;;
;; Meta-Meta-Playing (aka Hacking)
;; -------------------------------
;;
;; <https://git.savannah.gnu.org/cgit/emacs/elpa.git/tree?h=externals/gnugo>
;;; Code:
(require 'cl-lib) ; use the source luke!
(require 'time-date) ; for `time-subtract'
;;;---------------------------------------------------------------------------
;;; Political arts
(defconst gnugo-version "3.1.2"
"Version of gnugo.el currently loaded.
This follows a MAJOR.MINOR.PATCH scheme.")
;;;---------------------------------------------------------------------------
;;; Variables for the uninquisitive programmer
(defvar gnugo-program "gnugo"
"Name of the GNU Go program (executable file).
\\[gnugo] validates this using `executable-find'.
This program must accept command line args:
--mode gtp --quiet
For more information on GTP and GNU Go, please visit:
<https://www.gnu.org/software/gnugo>")
(defvar gnugo-start-game-hook nil
"Normal hook run immediately before the first move of the game.
To find out who is to move first, use `gnugo-current-player'.
See also `gnugo-board-mode'.")
(defvar gnugo-post-move-hook nil
"Normal hook run after a move and before the board is refreshed.
Initially, when `run-hooks' is called, the current buffer is the GNUGO
Board buffer of the game. Hook functions that switch buffers must take
care not to call (directly or indirectly through some other function)
`gnugo-put' or `gnugo-get' after the switch.")
(defvar gnugo-animation-string
(let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
(concat jam jam jam jam jam
;; "SECRET MESSAGE HERE"
blink blink blink blink blink blink blink blink
;; Playing go is like fighting ignorance: when you think you have
;; surrounded something by knowing it very well it often turns
;; out that in the time you spent deepening this understanding,
;; other areas of ignorance have surrounded you.
spin spin spin spin spin spin spin spin spin
;; Playing go is not like fighting ignorance: what one person
;; knows many people may come to know; knowledge does not build
;; solely move by move. Wisdom, on the other hand...
yada yada yada))
"String whose individual characters are used for animation.
Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
render the stones in their respective result groups as the first character
in the string, then the next, and so on.")
(defvar gnugo-mode-line "~b ~w :~m :~u"
"A `mode-line-format'-compliant value for GNUGO Board mode.
If a single string, the following special escape sequences are
replaced with their associated information:
~b,~w black,white captures (a number)
~p current player (black or white)
~m move number
~t time waiting for the current move
~u time taken for the Ultimate (most recent) move
The times are in seconds, or \"-\" if that information is not available.
For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
(defvar gnugo-X-face 'font-lock-string-face
"Name of face to use for X (black) stones.")
(defvar gnugo-O-face 'font-lock-builtin-face
"Name of face to use for O (white) stones.")
(defvar gnugo-grid-face 'default
"Name of face to use for the grid (A B C ... 1 2 3 ...).")
(defvar gnugo-undo-reaction 'play!
"What to do if undo (or oops) leaves GNU Go to play.
After `gnugo-undo-one-move', `gnugo-undo-two-moves' or `gnugo-oops',
when GNU Go is to play, this can be a symbol:
play -- make GNU Go play (unless in Zombie mode)
play! -- make GNU Go play unconditionally (traditional behavior)
zombie -- enable Zombie mode (`gnugo-zombie-mode')
one-shot -- like `zombie' but valid only for the next move
Any other value, or (as a special case) for `gnugo-undo-one-move',
any value other than `zombie', is taken as `one-shot'. Note that
making GNU Go play will probably result in the recently-liberated
board position becoming re-occupied.")
(defvar gnugo-xpms nil
"List of 46 ((TYPE . LOCATION) . XPM-IMAGE) forms.
XPM-IMAGE is an image as returned by `create-image' with
inline data (i.e., property :data with string value).
TYPE is a symbol, one of:
hoshi -- unoccupied position with dot
empty -- unoccupied position sans dot
bpmoku, bmoku -- black stone with and sans highlight point
wpmoku, wmoku -- white stone with and sans highlight point
LOCATION is an integer encoding edge, corner, or center:
1 2 3
4 5 6
7 8 9
For instance, 4 means \"left edge\", 9 means \"bottom right\".
There is only one location for hoshi: center. The other five
types each have all possible locations. So (+ 1 (* 9 5)) => 46.
The value can also be a function (satisfying `functionp') that
takes one arg, the size of the board, and returns the appropriate
list of forms.")
;;;---------------------------------------------------------------------------
;;; Variables for the inquisitive programmer
(defconst gnugo-font-lock-keywords
'(("X" . gnugo-X-face)
("O" . gnugo-O-face))
"Font lock keywords for `gnugo-board-mode'.")
(defvar gnugo-option-history nil
"History list of options for `gnugo' invocation.")
(defvar gnugo-state nil) ; hint: C-c C-p
(defvar gnugo-btw nil)
;;;---------------------------------------------------------------------------
;;; Support functions
(defsubst gnugo-aqr (key alist)
"Essentially: (cdr (assq KEY ALIST))
This is like Scheme ‘assq-ref’ but with reversed arguments.
The name was chosen to occupy the same space as \"cdr (assq\":
(cdr (assq KEY ALIST))
(gnugo-aqr KEY ALIST)
to minimize reindentation noise. [Surely Emacs must
provide something like this, somewhere, by now? --ttn]"
(cdr (assq key alist)))
(defsubst gnugo--mkht (&rest etc)
(apply 'make-hash-table :test 'eq etc))
(defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
(compare-strings s1 beg1 nil s2 beg2 nil))
(defun gnugo-put (key value)
"Associate move/game/board-specific property KEY with VALUE.
There are many properties, each named by a keyword, that record and control
how gnugo.el manages each game. Each GNUGO Board buffer has its own set
of properties, stored in the hash table `gnugo-state'. Here we document
some of the more stable properties. You may wish to use them as part of
a `gnugo-post-move-hook' function, for example. Be careful to preserve
the current buffer as `gnugo-state' is made into a buffer-local variable.
NOTE: In the following, \"see foo\" actually means \"see foo source or
you may never really understand to any degree of personal satisfaction\".
:proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
:diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
:game-over -- nil until game over at which time its value is set to the
alist ((live GROUP ...) (seki GROUP ...) (dead GROUP ...))
:sgf-collection -- after a `loadsgf' command, entire parse tree of file,
a simple list of one or more gametrees, updated in
conjunction w/ :sgf-gametree and :monkey
:sgf-gametree -- one of the gametrees in :sgf-collection
:monkey -- vector of two elements:
MEM, a pointer to one of the branches in the gametree;
BIDX, the index of the \"current branch\"
:gnugo-color -- either \"black\" or \"white\"
:user-color
:last-mover
:last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
:waiting-start
:black-captures -- these are strings since gnugo.el doesn't do anything
:white-captures w/ the information besides display it in the mode line
:display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
`gnugo-image-display-mode' and `gnugo-refresh',
as well as gnugo-xpms.el (available elsewhere)
:all-yy -- list of 46 symbols used as the `category' text property
(so that their plists, typically w/ property `display' or
`do-not-display') are consulted by the Emacs display engine;
46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
`gnugo-image-display-mode', `gnugo-yy' and `gnugo-yang'
:paren-ov -- a pair (left and right) of overlays shuffled about to indicate
the last move; only one is used when displaying using images
:last-user-bpos -- board position; keep the hapless human happy
As things stabilize probably more info will be added to this docstring."
(declare (indent 1))
(puthash key value gnugo-state))
(defun gnugo-get (key)
"Return the move/game/board-specific value for KEY.
See `gnugo-put'."
(gethash key gnugo-state))
(defun gnugo--forget (&rest keys)
(dolist (key keys)
(remhash key gnugo-state)))
(defsubst gnugo--tree-mnum (tree)
(aref tree 1))
(defsubst gnugo--tree-ends (tree)
(aref tree 0))
(defsubst gnugo--set-tree-ends (tree ls)
(aset tree 0 (apply 'vector ls))
(gnugo--tree-ends tree))
(defun gnugo--root-node (&optional tree)
(aref (or tree (gnugo-get :sgf-gametree))
2))
(defun gnugo-describe-internal-properties ()
"Pretty-print `gnugo-state' properties in another buffer.
Handle the big, slow-to-render, and/or uninteresting ones specially."
(interactive)
(let ((buf (current-buffer))
(d (gnugo-get :diamond))
(acc (cl-loop
for key being the hash-keys of gnugo-state
using (hash-values val)
collect (cons key
(cl-case key
((:xpms)
(format "hash: %X (%d images)"
(sxhash val)
(length val)))
(:sgf-collection
(length val))
(:sgf-gametree
(list (hash-table-count
(gnugo--tree-mnum val))
(gnugo--root-node val)
(gnugo--tree-ends val)))
(:monkey
(let ((mem (aref val 0)))
(list (aref val 1)
(car mem))))
(t val))))))
(switch-to-buffer (get-buffer-create
(format "%s*GNUGO Board Properties*"
d)))
(erase-buffer)
(emacs-lisp-mode)
(setq truncate-lines t)
(insert ";;; " (message "%d properties" (length acc)))
(save-excursion
(cl-loop
with standard-output = (current-buffer)
for (key . val) in acc
do (progn
(unless (bolp)
(newline))
(print key)
(pp val)))
(goto-char (point-min))
(let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
(if (string= "" d)
".+\n"
""))))
(while (re-search-forward rx nil t)
(let ((pos (get-text-property (string-to-number (match-string 1))
'gnugo-position buf)))
(delete-region (+ 2 (match-beginning 0)) (point))
(insert (format " %S" pos))))))))
(defun gnugo-board-buffer-p (&optional buffer)
"Return non-nil if BUFFER is a GNUGO Board buffer."
(eq 'gnugo-board-mode
(buffer-local-value
'major-mode
(or buffer (current-buffer)))))
(defun gnugo-board-user-play-ok-p (&optional buffer)
"Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
(with-current-buffer (or buffer (current-buffer))
(and gnugo-state (not (gnugo-get :waiting)))))
(defsubst gnugo--prop-blackp (object)
(eq :B object))
(defsubst gnugo--blackp (string)
(string= "black" string))
(defun gnugo-other (color)
"If COLOR is \"black\", return \"white\", otherwise \"black\"."
(if (gnugo--blackp color) "white" "black"))
(defun gnugo-current-player ()
"Return the current player, either \"black\" or \"white\"."
(gnugo-other (gnugo-get :last-mover)))
(defsubst gnugo--prop<-color (color)
(if (gnugo--blackp color) :B :W))
(defun gnugo-gate (&optional in-progress-p)
(unless (gnugo-board-buffer-p)
(user-error "Wrong buffer -- try M-x gnugo"))
(unless (gnugo-get :proc)
(user-error "No \"gnugo\" process!"))
(cl-destructuring-bind (&optional color . suggestion)
(gnugo-get :waiting)
(when color
(apply 'user-error
"%s -- please wait for \"(%s to play)\""
(if suggestion
(list "Still thinking"
color)
(list "Not your turn yet"
(gnugo-other color))))))
(when (and in-progress-p (gnugo-get :game-over))
(user-error "Sorry, game over")))
(defun gnugo-sentinel (proc string)
(let ((status (process-status proc)))
(when (memq status '(exit signal))
(let ((buf (process-buffer proc)))
(when (buffer-live-p buf)
(with-current-buffer buf
(setq mode-line-process
(list " [%s ("
(propertize (car (split-string string))
'face 'font-lock-warning-face)
")]"))
(when (eq proc (gnugo-get :proc))
(gnugo--forget :proc))))))))
(defun gnugo--begin-exchange (proc filter line)
(declare (indent 2)) ; good time, for a rime
; nice style, for a wile...
(set-process-filter proc filter)
(process-send-string proc line)
(process-send-string proc "\n"))
(defun gnugo--q (fmt &rest args)
"Send formatted command \"FMT ARGS...\"; wait for / return response.
The response is a string whose first two characters indicate the
status of the command. See also `gnugo-query'."
(let ((slow (gnugo-get :waiting))
(proc (gnugo-get :proc)))
(when slow
(user-error "Sorry, still waiting for %s to %s"
(car slow) (if (cdr slow)
"receive a suggestion"
"play")))
(process-put proc :incomplete t)
(process-put proc :srs "") ; synchronous return stash
(gnugo--begin-exchange
proc (lambda (proc string)
(let ((full (concat (process-get proc :srs)
string)))
(process-put proc :srs full)
(unless (numberp (gnugo--compare-strings
full (max 0 (- (length full)
2))
"\n\n" nil))
(process-put proc :incomplete nil))))
(if (null args)
fmt
(apply #'format fmt args)))
(while (process-get proc :incomplete)
(accept-process-output proc 30))
(prog1 (substring (process-get proc :srs) 0 -2)
(process-put proc :srs ""))))
(defsubst gnugo--no-worries (string)
(= ?= (aref string 0)))
(defun gnugo--q/ue (fmt &rest args)
(let ((ans (apply 'gnugo--q fmt args)))
(unless (gnugo--no-worries ans)
(user-error "%s" ans))
(substring ans 2)))
(defun gnugo-query (message-format &rest args)
"Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
Return a string that omits the first two characters (corresponding
to the status indicator in the Go Text Protocol). Use this function
when you are sure the command cannot fail."
(substring (apply 'gnugo--q message-format args)
2))
(defun gnugo--nquery (cmd)
(string-to-number (gnugo-query cmd)))
(defun gnugo-lsquery (message-format &rest args)
"Apply `gnugo-query' to args; split its rv (return list of strings)."
(split-string (apply 'gnugo-query message-format args)))
(defsubst gnugo--count-query (fmt &rest args)
(length (apply 'gnugo-lsquery fmt args)))
(defsubst gnugo--root-prop (prop &optional tree)
(gnugo-aqr prop (gnugo--root-node tree)))
(defun gnugo--set-root-prop (prop value &optional tree)
(let* ((root (gnugo--root-node tree))
(cur (assq prop root)))
(if cur
(setcdr cur value)
(push (cons prop value)
(cdr (last root))))))
(defun gnugo-goto-pos (pos)
"Move point to board position POS, a letter-number string.
Return final buffer position (i.e., point)."
(goto-char (point-min))
(forward-line (- (1+ (gnugo-get :SZ))
(string-to-number (substring pos 1))))
(forward-char 1)
(forward-char (+ (if (= 32 (following-char)) 1 2)
(* 2 (- (let ((letter (aref pos 0)))
(if (> ?I letter)
letter
(1- letter)))
?A))))
(point))
(defun gnugo-f (id)
(intern (if (symbolp id)
(symbol-name id)
id)
(gnugo-get :obarray)))
(defun gnugo-yang (c)
"Return the \"image type information\" corresponding to character C.
C is one of the four characters used in the ASCII representation
of a game board -- ?+ (U+2B PLUS SIGN), ?. (U+2E FULL STOP), ?X
and ?O (U+58 and U+4F, LATIN CAPITAL LETTER X and O, respectively).
For example, here is a 5x5 board with two stones placed:
. . . . .
. O . + . (white at B4)
. . + . .
. + . + X (black at E2)
. . . . .
The image type information consists of a single symbol for ?. and ?+
and a pair (SANS-POINT . WITH-POINT) for ?X and ?O. Both SANS-POINT
and WITH-POINT are symbols. For other C, return nil."
(gnugo-aqr c '((?+ . hoshi)
(?. . empty)
(?X . (bmoku . bpmoku))
(?O . (wmoku . wpmoku)))))
(defun gnugo-yy (yin yang &optional momentaryp)
"Return a symbol made by formatting YIN (an integer) and YANG.
The returned symbol has the format N-SYMBOL.
If YANG is a symbol, use it directly. Otherwise, YANG must be a pair.
If optional arg MOMENTARYP is non-nil, use the `cdr' of YANG.
Otherwise, use the `car' of YANG. See `gnugo-yang'."
(gnugo-f (format "%d-%s"
yin (cond ((symbolp yang) yang)
(momentaryp (cdr yang))
(t (car yang))))))
(define-minor-mode gnugo-grid-mode
"If enabled, display grid around the board."
:variable
((not (memq :nogrid buffer-invisibility-spec))
.
(lambda (bool)
(funcall (if bool
'remove-from-invisibility-spec
'add-to-invisibility-spec)
:nogrid)
(save-excursion (gnugo-refresh)))))
(defconst gnugo--intangible (if (fboundp 'cursor-intangible-mode)
'cursor-intangible
'intangible)
"Text property that controls intangibility.")
(defun gnugo--propertize-board-buffer ()
(erase-buffer)
(insert (substring (gnugo--q "showboard") 3))
(let* ((grid-props (list 'invisible :nogrid
'font-lock-face gnugo-grid-face))
(%gpad (gnugo-f 'gpad))
(%gspc (gnugo-f 'gspc))
(%lpad (gnugo-f 'lpad))
(%rpad (gnugo-f 'rpad))
(ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
(size (gnugo-get :SZ))
(size-string (number-to-string size)))
(goto-char (point-min))
(put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
(skip-chars-forward " ")
(put-text-property (1- (point)) (point) 'category %gpad)
(put-text-property (point) (line-end-position) 'category %gspc)
(forward-line 1)
(add-text-properties (1+ (point-min)) (1- (point)) grid-props)
(while (looking-at "\\s-*\\([0-9]+\\)[ ]")
(let* ((row (match-string-no-properties 1))
(edge (match-end 0))
(other-edge (+ edge (* 2 size) -1))
(right-empty (+ other-edge (length row) 1))
(top-p (string= size-string row))
(bot-p (string= "1" row)))
(let* ((nL (- edge 1 (length size-string)))
(nR (- edge 1))
(ov (make-overlay nL nR (current-buffer) t)))
(add-text-properties nL nR grid-props)
;; We redundantly set `invisible' in the overlay to workaround
;; a display bug whereby text *following* the overlaid text is
;; displayed with the face of the overlaid text, but only when
;; that text is invisible (i.e., `:nogrid' in invisibility spec).
;; This has something to do w/ the bletcherous `before-string'.
(overlay-put ov 'invisible :nogrid)
(overlay-put ov 'category %lpad))
(cl-do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
((< other-edge p))
(let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
(truncate (- p edge) 2))
row))
(yin (let ((A-p (= edge p))
(Z-p (= (1- other-edge) p)))
(cond ((and top-p A-p) 1)
((and top-p Z-p) 3)
((and bot-p A-p) 7)
((and bot-p Z-p) 9)
(top-p 2)
(bot-p 8)
(A-p 4)
(Z-p 6)
(t 5))))
(yang (gnugo-yang (char-after p))))
(add-text-properties p (1+ p)
`(gnugo-position
,position
gnugo-yin
,yin
gnugo-yang
,yang
category
,(gnugo-yy yin yang)
front-sticky
(gnugo-position gnugo-yin))))
(unless (= (1- other-edge) p)
(add-text-properties (1+ p) (+ 2 p) ispc-props)
(put-text-property p (+ 2 p) gnugo--intangible ival)))
(add-text-properties (1+ other-edge) right-empty grid-props)
(goto-char right-empty)
(when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
(let ((prop (if (string= "WH" (match-string 1))
:white-captures
:black-captures))
(beg (match-beginning 2))
(end (match-end 2)))
(put-text-property beg end :gnugo-cf (cons (- end beg) prop))
(gnugo-put prop (match-string-no-properties 2))))
(put-text-property right-empty (line-end-position) 'category %rpad)
(forward-line 1)))
(add-text-properties (1- (point)) (point-max) grid-props)
(skip-chars-forward " ")
(put-text-property (1- (point)) (point) 'category %gpad)
(put-text-property (point) (line-end-position)
'category %gspc)))
(defun gnugo--merge-showboard-results ()
(let ((aft (substring (gnugo--q "showboard") 3))
(adj 1) ; string to buffer position adjustment
(sync "[0-9]* stones$")
;; Note: `sync' used to start w/ "[0-9]+", but that is too
;; restrictive a condition that fails in the case of:
;;
;; (before)
;; ... WHITE has captured 1 stones
;; ^
;; (after)
;; ... WHITE has captured 14 stones
;; ^
;;
;; where the after count has more digits than the before count,
;; but shares the same leading digits. In this case, the result
;; of `compare-strings' points to the SPC following the before
;; count (indicated by caret in this example).
(bef (buffer-substring-no-properties (point-min) (point-max)))
(bef-start 0) (bef-idx 0)
(aft-start 0) (aft-idx 0)
aft-sync-backtrack mis inc cut new very-strange
(inhibit-read-only t))
(while (numberp (setq mis (gnugo--compare-strings
bef bef-start
aft aft-start)))
(setq aft-sync-backtrack nil
inc (if (cl-minusp mis)
(- (+ 1 mis))
(- mis 1))
bef-idx (+ bef-start inc)
aft-idx (+ aft-start inc)
bef-start (if (eq bef-idx (string-match sync bef bef-idx))
(match-end 0)
(1+ bef-idx))
aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
(let ((peek (1- aft-idx)))
(while (not (= 32 (aref aft peek)))
(setq peek (1- peek)))
(setq aft-sync-backtrack (1+ peek))))
(match-end 0)
(1+ aft-idx))
cut (+ bef-idx adj
(if aft-sync-backtrack
(- aft-sync-backtrack aft-idx)
0)))
(goto-char cut)
(if aft-sync-backtrack
(let* ((asb aft-sync-backtrack)
(l-p (get-text-property cut :gnugo-cf))
(old-len (car l-p))
(capprop (cdr l-p))
(keep (text-properties-at cut)))
(setq new (substring aft asb (string-match " " aft asb)))
(plist-put keep :gnugo-cf (cons (length new) capprop))
(gnugo-put capprop new)
(delete-char old-len)
(insert (apply 'propertize new keep))
(cl-incf adj (- (length new) old-len)))
(setq new (aref aft aft-idx))
(insert-and-inherit (char-to-string new))
(let ((yin (get-text-property cut 'gnugo-yin))
(yang (gnugo-yang new)))
(add-text-properties cut (1+ cut)
`(gnugo-yang
,yang
category
,(gnugo-yy yin yang))))
(delete-char 1)
;; Do this last to avoid complications w/ font lock and overlays
;; (this also means we cannot include `intangible' in `front-sticky').
;; This is necessary even for ‘cursor-intangible’; if we omit it, the
;; cursor can (incorrectly) enter the text displayed by ‘:paren-ov’.
;; TODO: Revisit later to see if that still holds.
(when (setq very-strange (get-text-property (1+ cut) gnugo--intangible))
(put-text-property cut (1+ cut) gnugo--intangible very-strange))))))
(defsubst gnugo--move-prop (node)
(or (assq :B node)
(assq :W node)))
(defun gnugo--as-pos-func ()
(let ((size (gnugo-get :SZ)))
;; rv
(lambda (cc)
(if (string= "" cc)
"PASS"
(let ((col (aref cc 0)))
(format "%c%d"
(+ ?A (- (if (> ?i col) col (1+ col)) ?a))
(- size (- (aref cc 1) ?a))))))))
(defsubst gnugo--resignp (string)
(string= "resign" string))
(defsubst gnugo--passp (string)
(string= "PASS" string))
(defun gnugo-move-history (&optional rsel color)
"Determine and return the game's move history.
Optional arg RSEL controls side effects and return value.
If nil, display the history in the echo area as \"(N moves)\"
followed by the space-separated list of moves. When called
interactively with a prefix arg (i.e., RSEL is (4)), display
similarly, but suffix with the mover (either \":B\" or \":W\").
RSEL may also be a symbol that selects what to return:
car -- the most-recent move
cadr -- the next-to-most-recent move
two -- the last two moves as a list, oldest last
bpos -- the last stone on the board placed by COLOR
For all other values of RSEL, do nothing and return nil."
(interactive "P")
(let* ((monkey (gnugo-get :monkey))
(mem (aref monkey 0))
(as-pos (gnugo--as-pos-func))
acc node mprop move)
(cl-flet*
((as-pos-maybe (x) (if (gnugo--resignp x)
x
(funcall as-pos x)))
(remem () (setq node (pop mem)
mprop (gnugo--move-prop node)))
(next (byp) (when (remem)
(setq move (as-pos-maybe (cdr mprop)))
(push (if byp
(format "%s%s" move (car mprop))
move)
acc)))
(nn () (next nil))
(tell () (message "(%d moves) %s"
(length acc)
(mapconcat 'identity (nreverse acc) " ")))
(finish (byp) (while mem (next byp)) (tell)))
(pcase rsel
(`(4) (finish t))
(`nil (finish nil))
(`car (car (nn)))
(`cadr (nn) (car (nn)))
(`two (nn) (nn) acc)
(`bpos (cl-loop
with prop = (gnugo--prop<-color color)
while mem
when (and (remem)
(eq prop (car mprop))
(setq move (cdr mprop))
;; i.e., "normal CC" position
(= 2 (length move)))
return (funcall as-pos move)))
(_ nil)))))
(defun gnugo-boss-is-near ()
"Do `bury-buffer' until the current one is not a GNU Board."
(interactive)
(while (gnugo-board-buffer-p)
(bury-buffer)))
(defsubst gnugo--no-regrets (monkey ends)
(eq (aref ends (aref monkey 1))
(aref monkey 0)))
(defun gnugo--as-cc-func ()
(let ((size (gnugo-get :SZ)))
(lambda (pos)
(let* ((col (aref pos 0))
(one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
(two (+ ?a (- size (string-to-number
(substring pos 1))))))
(format "%c%c" one two)))))
(defun gnugo--decorate (node &rest plist)
(cl-loop
with tp = (last node)
with fruit
while plist
do (setf
fruit (list
;; No OoE worries, here. "The first step in evaluating a
;; function call is to evaluate the remaining elements of the
;; list from left to right." (info "(elisp) Function Forms")
(cons
(pop plist)
(pop plist)))
(cdr tp) fruit
tp fruit)))
(defun gnugo-close-game (end-time resign)
(gnugo-put :game-end-time end-time)
(gnugo-put :scoring-seed (logand (random t) #xffffff))
(gnugo-put :game-over
(cl-flet
;; Q: What form does a game-over "group" take?
;; A: GROUP = (GHEAD POSITION[...])
;; GHEAD = (CPROP [OVERLAY[...]])
;; CPROP = ‘:B’ or ‘:W’
((group (color positions)
(cl-assert positions) ; one or more
(cons (list (gnugo--prop<-color color))
(sort positions #'string<))))
(if (or (eq t resign)
(and (stringp resign)
(string-match "[BW][+][Rr]esign" resign)))
;; Hmmm, treating resignation specially seems kind of pointless.
;; TODO: Choose one: (a) rationalize; (b) decruft.
`((live ,@(cl-flet
((ls (color) (mapcar
(lambda (x)
(group color (split-string x)))
(split-string
(gnugo-query "worm_stones %s" color)
"\n"))))
(append (ls "black")
(ls "white"))))
(seki)
(dead))
(cl-loop
with flat-seki = (gnugo-lsquery "final_status_list seki")
with dd = (gnugo-query "dragon_data")
with start = 0
with (live seki dead)
while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
dd start)
do (let* ((mem (match-string 1 dd))
(ent (group (match-string 2 dd)
(gnugo-lsquery "dragon_stones %s"
mem))))
(string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
dd start)
(cond ((member mem flat-seki)
(push ent seki))
((match-string 2 dd)
(push ent live))
(t
(push ent dead)))
(setq start (match-end 0)))
finally return
`((live ,@live)
(seki ,@seki)
(dead ,@dead)))))))
(defun gnugo--unclose-game ()
(gnugo--forget :game-over ; all those in -close-game
:scoring-seed
:game-end-time)
(let* ((root (gnugo--root-node))
(cur (assq :RE root)))
(when cur
(cl-assert (not (eq cur (car root))) nil
":RE at head of root node: %S"
root)
(delq cur root))))
(defun gnugo-push-move (who move)
(let* ((simple (booleanp who))
(ucolor (gnugo-get :user-color))
(color (if simple
(if who
ucolor
(gnugo-get :gnugo-color))
who))
(start (gnugo-get :waiting-start))
(now (current-time))
(resignp (gnugo--resignp move))
(passp (gnugo--passp move))
(head (gnugo-move-history 'car))
(onep (and head (gnugo--passp head)))
(donep (or resignp (and onep passp))))
(unless resignp
(gnugo--q/ue "play %s %s" color move))
(unless passp
(gnugo--merge-showboard-results))
(gnugo-put :last-mover color)
(when (if simple
who
(string= ucolor color))
(gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
;; update :sgf-gametree and :monkey
(let* ((property (gnugo--prop<-color color))
(pair (cons property (cond (resignp move)
(passp "")
(t (funcall (gnugo--as-cc-func)
move)))))
(fruit (list pair))
(monkey (gnugo-get :monkey))
(mem (aref monkey 0))
(tip (car mem))
(tree (gnugo-get :sgf-gametree))
(ends (gnugo--tree-ends tree))
(mnum (gnugo--tree-mnum tree))
(count (length ends))
(tip-move-num (gethash tip mnum))
(bidx (aref monkey 1)))
;; Detect déjà-vu. That is, when placing "A", avoid:
;;
;; X---Y---A new
;; \
;; --A---B old
;;
;; (such "variations" do not actually vary!) in favor of:
;;
;; X---Y---A new
;; \
;; --B old
;;
;; This linear search loses for multiple ‘old’ w/ "A",
;; a very unusual (but not invalid, sigh) situation.
(cl-loop
with (bx previous)
for i
;; Start with latest / highest likelihood for hit.
;; (See "to the right" comment, below.)
from (if (gnugo--no-regrets monkey ends)
1
0)
below count
if (setq bx (mod (+ bidx i) count)
previous
(cl-loop
with node
for m on (aref ends bx)
while (< tip-move-num
(gethash (setq node (car m))
mnum))
if (eq mem (cdr m))
return (when (equal pair (assq property node))
m)
finally return nil))
;; yes => follow
return
(progn
(unless (= bidx bx)
(cl-rotatef (aref ends bidx)
(aref ends bx)))
(setq mem previous))
;; no => construct
finally do
(progn