Replace some inappropriate uses of toggle-read-only. (Bug#7292)
[bpt/emacs.git] / lisp / play / gomoku.el
CommitLineData
1a06eabd
ER
1;;; gomoku.el --- Gomoku game between you and Emacs
2
d2ce10d2
GM
3;; Copyright (C) 1988, 1994, 1996, 2001, 2002, 2003, 2004, 2005, 2006,
4;; 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3a801d0c 5
2b38b487 6;; Author: Philippe Schnoebelen <phs@lsv.ens-cachan.fr>
16f97fc3 7;; Maintainer: FSF
3e910376 8;; Adapted-By: ESR, Daniel Pfeiffer <occitan@esperanto.org>
e5167999
ER
9;; Keywords: games
10
a2535589
JA
11;; This file is part of GNU Emacs.
12
b1fc2b50 13;; GNU Emacs is free software: you can redistribute it and/or modify
a2535589 14;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
15;; the Free Software Foundation, either version 3 of the License, or
16;; (at your option) any later version.
a2535589
JA
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
b1fc2b50 24;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
a2535589 25
e5167999
ER
26;;; Commentary:
27
a2535589
JA
28;; RULES:
29;;
db9cd97a 30;; Gomoku is a game played between two players on a rectangular board. Each
a2535589
JA
31;; player, in turn, marks a free square of its choice. The winner is the first
32;; one to mark five contiguous squares in any direction (horizontally,
33;; vertically or diagonally).
34;;
35;; I have been told that, in "The TRUE Gomoku", some restrictions are made
36;; about the squares where one may play, or else there is a known forced win
37;; for the first player. This program has no such restriction, but it does not
16f97fc3
RS
38;; know about the forced win, nor do I.
39;; See http://renju.nu/r1rulhis.htm for more information.
a2535589
JA
40
41
a2535589
JA
42;; There are two main places where you may want to customize the program: key
43;; bindings and board display. These features are commented in the code. Go
44;; and see.
45
46
47;; HOW TO USE:
48;;
d9a7a8f5 49;; The command "M-x gomoku" displays a
a2535589
JA
50;; board, the size of which depends on the size of the current window. The
51;; size of the board is easily modified by giving numeric arguments to the
52;; gomoku command and/or by customizing the displaying parameters.
53;;
54;; Emacs plays when it is its turn. When it is your turn, just put the cursor
55;; on the square where you want to play and hit RET, or X, or whatever key you
56;; bind to the command gomoku-human-plays. When it is your turn, Emacs is
57;; idle: you may switch buffers, read your mail, ... Just come back to the
58;; *Gomoku* buffer and resume play.
59
60
61;; ALGORITHM:
62;;
63;; The algorithm is briefly described in section "THE SCORE TABLE". Some
64;; parameters may be modified if you want to change the style exhibited by the
65;; program.
e5167999
ER
66
67;;; Code:
a2535589 68\f
323f7c49
SE
69(defgroup gomoku nil
70 "Gomoku game between you and Emacs."
71 :prefix "gomoku-"
72 :group 'games)
a2535589
JA
73;;;
74;;; GOMOKU MODE AND KEYMAP.
75;;;
323f7c49
SE
76(defcustom gomoku-mode-hook nil
77 "If non-nil, its value is called on entry to Gomoku mode.
78One useful value to include is `turn-on-font-lock' to highlight the pieces."
79 :type 'hook
80 :group 'gomoku)
a2535589 81
a1506d29 82;;;
00171645
PJ
83;;; CONSTANTS FOR BOARD
84;;;
85
428d45d2
GM
86(defconst gomoku-buffer-name "*Gomoku*"
87 "Name of the Gomoku buffer.")
88
00171645
PJ
89;; You may change these values if you have a small screen or if the squares
90;; look rectangular, but spacings SHOULD be at least 2 (MUST BE at least 1).
91
92(defconst gomoku-square-width 4
93 "*Horizontal spacing between squares on the Gomoku board.")
94
95(defconst gomoku-square-height 2
96 "*Vertical spacing between squares on the Gomoku board.")
97
98(defconst gomoku-x-offset 3
99 "*Number of columns between the Gomoku board and the side of the window.")
100
101(defconst gomoku-y-offset 1
102 "*Number of lines between the Gomoku board and the top of the window.")
103
104
a2535589
JA
105(defvar gomoku-mode-map nil
106 "Local keymap to use in Gomoku mode.")
107
108(if gomoku-mode-map nil
109 (setq gomoku-mode-map (make-sparse-keymap))
110
f5ecf0c9
RS
111 ;; Key bindings for cursor motion.
112 (define-key gomoku-mode-map "y" 'gomoku-move-nw) ; y
113 (define-key gomoku-mode-map "u" 'gomoku-move-ne) ; u
114 (define-key gomoku-mode-map "b" 'gomoku-move-sw) ; b
115 (define-key gomoku-mode-map "n" 'gomoku-move-se) ; n
116 (define-key gomoku-mode-map "h" 'backward-char) ; h
117 (define-key gomoku-mode-map "l" 'forward-char) ; l
118 (define-key gomoku-mode-map "j" 'gomoku-move-down) ; j
119 (define-key gomoku-mode-map "k" 'gomoku-move-up) ; k
120
121 (define-key gomoku-mode-map [kp-7] 'gomoku-move-nw)
122 (define-key gomoku-mode-map [kp-9] 'gomoku-move-ne)
123 (define-key gomoku-mode-map [kp-1] 'gomoku-move-sw)
124 (define-key gomoku-mode-map [kp-3] 'gomoku-move-se)
125 (define-key gomoku-mode-map [kp-4] 'backward-char)
126 (define-key gomoku-mode-map [kp-6] 'forward-char)
127 (define-key gomoku-mode-map [kp-2] 'gomoku-move-down)
128 (define-key gomoku-mode-map [kp-8] 'gomoku-move-up)
129
130 (define-key gomoku-mode-map "\C-n" 'gomoku-move-down) ; C-n
131 (define-key gomoku-mode-map "\C-p" 'gomoku-move-up) ; C-p
a2535589
JA
132
133 ;; Key bindings for entering Human moves.
a2535589
JA
134 (define-key gomoku-mode-map "X" 'gomoku-human-plays) ; X
135 (define-key gomoku-mode-map "x" 'gomoku-human-plays) ; x
f201b69e 136 (define-key gomoku-mode-map " " 'gomoku-human-plays) ; SPC
a2535589 137 (define-key gomoku-mode-map "\C-m" 'gomoku-human-plays) ; RET
f5ecf0c9
RS
138 (define-key gomoku-mode-map "\C-c\C-p" 'gomoku-human-plays) ; C-c C-p
139 (define-key gomoku-mode-map "\C-c\C-b" 'gomoku-human-takes-back) ; C-c C-b
140 (define-key gomoku-mode-map "\C-c\C-r" 'gomoku-human-resigns) ; C-c C-r
141 (define-key gomoku-mode-map "\C-c\C-e" 'gomoku-emacs-plays) ; C-c C-e
142
e8a57935 143 (define-key gomoku-mode-map [kp-enter] 'gomoku-human-plays)
f5ecf0c9 144 (define-key gomoku-mode-map [insert] 'gomoku-human-plays)
d7ab2718
RS
145 (define-key gomoku-mode-map [down-mouse-1] 'gomoku-click)
146 (define-key gomoku-mode-map [drag-mouse-1] 'gomoku-click)
147 (define-key gomoku-mode-map [mouse-1] 'gomoku-click)
148 (define-key gomoku-mode-map [down-mouse-2] 'gomoku-click)
149 (define-key gomoku-mode-map [mouse-2] 'gomoku-mouse-play)
150 (define-key gomoku-mode-map [drag-mouse-2] 'gomoku-mouse-play)
f5ecf0c9 151
4cbb3189
AS
152 (define-key gomoku-mode-map [remap previous-line] 'gomoku-move-up)
153 (define-key gomoku-mode-map [remap next-line] 'gomoku-move-down)
cf6d0352
JB
154 (define-key gomoku-mode-map [remap move-beginning-of-line] 'gomoku-beginning-of-line)
155 (define-key gomoku-mode-map [remap move-end-of-line] 'gomoku-end-of-line)
4cbb3189
AS
156 (define-key gomoku-mode-map [remap undo] 'gomoku-human-takes-back)
157 (define-key gomoku-mode-map [remap advertised-undo] 'gomoku-human-takes-back))
f5ecf0c9
RS
158
159(defvar gomoku-emacs-won ()
323f7c49 160 "For making font-lock use the winner's face for the line.")
f5ecf0c9 161
62d39a42 162(defface gomoku-O
6e71749d
JB
163 '((((class color)) (:foreground "red" :weight bold)))
164 "Face to use for Emacs' O."
323f7c49 165 :group 'gomoku)
f5ecf0c9 166
62d39a42 167(defface gomoku-X
6e71749d
JB
168 '((((class color)) (:foreground "green" :weight bold)))
169 "Face to use for your X."
323f7c49 170 :group 'gomoku)
f5ecf0c9
RS
171
172(defvar gomoku-font-lock-keywords
62d39a42
MB
173 '(("O" . 'gomoku-O)
174 ("X" . 'gomoku-X)
175 ("[-|/\\]" 0 (if gomoku-emacs-won 'gomoku-O 'gomoku-X)))
f5ecf0c9
RS
176 "*Font lock rules for Gomoku.")
177
178(put 'gomoku-mode 'front-sticky
179 (put 'gomoku-mode 'rear-nonsticky '(intangible)))
d7ab2718 180(put 'gomoku-mode 'intangible 1)
ea514681
EZ
181;; This one is for when they set view-read-only to t: Gomoku cannot
182;; allow View Mode to be activated in its buffer.
183(put 'gomoku-mode 'mode-class 'special)
a2535589 184
5ca809a7 185(defun gomoku-mode ()
a2535589 186 "Major mode for playing Gomoku against Emacs.
92423534
JB
187You and Emacs play in turn by marking a free square. You mark it with X
188and Emacs marks it with O. The winner is the first to get five contiguous
a2535589 189marks horizontally, vertically or in diagonal.
a2535589 190
92423534 191You play by moving the cursor over the square you choose and hitting \\[gomoku-human-plays].
a2535589 192
92423534 193Other useful commands:
a2535589 194\\{gomoku-mode-map}
92423534 195Entry to this mode calls the value of `gomoku-mode-hook' if that value
428d45d2 196is non-nil."
5ca809a7 197 (interactive)
428d45d2 198 (kill-all-local-variables)
5ca809a7
RS
199 (setq major-mode 'gomoku-mode
200 mode-name "Gomoku")
a2535589 201 (gomoku-display-statistics)
5ca809a7
RS
202 (use-local-map gomoku-mode-map)
203 (make-local-variable 'font-lock-defaults)
d2ce10d2
GM
204 (setq font-lock-defaults '(gomoku-font-lock-keywords t)
205 buffer-read-only t)
c83c9654 206 (run-mode-hooks 'gomoku-mode-hook))
a2535589
JA
207\f
208;;;
209;;; THE BOARD.
210;;;
211
212;; The board is a rectangular grid. We code empty squares with 0, X's with 1
db9cd97a
JB
213;; and O's with 6. The rectangle is recorded in a one dimensional vector
214;; containing padding squares (coded with -1). These squares allow us to
215;; detect when we are trying to move out of the board. We denote a square by
a2535589
JA
216;; its (X,Y) coords, or by the INDEX corresponding to them in the vector. The
217;; leftmost topmost square has coords (1,1) and index gomoku-board-width + 2.
218;; Similarly, vectors between squares may be given by two DX, DY coords or by
219;; one DEPL (the difference between indexes).
220
221(defvar gomoku-board-width nil
222 "Number of columns on the Gomoku board.")
223
224(defvar gomoku-board-height nil
225 "Number of lines on the Gomoku board.")
226
227(defvar gomoku-board nil
228 "Vector recording the actual state of the Gomoku board.")
229
230(defvar gomoku-vector-length nil
219a7700 231 "Length of `gomoku-board' vector.")
a2535589
JA
232
233(defvar gomoku-draw-limit nil
234 ;; This is usually set to 70% of the number of squares.
92423534 235 "After how many moves will Emacs offer a draw?")
a2535589
JA
236
237
238(defun gomoku-xy-to-index (x y)
239 "Translate X, Y cartesian coords into the corresponding board index."
240 (+ (* y gomoku-board-width) x y))
241
242(defun gomoku-index-to-x (index)
243 "Return corresponding x-coord of board INDEX."
244 (% index (1+ gomoku-board-width)))
245
246(defun gomoku-index-to-y (index)
247 "Return corresponding y-coord of board INDEX."
248 (/ index (1+ gomoku-board-width)))
249
250(defun gomoku-init-board ()
219a7700 251 "Create the `gomoku-board' vector and fill it with initial values."
a2535589
JA
252 (setq gomoku-board (make-vector gomoku-vector-length 0))
253 ;; Every square is 0 (i.e. empty) except padding squares:
254 (let ((i 0) (ii (1- gomoku-vector-length)))
255 (while (<= i gomoku-board-width) ; The squares in [0..width] and in
256 (aset gomoku-board i -1) ; [length - width - 1..length - 1]
257 (aset gomoku-board ii -1) ; are padding squares.
258 (setq i (1+ i)
259 ii (1- ii))))
260 (let ((i 0))
261 (while (< i gomoku-vector-length)
262 (aset gomoku-board i -1) ; and also all k*(width+1)
263 (setq i (+ i gomoku-board-width 1)))))
264\f
265;;;
266;;; THE SCORE TABLE.
267;;;
268
269;; Every (free) square has a score associated to it, recorded in the
270;; GOMOKU-SCORE-TABLE vector. The program always plays in the square having
271;; the highest score.
272
273(defvar gomoku-score-table nil
274 "Vector recording the actual score of the free squares.")
275
276
277;; The key point point about the algorithm is that, rather than considering
278;; the board as just a set of squares, we prefer to see it as a "space" of
279;; internested 5-tuples of contiguous squares (called qtuples).
280;;
281;; The aim of the program is to fill one qtuple with its O's while preventing
282;; you from filling another one with your X's. To that effect, it computes a
283;; score for every qtuple, with better qtuples having better scores. Of
284;; course, the score of a qtuple (taken in isolation) is just determined by
285;; its contents as a set, i.e. not considering the order of its elements. The
286;; highest score is given to the "OOOO" qtuples because playing in such a
287;; qtuple is winning the game. Just after this comes the "XXXX" qtuple because
288;; not playing in it is just loosing the game, and so on. Note that a
289;; "polluted" qtuple, i.e. one containing at least one X and at least one O,
290;; has score zero because there is no more any point in playing in it, from
291;; both an attacking and a defending point of view.
292;;
293;; Given the score of every qtuple, the score of a given free square on the
294;; board is just the sum of the scores of all the qtuples to which it belongs,
295;; because playing in that square is playing in all its containing qtuples at
296;; once. And it is that function which takes into account the internesting of
297;; the qtuples.
298;;
299;; This algorithm is rather simple but anyway it gives a not so dumb level of
300;; play. It easily extends to "n-dimensional Gomoku", where a win should not
301;; be obtained with as few as 5 contiguous marks: 6 or 7 (depending on n !)
302;; should be preferred.
303
304
305;; Here are the scores of the nine "non-polluted" configurations. Tuning
306;; these values will change (hopefully improve) the strength of the program
307;; and may change its style (rather aggressive here).
308
309(defconst nil-score 7 "Score of an empty qtuple.")
310(defconst Xscore 15 "Score of a qtuple containing one X.")
311(defconst XXscore 400 "Score of a qtuple containing two X's.")
312(defconst XXXscore 1800 "Score of a qtuple containing three X's.")
313(defconst XXXXscore 100000 "Score of a qtuple containing four X's.")
314(defconst Oscore 35 "Score of a qtuple containing one O.")
315(defconst OOscore 800 "Score of a qtuple containing two O's.")
316(defconst OOOscore 15000 "Score of a qtuple containing three O's.")
317(defconst OOOOscore 800000 "Score of a qtuple containing four O's.")
318
319;; These values are not just random: if, given the following situation:
320;;
321;; . . . . . . . O .
322;; . X X a . . . X .
323;; . . . X . . . X .
324;; . . . X . . . X .
325;; . . . . . . . b .
326;;
327;; you want Emacs to play in "a" and not in "b", then the parameters must
328;; satisfy the inequality:
329;;
330;; 6 * XXscore > XXXscore + XXscore
331;;
332;; because "a" mainly belongs to six "XX" qtuples (the others are less
333;; important) while "b" belongs to one "XXX" and one "XX" qtuples. Other
334;; conditions are required to obtain sensible moves, but the previous example
335;; should illustrate the point. If you manage to improve on these values,
336;; please send me a note. Thanks.
337
338
a7acbbe4
KH
339;; As we chose values 0, 1 and 6 to denote empty, X and O squares, the
340;; contents of a qtuple are uniquely determined by the sum of its elements and
a2535589
JA
341;; we just have to set up a translation table.
342
343(defconst gomoku-score-trans-table
344 (vector nil-score Xscore XXscore XXXscore XXXXscore 0
345 Oscore 0 0 0 0 0
346 OOscore 0 0 0 0 0
347 OOOscore 0 0 0 0 0
348 OOOOscore 0 0 0 0 0
349 0)
350 "Vector associating qtuple contents to their score.")
351
352
353;; If you do not modify drastically the previous constants, the only way for a
354;; square to have a score higher than OOOOscore is to belong to a "OOOO"
355;; qtuple, thus to be a winning move. Similarly, the only way for a square to
356;; have a score between XXXXscore and OOOOscore is to belong to a "XXXX"
357;; qtuple. We may use these considerations to detect when a given move is
358;; winning or loosing.
359
360(defconst gomoku-winning-threshold OOOOscore
92423534 361 "Threshold score beyond which an Emacs move is winning.")
a2535589
JA
362
363(defconst gomoku-loosing-threshold XXXXscore
364 "Threshold score beyond which a human move is winning.")
365
366
367(defun gomoku-strongest-square ()
368 "Compute index of free square with highest score, or nil if none."
369 ;; We just have to loop other all squares. However there are two problems:
370 ;; 1/ The SCORE-TABLE only gives correct scores to free squares. To speed
371 ;; up future searches, we set the score of padding or occupied squares
372 ;; to -1 whenever we meet them.
373 ;; 2/ We want to choose randomly between equally good moves.
374 (let ((score-max 0)
375 (count 0) ; Number of equally good moves
376 (square (gomoku-xy-to-index 1 1)) ; First square
377 (end (gomoku-xy-to-index gomoku-board-width gomoku-board-height))
378 best-square score)
379 (while (<= square end)
380 (cond
381 ;; If score is lower (i.e. most of the time), skip to next:
382 ((< (aref gomoku-score-table square) score-max))
383 ;; If score is better, beware of non free squares:
384 ((> (setq score (aref gomoku-score-table square)) score-max)
385 (if (zerop (aref gomoku-board square)) ; is it free ?
386 (setq count 1 ; yes: take it !
387 best-square square
388 score-max score)
389 (aset gomoku-score-table square -1))) ; no: kill it !
390 ;; If score is equally good, choose randomly. But first check freeness:
391 ((not (zerop (aref gomoku-board square)))
392 (aset gomoku-score-table square -1))
f7e55318 393 ((zerop (random (setq count (1+ count))))
a2535589
JA
394 (setq best-square square
395 score-max score)))
396 (setq square (1+ square))) ; try next square
397 best-square))
a2535589
JA
398\f
399;;;
400;;; INITIALIZING THE SCORE TABLE.
401;;;
402
403;; At initialization the board is empty so that every qtuple amounts for
404;; nil-score. Therefore, the score of any square is nil-score times the number
405;; of qtuples that pass through it. This number is 3 in a corner and 20 if you
406;; are sufficiently far from the sides. As computing the number is time
407;; consuming, we initialize every square with 20*nil-score and then only
408;; consider squares at less than 5 squares from one side. We speed this up by
409;; taking symmetry into account.
410;; Also, as it is likely that successive games will be played on a board with
411;; same size, it is a good idea to save the initial SCORE-TABLE configuration.
412
413(defvar gomoku-saved-score-table nil
414 "Recorded initial value of previous score table.")
415
416(defvar gomoku-saved-board-width nil
417 "Recorded value of previous board width.")
418
419(defvar gomoku-saved-board-height nil
420 "Recorded value of previous board height.")
421
422
423(defun gomoku-init-score-table ()
424 "Create the score table vector and fill it with initial values."
425 (if (and gomoku-saved-score-table ; Has it been stored last time ?
426 (= gomoku-board-width gomoku-saved-board-width)
427 (= gomoku-board-height gomoku-saved-board-height))
428 (setq gomoku-score-table (copy-sequence gomoku-saved-score-table))
429 ;; No, compute it:
430 (setq gomoku-score-table
431 (make-vector gomoku-vector-length (* 20 nil-score)))
432 (let (i j maxi maxj maxi2 maxj2)
433 (setq maxi (/ (1+ gomoku-board-width) 2)
434 maxj (/ (1+ gomoku-board-height) 2)
435 maxi2 (min 4 maxi)
436 maxj2 (min 4 maxj))
437 ;; We took symmetry into account and could use it more if the board
438 ;; would have been square and not rectangular !
439 ;; In our case we deal with all (i,j) in the set [1..maxi2]*[1..maxj] U
440 ;; [maxi2+1..maxi]*[1..maxj2]. Maxi2 and maxj2 are used because the
441 ;; board may well be less than 8 by 8 !
442 (setq i 1)
443 (while (<= i maxi2)
444 (setq j 1)
445 (while (<= j maxj)
446 (gomoku-init-square-score i j)
447 (setq j (1+ j)))
448 (setq i (1+ i)))
449 (while (<= i maxi)
450 (setq j 1)
451 (while (<= j maxj2)
452 (gomoku-init-square-score i j)
453 (setq j (1+ j)))
454 (setq i (1+ i))))
455 (setq gomoku-saved-score-table (copy-sequence gomoku-score-table)
456 gomoku-saved-board-width gomoku-board-width
457 gomoku-saved-board-height gomoku-board-height)))
458
459(defun gomoku-nb-qtuples (i j)
460 "Return the number of qtuples containing square I,J."
92423534 461 ;; This function is complicated because we have to deal
a2535589
JA
462 ;; with ugly cases like 3 by 6 boards, but it works.
463 ;; If you have a simpler (and correct) solution, send it to me. Thanks !
464 (let ((left (min 4 (1- i)))
465 (right (min 4 (- gomoku-board-width i)))
466 (up (min 4 (1- j)))
467 (down (min 4 (- gomoku-board-height j))))
468 (+ -12
469 (min (max (+ left right) 3) 8)
470 (min (max (+ up down) 3) 8)
471 (min (max (+ (min left up) (min right down)) 3) 8)
472 (min (max (+ (min right up) (min left down)) 3) 8))))
473
474(defun gomoku-init-square-score (i j)
475 "Give initial score to square I,J and to its mirror images."
476 (let ((ii (1+ (- gomoku-board-width i)))
477 (jj (1+ (- gomoku-board-height j)))
478 (sc (* (gomoku-nb-qtuples i j) (aref gomoku-score-trans-table 0))))
479 (aset gomoku-score-table (gomoku-xy-to-index i j) sc)
480 (aset gomoku-score-table (gomoku-xy-to-index ii j) sc)
481 (aset gomoku-score-table (gomoku-xy-to-index i jj) sc)
482 (aset gomoku-score-table (gomoku-xy-to-index ii jj) sc)))
483\f
484;;;
485;;; MAINTAINING THE SCORE TABLE.
486;;;
487
488;; We do not provide functions for computing the SCORE-TABLE given the
489;; contents of the BOARD. This would involve heavy nested loops, with time
490;; proportional to the size of the board. It is better to update the
491;; SCORE-TABLE after each move. Updating needs not modify more than 36
492;; squares: it is done in constant time.
493
494(defun gomoku-update-score-table (square dval)
495 "Update score table after SQUARE received a DVAL increment."
496 ;; The board has already been updated when this function is called.
497 ;; Updating scores is done by looking for qtuples boundaries in all four
498 ;; directions and then calling update-score-in-direction.
499 ;; Finally all squares received the right increment, and then are up to
500 ;; date, except possibly for SQUARE itself if we are taking a move back for
501 ;; its score had been set to -1 at the time.
502 (let* ((x (gomoku-index-to-x square))
503 (y (gomoku-index-to-y square))
504 (imin (max -4 (- 1 x)))
505 (jmin (max -4 (- 1 y)))
506 (imax (min 0 (- gomoku-board-width x 4)))
507 (jmax (min 0 (- gomoku-board-height y 4))))
508 (gomoku-update-score-in-direction imin imax
509 square 1 0 dval)
510 (gomoku-update-score-in-direction jmin jmax
511 square 0 1 dval)
512 (gomoku-update-score-in-direction (max imin jmin) (min imax jmax)
513 square 1 1 dval)
514 (gomoku-update-score-in-direction (max (- 1 y) -4
515 (- x gomoku-board-width))
516 (min 0 (- x 5)
517 (- gomoku-board-height y 4))
518 square -1 1 dval)))
519
520(defun gomoku-update-score-in-direction (left right square dx dy dval)
521 "Update scores for all squares in the qtuples starting between the LEFTth
522square and the RIGHTth after SQUARE, along the DX, DY direction, considering
523that DVAL has been added on SQUARE."
524 ;; We always have LEFT <= 0, RIGHT <= 0 and DEPL > 0 but we may very well
525 ;; have LEFT > RIGHT, indicating that no qtuple contains SQUARE along that
526 ;; DX,DY direction.
527 (cond
528 ((> left right)) ; Quit
529 (t ; Else ..
530 (let (depl square0 square1 square2 count delta)
531 (setq depl (gomoku-xy-to-index dx dy)
532 square0 (+ square (* left depl))
533 square1 (+ square (* right depl))
534 square2 (+ square0 (* 4 depl)))
535 ;; Compute the contents of the first qtuple:
536 (setq square square0
537 count 0)
538 (while (<= square square2)
539 (setq count (+ count (aref gomoku-board square))
540 square (+ square depl)))
541 (while (<= square0 square1)
542 ;; Update the squares of the qtuple beginning in SQUARE0 and ending
543 ;; in SQUARE2.
544 (setq delta (- (aref gomoku-score-trans-table count)
545 (aref gomoku-score-trans-table (- count dval))))
546 (cond ((not (zerop delta)) ; or else nothing to update
547 (setq square square0)
548 (while (<= square square2)
549 (if (zerop (aref gomoku-board square)) ; only for free squares
550 (aset gomoku-score-table square
551 (+ (aref gomoku-score-table square) delta)))
552 (setq square (+ square depl)))))
553 ;; Then shift the qtuple one square along DEPL, this only requires
554 ;; modifying SQUARE0 and SQUARE2.
555 (setq square2 (+ square2 depl)
556 count (+ count (- (aref gomoku-board square0))
557 (aref gomoku-board square2))
558 square0 (+ square0 depl)))))))
559\f
560;;;
561;;; GAME CONTROL.
562;;;
563
564;; Several variables are used to monitor a game, including a GAME-HISTORY (the
565;; list of all (SQUARE . PREVSCORE) played) that allows to take moves back
566;; (anti-updating the score table) and to compute the table from scratch in
567;; case of an interruption.
568
569(defvar gomoku-game-in-progress nil
570 "Non-nil if a game is in progress.")
571
572(defvar gomoku-game-history nil
573 "A record of all moves that have been played during current game.")
574
575(defvar gomoku-number-of-moves nil
576 "Number of moves already played in current game.")
577
578(defvar gomoku-number-of-human-moves nil
579 "Number of moves already played by human in current game.")
580
581(defvar gomoku-emacs-played-first nil
582 "Non-nil if Emacs played first.")
583
584(defvar gomoku-human-took-back nil
585 "Non-nil if Human took back a move during the game.")
586
587(defvar gomoku-human-refused-draw nil
588 "Non-nil if Human refused Emacs offer of a draw.")
589
590(defvar gomoku-emacs-is-computing nil
591 ;; This is used to detect interruptions. Hopefully, it should not be needed.
592 "Non-nil if Emacs is in the middle of a computation.")
593
594
595(defun gomoku-start-game (n m)
596 "Initialize a new game on an N by M board."
597 (setq gomoku-emacs-is-computing t) ; Raise flag
598 (setq gomoku-game-in-progress t)
599 (setq gomoku-board-width n
600 gomoku-board-height m
601 gomoku-vector-length (1+ (* (+ m 2) (1+ n)))
602 gomoku-draw-limit (/ (* 7 n m) 10))
f5ecf0c9
RS
603 (setq gomoku-emacs-won nil
604 gomoku-game-history nil
a2535589
JA
605 gomoku-number-of-moves 0
606 gomoku-number-of-human-moves 0
607 gomoku-emacs-played-first nil
608 gomoku-human-took-back nil
609 gomoku-human-refused-draw nil)
610 (gomoku-init-display n m) ; Display first: the rest takes time
611 (gomoku-init-score-table) ; INIT-BOARD requires that the score
612 (gomoku-init-board) ; table be already created.
613 (setq gomoku-emacs-is-computing nil))
614
615(defun gomoku-play-move (square val &optional dont-update-score)
616 "Go to SQUARE, play VAL and update everything."
617 (setq gomoku-emacs-is-computing t) ; Raise flag
618 (cond ((= 1 val) ; a Human move
619 (setq gomoku-number-of-human-moves (1+ gomoku-number-of-human-moves)))
620 ((zerop gomoku-number-of-moves) ; an Emacs move. Is it first ?
621 (setq gomoku-emacs-played-first t)))
622 (setq gomoku-game-history
623 (cons (cons square (aref gomoku-score-table square))
624 gomoku-game-history)
625 gomoku-number-of-moves (1+ gomoku-number-of-moves))
626 (gomoku-plot-square square val)
627 (aset gomoku-board square val) ; *BEFORE* UPDATE-SCORE !
628 (if dont-update-score nil
629 (gomoku-update-score-table square val) ; previous val was 0: dval = val
630 (aset gomoku-score-table square -1))
631 (setq gomoku-emacs-is-computing nil))
632
633(defun gomoku-take-back ()
634 "Take back last move and update everything."
635 (setq gomoku-emacs-is-computing t)
636 (let* ((last-move (car gomoku-game-history))
637 (square (car last-move))
638 (oldval (aref gomoku-board square)))
639 (if (= 1 oldval)
640 (setq gomoku-number-of-human-moves (1- gomoku-number-of-human-moves)))
641 (setq gomoku-game-history (cdr gomoku-game-history)
642 gomoku-number-of-moves (1- gomoku-number-of-moves))
643 (gomoku-plot-square square 0)
644 (aset gomoku-board square 0) ; *BEFORE* UPDATE-SCORE !
645 (gomoku-update-score-table square (- oldval))
646 (aset gomoku-score-table square (cdr last-move)))
647 (setq gomoku-emacs-is-computing nil))
648\f
649;;;
650;;; SESSION CONTROL.
651;;;
652
d9a62b4c
RS
653(defvar gomoku-number-of-emacs-wins 0
654 "Number of games Emacs won in this session.")
a2535589 655
d9a62b4c
RS
656(defvar gomoku-number-of-human-wins 0
657 "Number of games you won in this session.")
a2535589
JA
658
659(defvar gomoku-number-of-draws 0
660 "Number of games already drawn in this session.")
661
662
663(defun gomoku-terminate-game (result)
664 "Terminate the current game with RESULT."
d7ab2718
RS
665 (message
666 (cond
667 ((eq result 'emacs-won)
668 (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
669 (cond ((< gomoku-number-of-moves 20)
670 "This was a REALLY QUICK win.")
671 (gomoku-human-refused-draw
219a7700 672 "I won... Too bad you refused my offer of a draw!")
d7ab2718 673 (gomoku-human-took-back
219a7700 674 "I won... Taking moves back will not help you!")
d7ab2718 675 ((not gomoku-emacs-played-first)
219a7700 676 "I won... Playing first did not help you much!")
d7ab2718
RS
677 ((and (zerop gomoku-number-of-human-wins)
678 (zerop gomoku-number-of-draws)
679 (> gomoku-number-of-emacs-wins 1))
680 "I'm becoming tired of winning...")
681 ("I won.")))
682 ((eq result 'human-won)
683 (setq gomoku-number-of-human-wins (1+ gomoku-number-of-human-wins))
684 (concat "OK, you won this one."
685 (cond
686 (gomoku-human-took-back
687 " I, for one, never take my moves back...")
688 (gomoku-emacs-played-first
ce5a3ac0 689 ".. so what?")
d7ab2718
RS
690 (" Now, let me play first just once."))))
691 ((eq result 'human-resigned)
692 (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
693 "So you resign. That's just one more win for me.")
694 ((eq result 'nobody-won)
695 (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
696 (concat "This is a draw. "
697 (cond
698 (gomoku-human-took-back
699 "I, for one, never take my moves back...")
700 (gomoku-emacs-played-first
701 "Just chance, I guess.")
702 ("Now, let me play first just once."))))
703 ((eq result 'draw-agreed)
704 (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
705 (concat "Draw agreed. "
706 (cond
707 (gomoku-human-took-back
708 "I, for one, never take my moves back...")
709 (gomoku-emacs-played-first
710 "You were lucky.")
711 ("Now, let me play first just once."))))
712 ((eq result 'crash-game)
713 "Sorry, I have been interrupted and cannot resume that game...")))
714 (gomoku-display-statistics)
715 ;;(ding)
716 (setq gomoku-game-in-progress nil))
a2535589
JA
717
718(defun gomoku-crash-game ()
719 "What to do when Emacs detects it has been interrupted."
720 (setq gomoku-emacs-is-computing nil)
721 (gomoku-terminate-game 'crash-game)
722 (sit-for 4) ; Let's see the message
723 (gomoku-prompt-for-other-game))
724\f
725;;;
726;;; INTERACTIVE COMMANDS.
727;;;
728
d9a7a8f5 729;;;###autoload
a2535589
JA
730(defun gomoku (&optional n m)
731 "Start a Gomoku game between you and Emacs.
16f97fc3 732
0472835f 733If a game is in progress, this command allows you to resume it.
a2535589 734If optional arguments N and M are given, an N by M board is used.
d7ab2718 735If prefix arg is given for N, M is prompted for.
a2535589 736
92423534 737You and Emacs play in turn by marking a free square. You mark it with X
0472835f 738and Emacs marks it with O. The winner is the first to get five contiguous
a2535589 739marks horizontally, vertically or in diagonal.
92423534
JB
740
741You play by moving the cursor over the square you choose and hitting
742\\<gomoku-mode-map>\\[gomoku-human-plays].
16f97fc3
RS
743
744This program actually plays a simplified or archaic version of the
745Gomoku game, and ought to be upgraded to use the full modern rules.
746
92423534 747Use \\[describe-mode] for more info."
d7ab2718
RS
748 (interactive (if current-prefix-arg
749 (list (prefix-numeric-value current-prefix-arg)
750 (eval (read-minibuffer "Height: ")))))
428d45d2
GM
751 ;; gomoku-switch-to-window, but without the potential call to gomoku
752 ;; from gomoku-prompt-for-other-game.
753 (if (get-buffer gomoku-buffer-name)
754 (switch-to-buffer gomoku-buffer-name)
755 (when gomoku-game-in-progress
756 (setq gomoku-emacs-is-computing nil)
757 (gomoku-terminate-game 'crash-game)
758 (sit-for 4)
ce5a3ac0 759 (or (y-or-n-p "Another game? ") (error "Chicken!")))
428d45d2
GM
760 (switch-to-buffer gomoku-buffer-name)
761 (gomoku-mode))
a2535589
JA
762 (cond
763 (gomoku-emacs-is-computing
764 (gomoku-crash-game))
d7ab2718
RS
765 ((or (not gomoku-game-in-progress)
766 (<= gomoku-number-of-moves 2))
a2535589
JA
767 (let ((max-width (gomoku-max-width))
768 (max-height (gomoku-max-height)))
769 (or n (setq n max-width))
770 (or m (setq m max-height))
771 (cond ((< n 1)
772 (error "I need at least 1 column"))
773 ((< m 1)
774 (error "I need at least 1 row"))
775 ((> n max-width)
776 (error "I cannot display %d columns in that window" n)))
777 (if (and (> m max-height)
d7ab2718
RS
778 (not (eq m gomoku-saved-board-height))
779 ;; Use EQ because SAVED-BOARD-HEIGHT may be nil
ce5a3ac0 780 (not (y-or-n-p (format "Do you really want %d rows? " m))))
a2535589
JA
781 (setq m max-height)))
782 (message "One moment, please...")
783 (gomoku-start-game n m)
ce5a3ac0 784 (if (y-or-n-p "Do you allow me to play first? ")
a2535589
JA
785 (gomoku-emacs-plays)
786 (gomoku-prompt-for-move)))
ce5a3ac0 787 ((y-or-n-p "Shall we continue our game? ")
a2535589
JA
788 (gomoku-prompt-for-move))
789 (t
790 (gomoku-human-resigns))))
791
792(defun gomoku-emacs-plays ()
793 "Compute Emacs next move and play it."
794 (interactive)
795 (gomoku-switch-to-window)
796 (cond
797 (gomoku-emacs-is-computing
798 (gomoku-crash-game))
799 ((not gomoku-game-in-progress)
800 (gomoku-prompt-for-other-game))
801 (t
802 (message "Let me think...")
803 (let (square score)
804 (setq square (gomoku-strongest-square))
805 (cond ((null square)
806 (gomoku-terminate-game 'nobody-won))
807 (t
808 (setq score (aref gomoku-score-table square))
809 (gomoku-play-move square 6)
810 (cond ((>= score gomoku-winning-threshold)
f5ecf0c9 811 (setq gomoku-emacs-won t) ; for font-lock
d7ab2718 812 (gomoku-find-filled-qtuple square 6)
a2535589
JA
813 (gomoku-terminate-game 'emacs-won))
814 ((zerop score)
815 (gomoku-terminate-game 'nobody-won))
816 ((and (> gomoku-number-of-moves gomoku-draw-limit)
817 (not gomoku-human-refused-draw)
818 (gomoku-offer-a-draw))
819 (gomoku-terminate-game 'draw-agreed))
820 (t
821 (gomoku-prompt-for-move)))))))))
822
d7ab2718
RS
823;; For small square dimensions this is approximate, since though measured in
824;; pixels, event's (X . Y) is a character's top-left corner.
65091471 825(defun gomoku-click (click)
d7ab2718
RS
826 "Position at the square where you click."
827 (interactive "e")
828 (and (windowp (posn-window (setq click (event-end click))))
829 (numberp (posn-point click))
830 (select-window (posn-window click))
831 (setq click (posn-col-row click))
832 (gomoku-goto-xy
833 (min (max (/ (+ (- (car click)
834 gomoku-x-offset
835 1)
836 (window-hscroll)
837 gomoku-square-width
838 (% gomoku-square-width 2)
839 (/ gomoku-square-width 2))
840 gomoku-square-width)
841 1)
842 gomoku-board-width)
843 (min (max (/ (+ (- (cdr click)
844 gomoku-y-offset
845 1)
846 (let ((inhibit-point-motion-hooks t))
847 (count-lines 1 (window-start)))
848 gomoku-square-height
849 (% gomoku-square-height 2)
850 (/ gomoku-square-height 2))
851 gomoku-square-height)
852 1)
853 gomoku-board-height))))
a1506d29 854
d7ab2718 855(defun gomoku-mouse-play (click)
65091471
RS
856 "Play at the square where you click."
857 (interactive "e")
d7ab2718
RS
858 (if (gomoku-click click)
859 (gomoku-human-plays)))
65091471 860
a2535589
JA
861(defun gomoku-human-plays ()
862 "Signal to the Gomoku program that you have played.
863You must have put the cursor on the square where you want to play.
864If the game is finished, this command requests for another game."
865 (interactive)
866 (gomoku-switch-to-window)
867 (cond
868 (gomoku-emacs-is-computing
869 (gomoku-crash-game))
870 ((not gomoku-game-in-progress)
871 (gomoku-prompt-for-other-game))
872 (t
873 (let (square score)
874 (setq square (gomoku-point-square))
875 (cond ((null square)
219a7700 876 (error "Your point is not on a square. Retry!"))
a2535589 877 ((not (zerop (aref gomoku-board square)))
219a7700 878 (error "Your point is not on a free square. Retry!"))
a2535589
JA
879 (t
880 (setq score (aref gomoku-score-table square))
881 (gomoku-play-move square 1)
882 (cond ((and (>= score gomoku-loosing-threshold)
883 ;; Just testing SCORE > THRESHOLD is not enough for
884 ;; detecting wins, it just gives an indication that
885 ;; we confirm with GOMOKU-FIND-FILLED-QTUPLE.
886 (gomoku-find-filled-qtuple square 1))
a2535589
JA
887 (gomoku-terminate-game 'human-won))
888 (t
889 (gomoku-emacs-plays)))))))))
890
891(defun gomoku-human-takes-back ()
892 "Signal to the Gomoku program that you wish to take back your last move."
893 (interactive)
894 (gomoku-switch-to-window)
895 (cond
896 (gomoku-emacs-is-computing
897 (gomoku-crash-game))
898 ((not gomoku-game-in-progress)
899 (message "Too late for taking back...")
900 (sit-for 4)
901 (gomoku-prompt-for-other-game))
902 ((zerop gomoku-number-of-human-moves)
219a7700 903 (message "You have not played yet... Your move?"))
a2535589
JA
904 (t
905 (message "One moment, please...")
906 ;; It is possible for the user to let Emacs play several consecutive
907 ;; moves, so that the best way to know when to stop taking back moves is
908 ;; to count the number of human moves:
909 (setq gomoku-human-took-back t)
910 (let ((number gomoku-number-of-human-moves))
911 (while (= number gomoku-number-of-human-moves)
912 (gomoku-take-back)))
913 (gomoku-prompt-for-move))))
914
915(defun gomoku-human-resigns ()
916 "Signal to the Gomoku program that you may want to resign."
917 (interactive)
918 (gomoku-switch-to-window)
919 (cond
920 (gomoku-emacs-is-computing
921 (gomoku-crash-game))
922 ((not gomoku-game-in-progress)
923 (message "There is no game in progress"))
ce5a3ac0 924 ((y-or-n-p "You mean, you resign? ")
a2535589 925 (gomoku-terminate-game 'human-resigned))
ce5a3ac0 926 ((y-or-n-p "You mean, we continue? ")
a2535589
JA
927 (gomoku-prompt-for-move))
928 (t
929 (gomoku-terminate-game 'human-resigned)))) ; OK. Accept it
930\f
931;;;
932;;; PROMPTING THE HUMAN PLAYER.
933;;;
934
935(defun gomoku-prompt-for-move ()
936 "Display a message asking for Human's move."
937 (message (if (zerop gomoku-number-of-human-moves)
219a7700 938 "Your move? (Move to a free square and hit X, RET ...)"
ce5a3ac0 939 "Your move?"))
a2535589
JA
940 ;; This may seem silly, but if one omits the following line (or a similar
941 ;; one), the cursor may very well go to some place where POINT is not.
937e6a56 942 ;; FIXME: this can't be right!! --Stef
a2535589
JA
943 (save-excursion (set-buffer (other-buffer))))
944
945(defun gomoku-prompt-for-other-game ()
946 "Ask for another game, and start it."
ce5a3ac0 947 (if (y-or-n-p "Another game? ")
a2535589 948 (gomoku gomoku-board-width gomoku-board-height)
ce5a3ac0 949 (error "Chicken!")))
a2535589
JA
950
951(defun gomoku-offer-a-draw ()
0ff9b955 952 "Offer a draw and return t if Human accepted it."
219a7700 953 (or (y-or-n-p "I offer you a draw. Do you accept it? ")
d7ab2718 954 (not (setq gomoku-human-refused-draw t))))
a2535589
JA
955\f
956;;;
957;;; DISPLAYING THE BOARD.
958;;;
959
a2535589
JA
960(defun gomoku-max-width ()
961 "Largest possible board width for the current window."
962 (1+ (/ (- (window-width (selected-window))
963 gomoku-x-offset gomoku-x-offset 1)
964 gomoku-square-width)))
965
966(defun gomoku-max-height ()
967 "Largest possible board height for the current window."
968 (1+ (/ (- (window-height (selected-window))
969 gomoku-y-offset gomoku-y-offset 2)
970 ;; 2 instead of 1 because WINDOW-HEIGHT includes the mode line !
971 gomoku-square-height)))
972
a2535589 973(defun gomoku-point-y ()
d7ab2718
RS
974 "Return the board row where point is."
975 (let ((inhibit-point-motion-hooks t))
976 (1+ (/ (- (count-lines 1 (point)) gomoku-y-offset (if (bolp) 0 1))
977 gomoku-square-height))))
a2535589
JA
978
979(defun gomoku-point-square ()
d7ab2718
RS
980 "Return the index of the square point is on."
981 (let ((inhibit-point-motion-hooks t))
982 (gomoku-xy-to-index (1+ (/ (- (current-column) gomoku-x-offset)
983 gomoku-square-width))
984 (gomoku-point-y))))
a2535589
JA
985
986(defun gomoku-goto-square (index)
987 "Move point to square number INDEX."
988 (gomoku-goto-xy (gomoku-index-to-x index) (gomoku-index-to-y index)))
989
990(defun gomoku-goto-xy (x y)
991 "Move point to square at X, Y coords."
d7ab2718 992 (let ((inhibit-point-motion-hooks t))
9b4c5ecd
GM
993 (goto-char (point-min))
994 (forward-line (+ gomoku-y-offset (* gomoku-square-height (1- y)))))
a2535589
JA
995 (move-to-column (+ gomoku-x-offset (* gomoku-square-width (1- x)))))
996
997(defun gomoku-plot-square (square value)
d7ab2718
RS
998 "Draw 'X', 'O' or '.' on SQUARE depending on VALUE, leave point there."
999 (or (= value 1)
1000 (gomoku-goto-square square))
f5ecf0c9
RS
1001 (let ((inhibit-read-only t)
1002 (inhibit-point-motion-hooks t))
d7ab2718
RS
1003 (insert-and-inherit (cond ((= value 1) ?X)
1004 ((= value 6) ?O)
1005 (?.)))
ef649575 1006 (and (zerop value)
dafef0a3
EZ
1007 (add-text-properties
1008 (1- (point)) (point)
1009 '(mouse-face highlight help-echo "mouse-2: play at this square")))
0720cc69 1010 (delete-char 1)
d7ab2718
RS
1011 (backward-char 1))
1012 (sit-for 0)) ; Display NOW
a2535589
JA
1013
1014(defun gomoku-init-display (n m)
1015 "Display an N by M Gomoku board."
4a07a2af 1016 (buffer-disable-undo (current-buffer))
f5ecf0c9 1017 (let ((inhibit-read-only t)
d7ab2718
RS
1018 (point 1) opoint
1019 (intangible t)
1020 (i m) j x)
1021 ;; Try to minimize number of chars (because of text properties)
1022 (setq tab-width
1023 (if (zerop (% gomoku-x-offset gomoku-square-width))
1024 gomoku-square-width
1025 (max (/ (+ (% gomoku-x-offset gomoku-square-width)
1026 gomoku-square-width 1) 2) 2)))
0720cc69 1027 (erase-buffer)
f5ecf0c9
RS
1028 (newline gomoku-y-offset)
1029 (while (progn
d7ab2718
RS
1030 (setq j n
1031 x (- gomoku-x-offset gomoku-square-width))
1032 (while (>= (setq j (1- j)) 0)
1033 (insert-char ?\t (/ (- (setq x (+ x gomoku-square-width))
1034 (current-column))
1035 tab-width))
1036 (insert-char ? (- x (current-column)))
1037 (if (setq intangible (not intangible))
1038 (put-text-property point (point) 'intangible 2))
1039 (and (zerop j)
1040 (= i (- m 2))
1041 (progn
1042 (while (>= i 3)
1043 (append-to-buffer (current-buffer) opoint (point))
1044 (setq i (- i 2)))
1045 (goto-char (point-max))))
1046 (setq point (point))
1047 (insert ?.)
dafef0a3
EZ
1048 (add-text-properties
1049 point (point)
1050 '(mouse-face highlight
1051 help-echo "mouse-2: play at this square")))
f5ecf0c9 1052 (> (setq i (1- i)) 0))
d7ab2718
RS
1053 (if (= i (1- m))
1054 (setq opoint point))
f5ecf0c9 1055 (insert-char ?\n gomoku-square-height))
d7ab2718
RS
1056 (or (eq (char-after 1) ?.)
1057 (put-text-property 1 2 'point-entered
906f211e 1058 (lambda (x y) (if (bobp) (forward-char)))))
d7ab2718
RS
1059 (or intangible
1060 (put-text-property point (point) 'intangible 2))
1061 (put-text-property point (point) 'point-entered
906f211e 1062 (lambda (x y) (if (eobp) (backward-char))))
d7ab2718
RS
1063 (put-text-property (point-min) (point) 'category 'gomoku-mode))
1064 (gomoku-goto-xy (/ (1+ n) 2) (/ (1+ m) 2)) ; center of the board
f5ecf0c9 1065 (sit-for 0)) ; Display NOW
a2535589
JA
1066
1067(defun gomoku-display-statistics ()
1068 "Obnoxiously display some statistics about previous games in mode line."
1069 ;; We store this string in the mode-line-process local variable.
1070 ;; This is certainly not the cleanest way out ...
1071 (setq mode-line-process
d7ab2718
RS
1072 (format ": Won %d, lost %d%s"
1073 gomoku-number-of-human-wins
1074 gomoku-number-of-emacs-wins
1075 (if (zerop gomoku-number-of-draws)
1076 ""
1077 (format ", drew %d" gomoku-number-of-draws))))
1faea684 1078 (force-mode-line-update))
a2535589
JA
1079
1080(defun gomoku-switch-to-window ()
1081 "Find or create the Gomoku buffer, and display it."
1082 (interactive)
428d45d2
GM
1083 (if (get-buffer gomoku-buffer-name) ; Buffer exists:
1084 (switch-to-buffer gomoku-buffer-name) ; no problem.
1085 (if gomoku-game-in-progress
1086 (gomoku-crash-game)) ; buffer has been killed or something
1087 (switch-to-buffer gomoku-buffer-name) ; Anyway, start anew.
1088 (gomoku-mode)))
a2535589
JA
1089\f
1090;;;
1091;;; CROSSING WINNING QTUPLES.
1092;;;
1093
1094;; When someone succeeds in filling a qtuple, we draw a line over the five
1095;; corresponding squares. One problem is that the program does not know which
1096;; squares ! It only knows the square where the last move has been played and
1097;; who won. The solution is to scan the board along all four directions.
1098
a2535589 1099(defun gomoku-find-filled-qtuple (square value)
0ff9b955 1100 "Return t if SQUARE belongs to a qtuple filled with VALUEs."
a2535589
JA
1101 (or (gomoku-check-filled-qtuple square value 1 0)
1102 (gomoku-check-filled-qtuple square value 0 1)
1103 (gomoku-check-filled-qtuple square value 1 1)
1104 (gomoku-check-filled-qtuple square value -1 1)))
1105
1106(defun gomoku-check-filled-qtuple (square value dx dy)
0ff9b955 1107 "Return t if SQUARE belongs to a qtuple filled with VALUEs along DX, DY."
a2535589
JA
1108 (let ((a 0) (b 0)
1109 (left square) (right square)
d7ab2718 1110 (depl (gomoku-xy-to-index dx dy)))
a2535589
JA
1111 (while (and (> a -4) ; stretch tuple left
1112 (= value (aref gomoku-board (setq left (- left depl)))))
1113 (setq a (1- a)))
d7ab2718 1114 (while (and (< b (+ a 4)) ; stretch tuple right
a2535589
JA
1115 (= value (aref gomoku-board (setq right (+ right depl)))))
1116 (setq b (1+ b)))
d7ab2718
RS
1117 (cond ((= b (+ a 4)) ; tuple length = 5 ?
1118 (gomoku-cross-qtuple (+ square (* a depl)) (+ square (* b depl))
1119 dx dy)
a2535589
JA
1120 t))))
1121
a2535589
JA
1122(defun gomoku-cross-qtuple (square1 square2 dx dy)
1123 "Cross every square between SQUARE1 and SQUARE2 in the DX, DY direction."
1124 (save-excursion ; Not moving point from last square
f5ecf0c9
RS
1125 (let ((depl (gomoku-xy-to-index dx dy))
1126 (inhibit-read-only t)
1127 (inhibit-point-motion-hooks t))
a2535589 1128 ;; WARNING: this function assumes DEPL > 0 and SQUARE2 > SQUARE1
f5ecf0c9 1129 (while (/= square1 square2)
a2535589
JA
1130 (gomoku-goto-square square1)
1131 (setq square1 (+ square1 depl))
1132 (cond
f5ecf0c9
RS
1133 ((= dy 0) ; Horizontal
1134 (forward-char 1)
1135 (insert-char ?- (1- gomoku-square-width) t)
d7ab2718
RS
1136 (delete-region (point) (progn
1137 (skip-chars-forward " \t")
1138 (point))))
f5ecf0c9
RS
1139 ((= dx 0) ; Vertical
1140 (let ((n 1)
1141 (column (current-column)))
a2535589
JA
1142 (while (< n gomoku-square-height)
1143 (setq n (1+ n))
f5ecf0c9
RS
1144 (forward-line 1)
1145 (indent-to column)
1146 (insert-and-inherit ?|))))
1147 ((= dx -1) ; 1st Diagonal
d7ab2718 1148 (indent-to (prog1 (- (current-column) (/ gomoku-square-width 2))
f5ecf0c9
RS
1149 (forward-line (/ gomoku-square-height 2))))
1150 (insert-and-inherit ?/))
1151 (t ; 2nd Diagonal
d7ab2718 1152 (indent-to (prog1 (+ (current-column) (/ gomoku-square-width 2))
f5ecf0c9
RS
1153 (forward-line (/ gomoku-square-height 2))))
1154 (insert-and-inherit ?\\))))))
a2535589
JA
1155 (sit-for 0)) ; Display NOW
1156\f
1157;;;
1158;;; CURSOR MOTION.
1159;;;
f5ecf0c9 1160;; previous-line and next-line don't work right with intangible newlines
a2535589
JA
1161(defun gomoku-move-down ()
1162 "Move point down one row on the Gomoku board."
1163 (interactive)
d7ab2718 1164 (if (< (gomoku-point-y) gomoku-board-height)
05a84156
RS
1165 (let ((column (current-column)))
1166 (forward-line gomoku-square-height)
1167 (move-to-column column))))
a2535589
JA
1168
1169(defun gomoku-move-up ()
1170 "Move point up one row on the Gomoku board."
1171 (interactive)
d7ab2718 1172 (if (> (gomoku-point-y) 1)
05a84156
RS
1173 (let ((column (current-column)))
1174 (forward-line (- 1 gomoku-square-height))
1175 (move-to-column column))))
a2535589
JA
1176
1177(defun gomoku-move-ne ()
1178 "Move point North East on the Gomoku board."
1179 (interactive)
1180 (gomoku-move-up)
f5ecf0c9 1181 (forward-char))
a2535589
JA
1182
1183(defun gomoku-move-se ()
1184 "Move point South East on the Gomoku board."
1185 (interactive)
1186 (gomoku-move-down)
f5ecf0c9 1187 (forward-char))
a2535589
JA
1188
1189(defun gomoku-move-nw ()
1190 "Move point North West on the Gomoku board."
1191 (interactive)
1192 (gomoku-move-up)
f5ecf0c9 1193 (backward-char))
a2535589
JA
1194
1195(defun gomoku-move-sw ()
1196 "Move point South West on the Gomoku board."
1197 (interactive)
1198 (gomoku-move-down)
f5ecf0c9 1199 (backward-char))
a2535589 1200
d7ab2718
RS
1201(defun gomoku-beginning-of-line ()
1202 "Move point to first square on the Gomoku board row."
1203 (interactive)
1204 (move-to-column gomoku-x-offset))
1205
1206(defun gomoku-end-of-line ()
1207 "Move point to last square on the Gomoku board row."
1208 (interactive)
1209 (move-to-column (+ gomoku-x-offset
1210 (* gomoku-square-width (1- gomoku-board-width)))))
1211
d2fe6685
GM
1212(random t)
1213
49116ac0
JB
1214(provide 'gomoku)
1215
1a06eabd 1216;;; gomoku.el ends here